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

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

.DEFAULT_GOAL := help
.PHONY: help preflight deploy outputs 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; do command -v $$t >/dev/null || { echo "missing tool: $$t"; exit 1; }; done

deploy: preflight ## Create the POC and write its outputs to build/config.json
	$(TF) init -input=false
	$(TF) apply -input=false -auto-approve
	$(MAKE) outputs

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

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

destroy: preflight ## Remove everything and list leftovers (each list should be empty)
	$(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
	@echo "-- terraform state entries: $$($(TF) state list | wc -l | tr -d ' ')"
