# Sendico Development Environment - Makefile
# Docker Compose + Makefile build system

.PHONY: help init build up down restart logs rebuild clean vault-init proto

COMPOSE := docker compose -f docker-compose.dev.yml --env-file .env.dev
SERVICE ?=

# Colors
GREEN  := \033[0;32m
YELLOW := \033[1;33m
NC     := \033[0m

help:
	@echo "$(GREEN)Sendico Development Environment$(NC)"
	@echo ""
	@echo "$(YELLOW)Quick Start:$(NC)"
	@echo "  make init               Initialize dev environment (first time setup)"
	@echo "  make up                 Start all services"
	@echo "  make vault-init         Initialize Vault (if services need it)"
	@echo ""
	@echo "$(YELLOW)Main Commands:$(NC)"
	@echo "  make build              Build all service images"
	@echo "  make down               Stop all services"
	@echo "  make restart            Restart all services"
	@echo "  make status             Show service status"
	@echo "  make logs [SERVICE=x]   View logs (all or specific service)"
	@echo "  make rebuild SERVICE=x  Rebuild specific service"
	@echo "  make clean              Remove all containers and volumes"
	@echo ""
	@echo "$(YELLOW)Selective Operations:$(NC)"
	@echo "  make infra-up           Start infrastructure only (mongo, nats, vault)"
	@echo "  make services-up        Start application services only"
	@echo "  make list-services      List all available services"
	@echo ""
	@echo "$(YELLOW)Build Groups:$(NC)"
	@echo "  make build-core         Build core services (discovery, ledger, fees, documents)"
	@echo "  make build-fx           Build FX services (oracle, ingestor)"
	@echo "  make build-payments     Build payment orchestrator"
	@echo "  make build-gateways     Build gateway services (chain, tron, mntx, tgsettle)"
	@echo "  make build-api          Build API services (notification, bff)"
	@echo "  make build-frontend     Build Flutter web frontend"
	@echo ""
	@echo "$(YELLOW)Development:$(NC)"
	@echo "  make proto              Generate protobuf code"
	@echo "  make health             Check service health"
	@echo ""
	@echo "Examples:"
	@echo "  make logs SERVICE=dev-ledger"
	@echo "  make rebuild SERVICE=dev-ledger"

# First-time initialization
init:
	@echo "$(GREEN)Initializing development environment...$(NC)"
	@if [ ! -f ci/dev/mongo-key/mongo.key ]; then \
		echo "$(YELLOW)Generating MongoDB keyfile...$(NC)"; \
		openssl rand -base64 756 | tr -d '\n' > ci/dev/mongo-key/mongo.key; \
		chmod 400 ci/dev/mongo-key/mongo.key; \
	fi
	@if [ ! -f .env.dev ]; then \
		echo "$(YELLOW)Creating .env.dev with default values...$(NC)"; \
		echo "# Sendico Development Environment Configuration" > .env.dev; \
		echo "# Simple plaintext credentials for infrastructure" >> .env.dev; \
		echo "" >> .env.dev; \
		echo "# MongoDB Configuration" >> .env.dev; \
		echo "MONGO_USER=dev_root" >> .env.dev; \
		echo "MONGO_PASSWORD=dev_password_123" >> .env.dev; \
		echo "" >> .env.dev; \
		echo "# NATS Configuration" >> .env.dev; \
		echo "NATS_USER=dev_nats" >> .env.dev; \
		echo "NATS_PASSWORD=nats_password_123" >> .env.dev; \
		echo "" >> .env.dev; \
		echo "# Vault Configuration (for application data only)" >> .env.dev; \
		echo "VAULT_ADDR=http://dev-vault:8200" >> .env.dev; \
	fi
	@echo "$(GREEN)Verifying .env.dev...$(NC)"
	@cat .env.dev | grep -q "MONGO_USER=" || (echo "$(YELLOW)Error: .env.dev is incomplete$(NC)" && exit 1)
	@echo "$(GREEN)Running proto generation...$(NC)"
	@./generate_protos.sh
	@echo "$(GREEN)Building Docker images...$(NC)"
	@$(COMPOSE) build
	@echo "$(GREEN)✅ Initialization complete!$(NC)"
	@echo ""
	@echo "Next steps:"
	@echo "  1. make up          # Start services"
	@echo "  2. make vault-init  # Initialize Vault (if needed)"

# Build all images
build:
	@echo "$(GREEN)Building all service images...$(NC)"
	@./generate_protos.sh
	@$(COMPOSE) build

# Start all services
up:
	@echo "$(GREEN)Starting development environment...$(NC)"
	@$(COMPOSE) up -d
	@echo ""
	@echo "$(GREEN)✅ Development environment started!$(NC)"
	@echo ""
	@echo "Services:"
	@echo "  MongoDB:    mongodb://dev_root:dev_password_123@localhost:27017/admin?replicaSet=dev-rs"
	@echo "  NATS:       nats://dev_nats:nats_password_123@localhost:4222"
	@echo "  NATS UI:    http://localhost:8222"
	@echo "  Vault:      http://localhost:8200 (run 'make vault-init' first)"
	@echo ""
	@echo "View logs:    make logs [SERVICE=name]"
	@echo "Stop:         make down"

# Stop all services
down:
	@echo "$(YELLOW)Stopping development environment...$(NC)"
	@$(COMPOSE) down

# Restart all services
restart:
	@echo "$(YELLOW)Restarting services...$(NC)"
	@$(COMPOSE) restart

# View logs
logs:
ifdef SERVICE
	@$(COMPOSE) logs -f $(SERVICE)
else
	@$(COMPOSE) logs -f
endif

# Rebuild specific service
rebuild:
ifndef SERVICE
	$(error SERVICE is required: make rebuild SERVICE=ledger)
endif
	@echo "$(GREEN)Rebuilding $(SERVICE)...$(NC)"
	@$(COMPOSE) build $(SERVICE)
	@$(COMPOSE) up -d --force-recreate $(SERVICE)
	@echo "$(GREEN)✅ $(SERVICE) rebuilt$(NC)"
	@echo "View logs: make logs SERVICE=$(SERVICE)"

# Generate protobuf code
proto:
	@echo "$(GREEN)Generating protobuf code...$(NC)"
	@./generate_protos.sh
	@echo "$(GREEN)✅ Protobuf generation complete$(NC)"

# Clean everything
clean:
	@echo "$(YELLOW)WARNING: This will remove all containers and volumes!$(NC)"
	@read -p "Are you sure? [y/N] " -n 1 -r; \
	echo; \
	if [[ $$REPLY =~ ^[Yy]$$ ]]; then \
		$(COMPOSE) down -v --remove-orphans; \
		docker system prune -f; \
		echo "$(GREEN)✅ Cleanup complete$(NC)"; \
	fi

# Initialize Vault (first time only)
vault-init:
	@echo "$(GREEN)Initializing Vault...$(NC)"
	@echo "$(YELLOW)Make sure Vault is running: make up$(NC)"
	@sleep 2
	@echo "Checking Vault status..."
	@docker exec dev-vault vault status || echo "Vault not initialized yet"
	@echo ""
	@echo "$(GREEN)Initializing Vault with 1 key share...$(NC)"
	@docker exec dev-vault vault operator init -key-shares=1 -key-threshold=1 > vault-keys.txt || echo "Vault already initialized"
	@if [ -f vault-keys.txt ]; then \
		echo "$(GREEN)✅ Vault initialized!$(NC)"; \
		echo ""; \
		echo "$(YELLOW)IMPORTANT: Save vault-keys.txt securely!$(NC)"; \
		echo "It contains the unseal key and root token."; \
		echo ""; \
		UNSEAL_KEY=$$(grep 'Unseal Key 1:' vault-keys.txt | awk '{print $$NF}'); \
		echo "Unsealing Vault..."; \
		docker exec dev-vault vault operator unseal $$UNSEAL_KEY; \
		echo ""; \
		echo "$(GREEN)✅ Vault is unsealed and ready!$(NC)"; \
		echo ""; \
		echo "Root token: $$(grep 'Initial Root Token:' vault-keys.txt | awk '{print $$NF}')"; \
		echo "UI: http://localhost:8200"; \
	fi

# Infrastructure only (mongo + nats + vault)
infra-up:
	@echo "$(GREEN)Starting infrastructure only...$(NC)"
	@$(COMPOSE) up -d dev-mongo-1 dev-mongo-2 dev-mongo-3 dev-nats dev-vault
	@$(COMPOSE) up dev-mongo-init

# Services only (assumes infra is running)
services-up:
	@echo "$(GREEN)Starting application services...$(NC)"
	@$(COMPOSE) up -d \
		dev-discovery \
		dev-fx-oracle \
		dev-fx-ingestor \
		dev-billing-fees \
		dev-billing-documents \
		dev-ledger \
		dev-payments-orchestrator \
		dev-chain-gateway \
		dev-tron-gateway \
		dev-mntx-gateway \
		dev-tgsettle-gateway \
		dev-notification \
		dev-bff \
		dev-frontend

# Status check
status:
	@$(COMPOSE) ps

# List all services
list-services:
	@echo "$(GREEN)Infrastructure Services:$(NC)"
	@echo "  - dev-mongo-1, dev-mongo-2, dev-mongo-3 (MongoDB Replica Set)"
	@echo "  - dev-nats (NATS with JetStream)"
	@echo "  - dev-vault (Vault for application secrets)"
	@echo ""
	@echo "$(GREEN)Application Services:$(NC)"
	@echo "  - dev-discovery         :9407  (Service Registry)"
	@echo "  - dev-fx-oracle         :50051, :9400 (FX Quotes)"
	@echo "  - dev-fx-ingestor       :9102  (FX Rate Ingestion)"
	@echo "  - dev-billing-fees      :50060, :9402 (Fee Calculation)"
	@echo "  - dev-billing-documents :50061, :9409 (Billing Documents)"
	@echo "  - dev-ledger            :50052, :9401 (Double-Entry Ledger)"
	@echo "  - dev-payments-orchestrator :50062, :9403 (Payment Orchestration)"
	@echo "  - dev-chain-gateway     :50070, :9404 (EVM Blockchain Gateway)"
	@echo "  - dev-tron-gateway      :50071, :9408 (TRON Blockchain Gateway)"
	@echo "  - dev-mntx-gateway      :50075, :9405, :8084 (Card Payouts)"
	@echo "  - dev-tgsettle-gateway  :50080, :9406 (Telegram Settlements)"
	@echo "  - dev-notification      :8081  (Notifications)"
	@echo "  - dev-bff               :8080  (Backend for Frontend)"
	@echo "  - dev-frontend          :3000  (Flutter Web UI)"

# Health check all services
health:
	@echo "$(GREEN)Checking service health...$(NC)"
	@$(COMPOSE) ps --format json | grep -v "State" || echo "Run 'make up' first"

# Build specific service group
build-infra:
	@echo "$(GREEN)Building infrastructure images...$(NC)"
	# Infrastructure uses official images, nothing to build

build-core:
	@echo "$(GREEN)Building core services...$(NC)"
	@$(COMPOSE) build dev-discovery dev-ledger dev-billing-fees dev-billing-documents

build-fx:
	@echo "$(GREEN)Building FX services...$(NC)"
	@$(COMPOSE) build dev-fx-oracle dev-fx-ingestor

build-payments:
	@echo "$(GREEN)Building payment services...$(NC)"
	@$(COMPOSE) build dev-payments-orchestrator

build-gateways:
	@echo "$(GREEN)Building gateway services...$(NC)"
	@$(COMPOSE) build dev-chain-gateway dev-tron-gateway dev-mntx-gateway dev-tgsettle-gateway

build-api:
	@echo "$(GREEN)Building API services...$(NC)"
	@$(COMPOSE) build dev-notification dev-bff

build-frontend:
	@echo "$(GREEN)Building frontend...$(NC)"
	@$(COMPOSE) build dev-frontend
