# search-assistant - GCP Deployment
# Generated by: bedsheet deploy --target gcp
#
# Quick Start: make init && make deploy
# That's it! Your agent will be live on Cloud Run.

.PHONY: help init auth setup deploy deploy-all status url logs dev test clean destroy
.SILENT: help

PROJECT = bedsheet-e2e-test
REGION = me-west1
SERVICE = search_assistant
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
NC = \033[0m # No Color

help:
	@printf "$(BLUE)search-assistant - GCP Deployment$(NC)\n"
	@printf "\n"
	@printf "$(GREEN)Quick Start:$(NC)\n"
	@printf "  make init      - One-time setup (auth, APIs, infrastructure)\n"
	@printf "  make deploy    - Deploy your agent to Cloud Run\n"
	@printf "  make url       - Get your agent's URL\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 locally 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 destroy   - Remove all deployed resources\n"
	@printf "  make clean     - Clean local build artifacts\n"

# =============================================================================
# INITIALIZATION - One-time setup
# =============================================================================

init: _check_gcloud _check_auth _check_adc _check_project _create_env _enable_apis _setup_infra
	@printf "\n$(GREEN)✅ Initialization complete!$(NC)\n"
	@printf "\n"
	@printf "Next: Run $(BLUE)make deploy$(NC) to deploy your agent.\n"
	@printf "Or:   Run $(BLUE)make dev$(NC) to test locally first.\n"

_check_gcloud:
	@printf "$(BLUE)Checking gcloud CLI...$(NC)\n"
	@which gcloud > /dev/null 2>&1 || { \
		printf "$(RED)❌ gcloud CLI not found$(NC)\n"; \
		printf "\nInstall it from: https://cloud.google.com/sdk/docs/install\n"; \
		printf "Then run: $(BLUE)make init$(NC) again\n"; \
		exit 1; \
	}
	@printf "   ✅ gcloud CLI installed\n"

_check_auth:
	@printf "$(BLUE)Checking gcloud authentication...$(NC)\n"
	@if ! gcloud auth list --filter=status:ACTIVE --format="value(account)" 2>/dev/null | head -1 | grep -q .; then \
		printf "$(YELLOW)⚡ Opening browser to log in to Google Cloud...$(NC)\n"; \
		gcloud auth login --quiet; \
	fi
	@printf "   ✅ Authenticated as: $$(gcloud auth list --filter=status:ACTIVE --format='value(account)' | head -1)\n"

_check_adc:
	@printf "$(BLUE)Checking Application Default Credentials...$(NC)\n"
	@if [ ! -f ~/.config/gcloud/application_default_credentials.json ]; then \
		printf "$(YELLOW)⚡ Opening browser to set up Vertex AI access...$(NC)\n"; \
		gcloud auth application-default login --quiet; \
	fi
	@printf "   ✅ ADC configured\n"

_check_project:
	@printf "$(BLUE)Setting GCP project...$(NC)\n"
	@gcloud config set project $(PROJECT) --quiet
	@printf "   ✅ Project: $(PROJECT)\n"

_create_env:
	@printf "$(BLUE)Creating environment file...$(NC)\n"
	@if [ ! -f .env ]; then \
		cp .env.example .env; \
		printf "   ✅ Created .env from template\n"; \
	else \
		printf "   ✅ .env already exists\n"; \
	fi

_enable_apis:
	@printf "$(BLUE)Enabling GCP APIs (this may take a minute)...$(NC)\n"
	@gcloud services enable \
		run.googleapis.com \
		aiplatform.googleapis.com \
		artifactregistry.googleapis.com \
		cloudbuild.googleapis.com \
		logging.googleapis.com \
		--quiet
	@printf "   ✅ APIs enabled: Cloud Run, Vertex AI, Artifact Registry, Cloud Build, Logging\n"

_setup_infra:
	@printf "$(BLUE)Creating infrastructure with Terraform...$(NC)\n"
	@cd terraform && terraform init -input=false > /dev/null 2>&1
	@cd terraform && terraform apply -auto-approve -input=false
	@printf "   ✅ Infrastructure ready\n"

# =============================================================================
# AUTHENTICATION - Run if you need to re-authenticate
# =============================================================================

auth:
	@printf "$(BLUE)Setting up authentication...$(NC)\n"
	@gcloud auth login
	@gcloud auth application-default login
	@gcloud config set project $(PROJECT)
	@printf "$(GREEN)✅ Authentication complete$(NC)\n"

# =============================================================================
# DEPLOYMENT
# =============================================================================

deploy: _preflight_quick
	@printf "$(BLUE)🚀 Deploying $(SERVICE) to Cloud Run...$(NC)\n"
	@printf "\n"
	@gcloud builds submit \
		--config cloudbuild.yaml \
		--project $(PROJECT) \
		--substitutions=_REGION=$(REGION),_SERVICE=$(SERVICE)
	@printf "\n$(GREEN)✅ Deployment complete!$(NC)\n"
	@printf "\n"
	@$(MAKE) url --no-print-directory
	@$(MAKE) _open_browser --no-print-directory

_open_browser:
	@URL=$$(gcloud run services describe $(SERVICE) --region $(REGION) --project $(PROJECT) --format='value(status.url)' 2>/dev/null); \
	if [ -n "$$URL" ]; then \
		printf "\n$(BLUE)Opening browser...$(NC)\n"; \
		(which xdg-open > /dev/null 2>&1 && xdg-open "$$URL") || \
		(which open > /dev/null 2>&1 && open "$$URL") || \
		printf "Open in browser: $$URL\n"; \
	fi

deploy-all: init deploy
	@printf "\n$(GREEN)🎉 Your agent is live!$(NC)\n"

_preflight_quick:
	@test -f .env || { printf "$(RED)❌ Run 'make init' first$(NC)\n"; exit 1; }
	@gcloud auth list --filter=status:ACTIVE --format="value(account)" 2>/dev/null | head -1 | grep -q . || { printf "$(RED)❌ Run 'make init' first$(NC)\n"; exit 1; }

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

status:
	@printf "$(BLUE)Deployment Status$(NC)\n"
	@printf "================\n"
	@printf "Project:  $(PROJECT)\n"
	@printf "Region:   $(REGION)\n"
	@printf "Service:  $(SERVICE)\n"
	@printf "\n"
	@if gcloud run services describe $(SERVICE) --region $(REGION) --project $(PROJECT) --format="value(status.url)" 2>/dev/null | grep -q .; then \
		printf "$(GREEN)● Running$(NC)\n"; \
		printf "URL: $$(gcloud run services describe $(SERVICE) --region $(REGION) --format='value(status.url)')\n"; \
		printf "\nLatest revision:\n"; \
		gcloud run revisions list --service $(SERVICE) --region $(REGION) --limit 1 --format="table(name,ready,active)"; \
	else \
		printf "$(YELLOW)○ Not deployed$(NC)\n"; \
		printf "\nRun $(BLUE)make deploy$(NC) to deploy your agent.\n"; \
	fi

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

logs:
	@printf "$(BLUE)Streaming logs for $(SERVICE)...$(NC)\n"
	@printf "(Press Ctrl+C to stop)\n\n"
	@gcloud run logs tail $(SERVICE) --region $(REGION) --project $(PROJECT)

# =============================================================================
# LOCAL 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"
	@GOOGLE_CLOUD_PROJECT=$(PROJECT) GOOGLE_CLOUD_LOCATION=$(REGION) python -m google.adk.cli web .

test:
	@printf "$(BLUE)Testing agent via CLI...$(NC)\n"
	@GOOGLE_CLOUD_PROJECT=$(PROJECT) GOOGLE_CLOUD_LOCATION=$(REGION) python -m google.adk.cli run agent.agent

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

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

destroy:
	@printf "$(RED)⚠️  This will delete ALL deployed resources:$(NC)\n"
	@printf "   - Cloud Run service\n"
	@printf "   - Service account\n"
	@printf "   - Artifact Registry repository\n"
	@printf "   - Container images\n"
	@printf "\n"
	@read -p "Are you sure? (yes/no): " confirm && [ "$$confirm" = "yes" ] || { printf "Aborted.\n"; exit 1; }
	@printf "\n$(BLUE)Destroying infrastructure...$(NC)\n"
	@cd terraform && terraform destroy -auto-approve
	@printf "\n$(GREEN)✅ All resources destroyed$(NC)\n"

# =============================================================================
# ADVANCED / TERRAFORM
# =============================================================================

tf-init:
	cd terraform && terraform init

tf-plan:
	cd terraform && terraform plan

tf-apply:
	cd terraform && terraform apply

tf-output:
	cd terraform && terraform output