# investment-advisor - GCP Deployment
# Generated by: bedsheet deploy --target gcp
#
# QUICK START:
#   1. make setup    - Configure your GCP project (guided)
#   2. make deploy   - Deploy your agent to Cloud Run
#
# Your agent will be live on Cloud Run in minutes!

.PHONY: help setup deploy dev test logs status url clean destroy
.SILENT: help _banner

# Configuration (set in terraform.tfvars or override here)
PROJECT ?= bedsheet-e2e-test
REGION ?= europe-west1
SERVICE = investment-advisor
IMAGE = $(REGION)-docker.pkg.dev/$(PROJECT)/$(SERVICE)-repo/$(SERVICE)

# Colors for output
GREEN = \033[0;32m
YELLOW = \033[0;33m
RED = \033[0;31m
BLUE = \033[0;34m
CYAN = \033[0;36m
NC = \033[0m

# =============================================================================
# HELP
# =============================================================================

help:
	@printf "\n"
	@printf "$(CYAN)╔══════════════════════════════════════════════════════════════╗$(NC)\n"
	@printf "$(CYAN)║$(NC)  $(BLUE)investment-advisor$(NC) - GCP Deployment                          $(CYAN)║$(NC)\n"
	@printf "$(CYAN)╚══════════════════════════════════════════════════════════════╝$(NC)\n"
	@printf "\n"
	@printf "$(GREEN)QUICK START$(NC)\n"
	@printf "  make setup      Configure GCP project (run once, guided)\n"
	@printf "  make deploy     Deploy agent to Cloud Run\n"
	@printf "\n"
	@printf "$(GREEN)DEVELOPMENT$(NC)\n"
	@printf "  make dev        Run locally with ADK Dev UI (http://localhost:8000)\n"
	@printf "  make test       Test agent via CLI\n"
	@printf "  make logs       Stream Cloud Run logs\n"
	@printf "\n"
	@printf "$(GREEN)MANAGEMENT$(NC)\n"
	@printf "  make status     Show deployment status\n"
	@printf "  make url        Get your agent's URL\n"
	@printf "  make destroy    Remove all resources\n"
	@printf "\n"

_banner:
	@printf "\n"
	@printf "$(CYAN)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━$(NC)\n"
	@printf "  $(BLUE)investment-advisor$(NC) - Cloud Run Deployment\n"
	@printf "$(CYAN)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━$(NC)\n"
	@printf "\n"

# =============================================================================
# SETUP - Guided one-time configuration
# =============================================================================

setup: _banner _check_tools _setup_auth _setup_project _setup_terraform
	@printf "\n"
	@printf "$(GREEN)╔══════════════════════════════════════════════════════════════╗$(NC)\n"
	@printf "$(GREEN)║  ✅ Setup Complete!                                          ║$(NC)\n"
	@printf "$(GREEN)╚══════════════════════════════════════════════════════════════╝$(NC)\n"
	@printf "\n"
	@printf "Next steps:\n"
	@printf "  1. Run $(BLUE)make deploy$(NC) to deploy your agent\n"
	@printf "  2. Or run $(BLUE)make dev$(NC) to test locally first\n"
	@printf "\n"

_check_tools:
	@printf "$(BLUE)Step 1/4: Checking required tools...$(NC)\n"
	@printf "\n"
	@# Check gcloud
	@if ! which gcloud > /dev/null 2>&1; then \
		printf "$(RED)✗ gcloud CLI not found$(NC)\n"; \
		printf "\n"; \
		printf "Install the Google Cloud SDK:\n"; \
		printf "  $(CYAN)https://cloud.google.com/sdk/docs/install$(NC)\n"; \
		printf "\n"; \
		exit 1; \
	fi
	@printf "  $(GREEN)✓$(NC) gcloud CLI installed\n"
	@# Check terraform
	@if ! which terraform > /dev/null 2>&1; then \
		printf "$(RED)✗ Terraform not found$(NC)\n"; \
		printf "\n"; \
		printf "Install Terraform:\n"; \
		printf "  $(CYAN)https://developer.hashicorp.com/terraform/install$(NC)\n"; \
		printf "\n"; \
		exit 1; \
	fi
	@printf "  $(GREEN)✓$(NC) Terraform installed\n"
	@printf "\n"

_setup_auth:
	@printf "$(BLUE)Step 2/4: Setting up authentication...$(NC)\n"
	@printf "\n"
	@# Check if already authenticated
	@if ! gcloud auth list --filter=status:ACTIVE --format="value(account)" 2>/dev/null | head -1 | grep -q .; then \
		printf "$(YELLOW)Opening browser for Google Cloud login...$(NC)\n"; \
		gcloud auth login; \
	fi
	@printf "  $(GREEN)✓$(NC) Logged in as: $$(gcloud auth list --filter=status:ACTIVE --format='value(account)' | head -1)\n"
	@printf "\n"
	@# Setup ADC for Terraform
	@if [ ! -f ~/.config/gcloud/application_default_credentials.json ]; then \
		printf "$(YELLOW)Setting up Application Default Credentials for Terraform...$(NC)\n"; \
		gcloud auth application-default login; \
	fi
	@printf "  $(GREEN)✓$(NC) Application Default Credentials configured\n"
	@printf "\n"

_setup_project:
	@printf "$(BLUE)Step 3/4: Configuring GCP project...$(NC)\n"
	@printf "\n"
	@# Check if PROJECT is set
	@if [ -z "$(PROJECT)" ] || [ "$(PROJECT)" = "your-project-id" ]; then \
		printf "$(YELLOW)Which GCP project should we use?$(NC)\n"; \
		printf "\n"; \
		printf "Your available projects:\n"; \
		gcloud projects list --format="table(projectId,name)" 2>/dev/null | head -10 || true; \
		printf "\n"; \
		printf "Enter your GCP Project ID: "; \
		read project_id; \
		if [ -z "$$project_id" ]; then \
			printf "$(RED)Project ID is required$(NC)\n"; \
			exit 1; \
		fi; \
		printf "\n"; \
		sed -i.bak "s/^PROJECT ?=.*/PROJECT ?= $$project_id/" Makefile && rm -f Makefile.bak; \
		sed -i.bak "s/project_id = .*/project_id = \"$$project_id\"/" terraform/terraform.tfvars 2>/dev/null || \
			echo "project_id = \"$$project_id\"" > terraform/terraform.tfvars; \
		rm -f terraform/terraform.tfvars.bak; \
		gcloud config set project $$project_id; \
		printf "  $(GREEN)✓$(NC) Project set to: $$project_id\n"; \
	else \
		gcloud config set project $(PROJECT) --quiet; \
		printf "  $(GREEN)✓$(NC) Using project: $(PROJECT)\n"; \
	fi
	@printf "\n"
	@# Set ADC quota project
	@gcloud auth application-default set-quota-project $$(gcloud config get-value project) --quiet 2>/dev/null || true
	@printf "  $(GREEN)✓$(NC) ADC quota project configured\n"
	@printf "\n"

_setup_terraform:
	@printf "$(BLUE)Step 4/5: Enabling required GCP APIs...$(NC)\n"
	@printf "\n"
	@printf "  Enabling APIs (this may take a minute)...\n"
	@gcloud services enable \
		run.googleapis.com \
		artifactregistry.googleapis.com \
		aiplatform.googleapis.com \
		cloudbuild.googleapis.com \
		logging.googleapis.com \
		monitoring.googleapis.com \
		iam.googleapis.com \
		iamcredentials.googleapis.com \
		--quiet 2>/dev/null || true
	@printf "  $(GREEN)✓$(NC) APIs enabled\n"
	@printf "\n"
	@printf "$(BLUE)Step 5/5: Initializing infrastructure...$(NC)\n"
	@printf "\n"
	@# Create terraform.tfvars if it doesn't exist
	@if [ ! -f terraform/terraform.tfvars ]; then \
		printf "project_id = \"$$(gcloud config get-value project)\"\n" > terraform/terraform.tfvars; \
		printf "region     = \"$(REGION)\"\n" >> terraform/terraform.tfvars; \
	fi
	@# Create .env if it doesn't exist
	@if [ ! -f .env ]; then \
		cp .env.example .env 2>/dev/null || true; \
	fi
	@# Initialize Terraform
	@printf "  Initializing Terraform...\n"
	@cd terraform && terraform init -input=false > /dev/null 2>&1
	@printf "  $(GREEN)✓$(NC) Terraform initialized\n"
	@printf "\n"
	@# Show what will be created
	@printf "  Planning infrastructure...\n"
	@cd terraform && terraform plan -input=false -compact-warnings 2>/dev/null | grep -E "^  #|^Plan:" | head -20 || true
	@printf "\n"
	@printf "  $(GREEN)✓$(NC) Infrastructure plan ready\n"
	@printf "\n"

# =============================================================================
# DEPLOY - Build and deploy to Cloud Run
# =============================================================================

deploy: _preflight _build _post_deploy
	@printf "\n"
	@printf "$(GREEN)╔══════════════════════════════════════════════════════════════╗$(NC)\n"
	@printf "$(GREEN)║  🚀 Deployment Complete!                                     ║$(NC)\n"
	@printf "$(GREEN)╚══════════════════════════════════════════════════════════════╝$(NC)\n"
	@printf "\n"
	@$(MAKE) url --no-print-directory

_preflight:
	@printf "$(BLUE)Preflight checks...$(NC)\n"
	@# Check Terraform is initialized
	@if [ ! -d terraform/.terraform ]; then \
		printf "$(YELLOW)Terraform not initialized. Running setup...$(NC)\n"; \
		$(MAKE) setup; \
	fi
	@# Check project is set (strip ANSI codes from terraform output, fallback to gcloud)
	@PROJECT_ID=$$(cd terraform && terraform output -raw project_id 2>/dev/null | tr -d '\033' | sed 's/\[[0-9;]*m//g' | grep -E '^[a-z][-a-z0-9]*[a-z0-9]$$' || gcloud config get-value project 2>/dev/null); \
	if [ -z "$$PROJECT_ID" ] || [ "$$PROJECT_ID" = "your-project-id" ]; then \
		printf "$(RED)GCP project not configured. Run 'make setup' first.$(NC)\n"; \
		exit 1; \
	fi
	@printf "  $(GREEN)✓$(NC) Ready to deploy\n"
	@printf "\n"

_build:
	@printf "$(BLUE)Deploying via Cloud Build...$(NC)\n"
	@printf "\n"
	@printf "  Cloud Build will:\n"
	@printf "    1. Enable required GCP APIs\n"
	@printf "    2. Create Artifact Registry repo\n"
	@printf "    3. Create service account\n"
	@printf "    4. Build container image\n"
	@printf "    5. Deploy to Cloud Run\n"
	@printf "\n"
	@PROJECT_ID=$$(gcloud config get-value project 2>/dev/null); \
	printf "  Submitting to Cloud Build (project: $$PROJECT_ID)...\n"; \
	gcloud builds submit \
		--config cloudbuild.yaml \
		--project $$PROJECT_ID \
		--substitutions=_REGION=$(REGION),_SERVICE=$(SERVICE) \
		--quiet
	@printf "  $(GREEN)✓$(NC) Deployment complete\n"
	@printf "\n"

_apply:
	@printf "$(BLUE)Applying infrastructure...$(NC)\n"
	@printf "\n"
	@cd terraform && terraform apply -auto-approve -input=false -compact-warnings
	@printf "\n"
	@printf "  $(GREEN)✓$(NC) Infrastructure applied\n"
	@printf "\n"

_post_deploy:
	@printf "$(BLUE)Verifying deployment...$(NC)\n"
	@# Get Cloud Run service URL via gcloud
	@SERVICE_URL=$$(gcloud run services describe $(SERVICE) --region $(REGION) --format 'value(status.url)' 2>/dev/null); \
	if [ -n "$$SERVICE_URL" ]; then \
		printf "  $(GREEN)✓$(NC) Service is live at $$SERVICE_URL\n"; \
	else \
		printf "  $(YELLOW)⚠$(NC) Service not found yet. It may still be deploying.\n"; \
	fi
	@printf "\n"

# =============================================================================
# DEVELOPMENT
# =============================================================================

dev:
	@printf "$(BLUE)Starting ADK Dev UI locally...$(NC)\n"
	@printf "\n"
	@printf "Open $(GREEN)http://localhost:8000$(NC) in your browser\n"
	@printf "\n"
	@PROJECT_ID=$$(gcloud config get-value project 2>/dev/null); \
	GOOGLE_CLOUD_PROJECT=$$PROJECT_ID GOOGLE_CLOUD_LOCATION=global GOOGLE_GENAI_USE_VERTEXAI=True uv run python -m google.adk.cli web .

test:
	@printf "$(BLUE)Testing agent via CLI...$(NC)\n"
	@PROJECT_ID=$$(gcloud config get-value project 2>/dev/null); \
	GOOGLE_CLOUD_PROJECT=$$PROJECT_ID GOOGLE_CLOUD_LOCATION=global GOOGLE_GENAI_USE_VERTEXAI=True uv run python -m google.adk.cli run agent.agent

# =============================================================================
# STATUS & INFO
# =============================================================================

status:
	@printf "\n"
	@printf "$(BLUE)Deployment Status$(NC)\n"
	@printf "══════════════════\n"
	@printf "\n"
	@if [ -d terraform/.terraform ]; then \
		cd terraform && terraform output 2>/dev/null || printf "$(YELLOW)Run 'make setup' to initialize$(NC)\n"; \
	else \
		printf "$(YELLOW)Not initialized. Run 'make setup' first.$(NC)\n"; \
	fi
	@printf "\n"

url:
	@SERVICE_URL=$$(gcloud run services describe $(SERVICE) --region $(REGION) --format 'value(status.url)' 2>/dev/null); \
	if [ -n "$$SERVICE_URL" ]; then \
		printf "\n"; \
		printf "$(GREEN)🌐 Your agent is live at:$(NC)\n"; \
		printf "\n"; \
		printf "   $$SERVICE_URL\n"; \
		printf "\n"; \
		printf "$(BLUE)Test it:$(NC)\n"; \
		printf "   curl -X POST $$SERVICE_URL/invoke \\\\\n"; \
		printf "     -H 'Content-Type: application/json' \\\\\n"; \
		printf "     -d '{\"message\": \"Hello!\"}'\n"; \
		printf "\n"; \
	else \
		printf "$(YELLOW)Agent not deployed yet. Run 'make deploy' first.$(NC)\n"; \
	fi

logs:
	@printf "$(BLUE)Streaming logs...$(NC)\n"
	@printf "(Press Ctrl+C to stop)\n\n"
	@PROJECT_ID=$$(cd terraform && terraform output -raw project_id 2>/dev/null | tr -d '\033' | sed 's/\[[0-9;]*m//g' | grep -E '^[a-z][-a-z0-9]*[a-z0-9]$$' || gcloud config get-value project 2>/dev/null); \
	gcloud run logs tail $(SERVICE) --region $(REGION) --project $$PROJECT_ID

# =============================================================================
# CLEANUP
# =============================================================================

clean:
	@printf "$(BLUE)Cleaning local artifacts...$(NC)\n"
	@rm -rf __pycache__ agent/__pycache__ terraform/.terraform.lock.hcl
	@printf "  $(GREEN)✓$(NC) Clean\n"

destroy:
	@printf "\n"
	@printf "$(RED)⚠️  WARNING: This will PERMANENTLY DELETE all resources:$(NC)\n"
	@printf "\n"
	@printf "   • Cloud Run service\n"
	@printf "   • Service account\n"
	@printf "   • Artifact Registry (all container images)\n"
	@printf "   • IAM bindings\n"
	@printf "   • Logging metrics\n"
	@printf "\n"
	@read -p "Type 'destroy' to confirm: " confirm && [ "$$confirm" = "destroy" ] || { printf "\nAborted.\n"; exit 1; }
	@printf "\n"
	@printf "$(BLUE)Destroying infrastructure...$(NC)\n"
	@cd terraform && terraform destroy -auto-approve
	@printf "\n"
	@printf "$(GREEN)✓ All resources destroyed$(NC)\n"
	@printf "\n"

# =============================================================================
# TERRAFORM COMMANDS (Advanced)
# =============================================================================

tf-init:
	cd terraform && terraform init

tf-plan:
	cd terraform && terraform plan

tf-apply:
	cd terraform && terraform apply

tf-output:
	cd terraform && terraform output

tf-destroy:
	cd terraform && terraform destroy