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

PROJECT     := reinvent-field-kits
PROFILE     ?= supernova
# Route 53 public hosted zone in the target account; the dashboard is served at reinvent.<DOMAIN>.
DOMAIN      ?= renkenk.people.aws.dev
REGION      := us-east-1
# Announcements older than this are not synced.
SINCE       ?= 2026-11-30
COST_CENTER ?= poc
COST_DAYS   ?= 7
PORT        ?= 8788
TF          := terraform -chdir=platform/terraform
# Kits that deploy something; a notes-only kit has no Makefile.
KITS        := $(filter-out _template,$(patsubst kits/%/Makefile,%,$(wildcard kits/*/Makefile)))
TAG_KEYS    := Project Environment Owner CostCenter ManagedBy Repository
CFG         := build/platform.json

export AWS_PROFILE := $(PROFILE)
export AWS_REGION  := $(REGION)
export TF_VAR_cost_center := $(COST_CENTER)
export TF_VAR_domain_name := $(DOMAIN)
export TF_VAR_feed_since  := $(SINCE)

.DEFAULT_GOAL := help
.PHONY: help preflight sync queue feed venv dashboard serve init plan deploy outputs kit cost-tags cost destroy-all

help: ## Show targets
	@grep -E '^[a-zA-Z0-9_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "  %-12s %s\n", $$1, $$2}'
	@echo ""
	@echo "  Kits: $(KITS)"
	@echo "  New kit: /field-kit <announcement name or URL> in Claude Code (contract: KIT_SPEC.md)"

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

sync: ## Pull announcements since SINCE into tracker/, including what the feed function in AWS found and triaged
	python3 tracker/sync.py --since $(SINCE) $(if $(wildcard $(CFG)),--feed $$(jq -r .dashboard_url.value $(CFG))/data/feed.json)

queue: ## Add an announcement to the kit queue shown on the dashboard: make queue URL=<announcement url>
	@[ -n "$(URL)" ] || { echo "usage: make queue URL=<announcement url from the dashboard>"; exit 1; }
	@python3 -c 'import json,sys; u=sys.argv[1].rstrip("/"); known={i["url"].rstrip("/") for i in json.load(open("tracker/announcements.json"))["items"]}; sys.exit("not a synced announcement: "+u) if u not in known else None; q=json.load(open("tracker/queue.json")); q+=[] if u in q else [u]; json.dump(q,open("tracker/queue.json","w"),indent=2); print("queued", len(q), "announcements")' "$(URL)"

venv: ## Create .venv with the dashboard's one dependency (markdown)
	@[ -x .venv/bin/python ] || python3 -m venv .venv
	@.venv/bin/pip install -q -r dashboard/requirements.txt

dashboard: venv ## Build dashboard/dist: the announcement table plus each kit's documents, diagram and screenshots as pages
	.venv/bin/python dashboard/build.py

serve: dashboard ## Preview the dashboard at http://127.0.0.1:PORT
	python3 -m http.server $(PORT) --bind 127.0.0.1 --directory dashboard/dist

init: ## terraform init for the shared platform
	$(TF) init -input=false

plan: init ## terraform plan for the shared platform
	$(TF) plan -input=false

deploy: preflight init dashboard ## Apply the shared platform and publish the dashboard (first run about 10 min, run in background)
	$(TF) apply -input=false -auto-approve
	$(MAKE) outputs
	aws s3 sync dashboard/dist s3://$$(jq -r .site_bucket.value $(CFG))/ --delete --exclude 'data/*' --only-show-errors
	aws cloudfront create-invalidation --distribution-id $$(jq -r .distribution_id.value $(CFG)) --paths '/*' --query Invalidation.Status --output text
	@echo "dashboard: $$(jq -r .dashboard_url.value $(CFG))"

outputs: ## Write platform outputs to build/platform.json
	@mkdir -p build
	$(TF) output -json > $(CFG)

feed: preflight ## Run the feed function in AWS now instead of waiting for its hourly schedule
	aws lambda invoke --function-name $$(jq -r .feed_function.value $(CFG)) --cli-read-timeout 320 build/feed-run.json >/dev/null && cat build/feed-run.json && echo

kit: ## Run a kit target: make kit KIT=amazon-ergo T=deploy
	@[ -n "$(KIT)" ] && [ -n "$(T)" ] || { echo "usage: make kit KIT=<slug> T=<target>"; exit 1; }
	$(MAKE) -C kits/$(KIT) $(T)

cost-tags: ## Activate the 6 cost allocation tag keys (account-wide, idempotent, up to 24h to appear)
	aws ce update-cost-allocation-tags-status --region us-east-1 --cost-allocation-tags-status \
	  $(foreach k,$(TAG_KEYS),TagKey=$(k),Status=Active)

cost: ## Cost Explorer: last COST_DAYS days by Project tag for everything in this repo (needs make cost-tags; lags up to 24h)
	@start=$$(date -u -v-$(COST_DAYS)d +%F); end=$$(date -u +%F); \
	echo "Unblended cost $$start to $$end, tag Repository=$(PROJECT)"; \
	aws ce get-cost-and-usage --region us-east-1 --time-period Start=$$start,End=$$end --granularity DAILY --metrics UnblendedCost \
	  --group-by Type=TAG,Key=Project --filter '{"Tags":{"Key":"Repository","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-all: preflight ## Destroy every kit, then the shared platform, and list leftovers (each list should be empty)
	@for k in $(KITS); do echo "== kit $$k"; $(MAKE) -C kits/$$k destroy; done
	@echo "== platform"
	@b=$$($(TF) output -raw site_bucket 2>/dev/null || true); [ -z "$$b" ] || aws s3 rm s3://$$b --recursive --only-show-errors
	@$(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 Repository=$(PROJECT) (KMS keys pending deletion are expected)"
	@aws resourcegroupstaggingapi get-resources --tag-filters Key=Repository,Values=$(PROJECT) \
	  --query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n' | grep -v ':kms:' || true
	@echo "-- log groups:"; aws logs describe-log-groups --log-group-name-prefix /$(PROJECT)/ --query 'logGroups[].logGroupName' --output text
	@echo "-- platform terraform state entries: $$($(TF) state list | wc -l | tr -d ' ')"
