SHELL := /bin/bash
.SHELLFLAGS := -eu -o pipefail -c

KIT         := $(notdir $(CURDIR))
PROJECT     := field-kit-$(KIT)
ROOT        := $(abspath $(CURDIR)/../..)
TF          := terraform -chdir=poc/terraform
PROFILE     ?= supernova
REGION      ?= us-east-1
COST_CENTER ?= poc
COST_DAYS   ?= 7
CFG         := build/config.json
PY          := .venv/bin/python

export AWS_PROFILE := $(PROFILE)
export AWS_REGION  := $(REGION)
export PROJECT
export TF_VAR_project_name := $(PROJECT)
export TF_VAR_cost_center  := $(COST_CENTER)

.DEFAULT_GOAL := help
.PHONY: help preflight venv deploy outputs demo verify screenshots diagram cost destroy

help: ## Show targets
	@grep -E '^[a-zA-Z0-9_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "  %-12s %s\n", $$1, $$2}'

preflight: ## Check credentials and tools
	@out=$$(aws sts get-caller-identity --query Arn --output text 2>&1) || { \
	  echo "AWS profile $(PROFILE) has no valid credentials: run mwinit, then retry."; echo "$$out" | tail -1 | cut -c1-200; exit 1; }; \
	  echo "AWS identity: $$(echo "$$out" | sed -E 's/[0-9]{12}/<account>/')"
	@for t in terraform aws jq python3 curl uv; do command -v $$t >/dev/null || { echo "missing tool: $$t"; exit 1; }; done

venv: .venv/.installed ## Create .venv with the boto3 release that knows the preview APIs

.venv/.installed: poc/requirements.txt
	python3 -m venv .venv
	.venv/bin/pip install -q --upgrade pip -r poc/requirements.txt
	@touch $@

# Terraform first (bucket, policy, role, network, trail), then the script for what
# Terraform has no resources for (workload identity provider, template, runtimes).
deploy: preflight venv ## Create the POC and write its outputs to build/config.json
	$(TF) init -input=false
	$(TF) apply -input=false -auto-approve
	$(MAKE) outputs
	$(PY) poc/agentctl.py deploy

outputs:
	@mkdir -p build
	$(TF) output -json > $(CFG)

demo: ## Scripted demo: the policy, agentA, agentB, then the CloudTrail evidence
	poc/demo.sh

verify: ## Prove the POC works end to end
	poc/verify.sh

screenshots: ## Capture docs/screenshots/*.png from the running POC
	poc/screenshots.sh

diagram: ## Render docs/architecture.png
	python3 docs/diagram.py
	$(ROOT)/shared/diagrams/render.sh docs/architecture.html docs/architecture.png

cost: ## Cost Explorer: last COST_DAYS days by service for this kit (needs make cost-tags at the repo root; lags up to 24h)
	@start=$$(date -u -v-$(COST_DAYS)d +%F); end=$$(date -u +%F); \
	echo "Unblended cost $$start to $$end, tag Project=$(PROJECT)"; \
	aws ce get-cost-and-usage --region us-east-1 --time-period Start=$$start,End=$$end --granularity DAILY --metrics UnblendedCost \
	  --group-by Type=DIMENSION,Key=SERVICE --filter '{"Tags":{"Key":"Project","Values":["$(PROJECT)"]}}' \
	  --query 'ResultsByTime[].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' --output text \
	  | awk -F'\t' '{ s[$$1] += $$2; t += $$2 } END { for (k in s) printf "  %10.2f  %s\n", s[k], k; printf "  %10.2f  TOTAL\n", t }' | sort -rn

# The script first (runtimes, template, provider, runtime log groups), because the
# runtimes hold network interfaces in the VPC that Terraform is about to delete.
destroy: preflight venv ## Remove everything and list leftovers (each list should be empty)
	$(PY) poc/agentctl.py destroy
	$(TF) init -input=false
	@$(TF) apply -destroy -input=false -auto-approve || { echo "destroy failed; retrying once"; $(TF) apply -destroy -input=false -auto-approve; }
	@rm -rf build
	@echo "== Leftover check for tag Project=$(PROJECT) (KMS keys pending deletion are expected)"
	@aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=$(PROJECT) \
	  --query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n' | grep -v ':kms:' || true
	@echo "-- log groups:"; for p in /$(PROJECT)/ /aws/lambda/$(PROJECT); do \
	  aws logs describe-log-groups --log-group-name-prefix $$p --query 'logGroups[].logGroupName' --output text; done
	@$(PY) poc/agentctl.py leftovers
	@echo "-- terraform state entries: $$($(TF) state list | wc -l | tr -d ' ')"
