.PHONY: help proto build test docker-build docker-up docker-down deploy-k8s clean lint fmt

# Default target
.DEFAULT_GOAL := help

# Variables
GO := go
DOCKER := docker
DOCKER_COMPOSE := docker-compose
PROTOC := protoc
GOPATH := $(shell go env GOPATH)
PROJECT_NAME := mpc-system
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
BUILD_TIME := $(shell date -u '+%Y-%m-%d_%H:%M:%S')
LDFLAGS := -ldflags "-X main.Version=$(VERSION) -X main.BuildTime=$(BUILD_TIME)"

# Services
SERVICES := session-coordinator message-router server-party account

help: ## Show this help
	@echo "MPC Distributed Signature System - Build Commands"
	@echo ""
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'

# ============================================
# Development Commands
# ============================================

init: ## Initialize the project (install tools)
	@echo "Installing tools..."
	$(GO) install google.golang.org/protobuf/cmd/protoc-gen-go@latest
	$(GO) install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
	$(GO) install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@latest
	$(GO) install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
	$(GO) mod download
	@echo "Tools installed successfully!"

proto: ## Generate protobuf code
	@echo "Generating protobuf..."
	@mkdir -p api/grpc/coordinator/v1
	@mkdir -p api/grpc/router/v1
	$(PROTOC) --go_out=. --go_opt=paths=source_relative \
		--go-grpc_out=. --go-grpc_opt=paths=source_relative \
		api/proto/*.proto
	@echo "Protobuf generated successfully!"

fmt: ## Format Go code
	@echo "Formatting code..."
	$(GO) fmt ./...
	@echo "Code formatted!"

lint: ## Run linter
	@echo "Running linter..."
	golangci-lint run ./...
	@echo "Lint completed!"

# ============================================
# Build Commands
# ============================================

build: ## Build all services
	@echo "Building all services..."
	@for service in $(SERVICES); do \
		echo "Building $$service..."; \
		$(GO) build $(LDFLAGS) -o bin/$$service ./services/$$service/cmd/server; \
	done
	@echo "All services built successfully!"

build-session-coordinator: ## Build session-coordinator service
	@echo "Building session-coordinator..."
	$(GO) build $(LDFLAGS) -o bin/session-coordinator ./services/session-coordinator/cmd/server

build-message-router: ## Build message-router service
	@echo "Building message-router..."
	$(GO) build $(LDFLAGS) -o bin/message-router ./services/message-router/cmd/server

build-server-party: ## Build server-party service
	@echo "Building server-party..."
	$(GO) build $(LDFLAGS) -o bin/server-party ./services/server-party/cmd/server

build-account: ## Build account service
	@echo "Building account service..."
	$(GO) build $(LDFLAGS) -o bin/account ./services/account/cmd/server

clean: ## Clean build artifacts
	@echo "Cleaning..."
	rm -rf bin/
	rm -rf vendor/
	$(GO) clean -cache
	@echo "Cleaned!"

# ============================================
# Test Commands
# ============================================

test: ## Run all tests
	@echo "Running tests..."
	$(GO) test -v -race -coverprofile=coverage.out ./...
	@echo "Tests completed!"

test-unit: ## Run unit tests only
	@echo "Running unit tests..."
	$(GO) test -v -race -short ./...
	@echo "Unit tests completed!"

test-integration: ## Run integration tests
	@echo "Running integration tests..."
	$(GO) test -v -race -tags=integration ./tests/integration/...
	@echo "Integration tests completed!"

test-e2e: ## Run end-to-end tests
	@echo "Running e2e tests..."
	$(GO) test -v -race -tags=e2e ./tests/e2e/...
	@echo "E2E tests completed!"

test-coverage: ## Run tests with coverage report
	@echo "Running tests with coverage..."
	$(GO) test -v -race -coverprofile=coverage.out -covermode=atomic ./...
	$(GO) tool cover -html=coverage.out -o coverage.html
	@echo "Coverage report generated: coverage.html"

test-docker-integration: ## Run integration tests in Docker
	@echo "Starting test infrastructure..."
	$(DOCKER_COMPOSE) -f tests/docker-compose.test.yml up -d postgres-test redis-test rabbitmq-test
	@echo "Waiting for services..."
	sleep 10
	$(DOCKER_COMPOSE) -f tests/docker-compose.test.yml run --rm migrate
	$(DOCKER_COMPOSE) -f tests/docker-compose.test.yml run --rm integration-tests
	@echo "Integration tests completed!"

test-docker-e2e: ## Run E2E tests in Docker
	@echo "Starting full test environment..."
	$(DOCKER_COMPOSE) -f tests/docker-compose.test.yml up -d
	@echo "Waiting for services to be healthy..."
	sleep 30
	$(DOCKER_COMPOSE) -f tests/docker-compose.test.yml run --rm e2e-tests
	@echo "E2E tests completed!"

test-docker-all: ## Run all tests in Docker
	@echo "Running all tests in Docker..."
	$(MAKE) test-docker-integration
	$(MAKE) test-docker-e2e
	@echo "All Docker tests completed!"

test-clean: ## Clean up test resources
	@echo "Cleaning up test resources..."
	$(DOCKER_COMPOSE) -f tests/docker-compose.test.yml down -v --remove-orphans
	rm -f coverage.out coverage.html
	@echo "Test cleanup completed!"

# ============================================
# Docker Commands
# ============================================

docker-build: ## Build Docker images
	@echo "Building Docker images..."
	$(DOCKER_COMPOSE) build
	@echo "Docker images built!"

docker-up: ## Start all services with Docker Compose
	@echo "Starting services..."
	$(DOCKER_COMPOSE) up -d
	@echo "Services started!"

docker-down: ## Stop all services
	@echo "Stopping services..."
	$(DOCKER_COMPOSE) down
	@echo "Services stopped!"

docker-logs: ## View logs
	$(DOCKER_COMPOSE) logs -f

docker-ps: ## View running containers
	$(DOCKER_COMPOSE) ps

docker-clean: ## Remove all containers and volumes
	@echo "Cleaning Docker resources..."
	$(DOCKER_COMPOSE) down -v --remove-orphans
	@echo "Docker resources cleaned!"

# ============================================
# Database Commands
# ============================================

db-migrate: ## Run database migrations
	@echo "Running database migrations..."
	psql -h localhost -U mpc_user -d mpc_system -f migrations/001_init_schema.sql
	@echo "Migrations completed!"

db-reset: ## Reset database (drop and recreate)
	@echo "Resetting database..."
	psql -h localhost -U mpc_user -d postgres -c "DROP DATABASE IF EXISTS mpc_system"
	psql -h localhost -U mpc_user -d postgres -c "CREATE DATABASE mpc_system"
	$(MAKE) db-migrate
	@echo "Database reset completed!"

# ============================================
# Mobile SDK Commands
# ============================================

build-android-sdk: ## Build Android SDK
	@echo "Building Android SDK..."
	gomobile bind -target=android -o sdk/android/mpcsdk.aar ./sdk/go
	@echo "Android SDK built!"

build-ios-sdk: ## Build iOS SDK
	@echo "Building iOS SDK..."
	gomobile bind -target=ios -o sdk/ios/Mpcsdk.xcframework ./sdk/go
	@echo "iOS SDK built!"

build-mobile-sdk: build-android-sdk build-ios-sdk ## Build all mobile SDKs

# ============================================
# Kubernetes Commands
# ============================================

deploy-k8s: ## Deploy to Kubernetes
	@echo "Deploying to Kubernetes..."
	kubectl apply -f k8s/
	@echo "Deployed!"

undeploy-k8s: ## Remove from Kubernetes
	@echo "Removing from Kubernetes..."
	kubectl delete -f k8s/
	@echo "Removed!"

# ============================================
# Development Helpers
# ============================================

run-coordinator: ## Run session-coordinator locally
	$(GO) run ./services/session-coordinator/cmd/server

run-router: ## Run message-router locally
	$(GO) run ./services/message-router/cmd/server

run-party: ## Run server-party locally
	$(GO) run ./services/server-party/cmd/server

run-account: ## Run account service locally
	$(GO) run ./services/account/cmd/server

dev: docker-up ## Start development environment
	@echo "Development environment is ready!"
	@echo "  PostgreSQL: localhost:5432"
	@echo "  Redis: localhost:6379"
	@echo "  RabbitMQ: localhost:5672 (management: localhost:15672)"
	@echo "  Consul: localhost:8500"

# ============================================
# Release Commands
# ============================================

release: lint test build ## Create a release
	@echo "Creating release $(VERSION)..."
	@echo "Release created!"

version: ## Show version
	@echo "Version: $(VERSION)"
	@echo "Build Time: $(BUILD_TIME)"
