# =============================================================================
# Xpeditis - production Hetzner
# =============================================================================
# Toutes les cibles s'executent depuis infra/prod/.
#   make help
#
# Les cibles qui touchent la production affichent ce qu'elles vont faire et
# demandent confirmation. Aucune ne s'execute par accident.

SHELL := /bin/bash
.DEFAULT_GOAL := help

KUBECONFIG ?= $(HOME)/.kube/xpeditis-prod.yaml
NAMESPACE  ?= xpeditis-prod
REGISTRY   ?= rg.fr-par.scw.cloud/weworkstudio
export KUBECONFIG

BOLD := \033[1m
RESET := \033[0m

.PHONY: help
help: ## Affiche cette aide
	@printf '$(BOLD)Xpeditis - production$(RESET)\n\n'
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \
	  | awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-22s\033[0m %s\n", $$1, $$2}'
	@printf '\nKUBECONFIG : $(KUBECONFIG)\n'

# --- Infrastructure ---------------------------------------------------------

.PHONY: tf-init
tf-init: ## Terraform : initialisation
	cd terraform && terraform init

.PHONY: tf-plan
tf-plan: ## Terraform : previsualise les changements d'infrastructure
	cd terraform && terraform plan

.PHONY: tf-apply
tf-apply: ## Terraform : applique (cree/modifie les serveurs)
	@printf '$(BOLD)Cette commande modifie l infrastructure de PRODUCTION.$(RESET)\n'
	@read -p 'Continuer ? [oui/non] ' r; [ "$$r" = oui ]
	cd terraform && terraform apply

.PHONY: tf-output
tf-output: ## Terraform : affiche les IP et les enregistrements DNS a creer
	cd terraform && terraform output

.PHONY: cloudflare-ips
cloudflare-ips: ## Compare les rangs IP Cloudflare avec firewall.tf
	bash scripts/refresh-cloudflare-ips.sh

# --- Secrets ----------------------------------------------------------------

.PHONY: secrets-edit
secrets-edit: ## Edite les secrets chiffres (SOPS ouvre votre editeur)
	sops k8s/base/03-secrets.sops.yaml

.PHONY: secrets-apply
secrets-apply: ## Applique les secrets sur le cluster
	bash scripts/secrets-apply.sh

.PHONY: secrets-check
secrets-check: ## Verifie qu'aucun secret en clair n'est pret a etre commite
	@echo '>>> Fichiers suspects dans infra/prod :'
	@! git ls-files --others --cached --exclude-standard . \
	  | grep -E '\.(env|key|pem)$$|secrets\.yaml$$|tfvars$$' \
	  | grep -v '\.example$$' \
	  | grep -v '\.sops\.' \
	  || (echo 'ARRET : des fichiers sensibles sont suivis ou non ignores.'; exit 1)
	@echo 'Aucun fichier sensible detecte.'

# --- Deploiement ------------------------------------------------------------

.PHONY: deploy
deploy: ## Deploie une version (make deploy TAG=prod-a1b2c3d)
	@[ -n "$(TAG)" ] || (echo 'Usage: make deploy TAG=prod-a1b2c3d'; exit 1)
	bash scripts/deploy.sh $(TAG)

.PHONY: deploy-monitoring
deploy-monitoring: ## Deploie ou met a jour la pile d'observabilite
	bash scripts/deploy-monitoring.sh

.PHONY: rollback
rollback: ## Revient a la version precedente (backend + frontend)
	@printf '$(BOLD)Retour arriere de la PRODUCTION.$(RESET)\n'
	@read -p 'Continuer ? [oui/non] ' r; [ "$$r" = oui ]
	kubectl -n $(NAMESPACE) rollout undo deploy/xpeditis-backend
	kubectl -n $(NAMESPACE) rollout undo deploy/xpeditis-frontend
	kubectl -n $(NAMESPACE) rollout status deploy/xpeditis-backend
	kubectl -n $(NAMESPACE) rollout status deploy/xpeditis-frontend

.PHONY: restart
restart: ## Redemarre les pods applicatifs (prise en compte des secrets)
	kubectl -n $(NAMESPACE) rollout restart deploy/xpeditis-backend deploy/xpeditis-frontend

# --- Controles --------------------------------------------------------------

.PHONY: preflight
preflight: ## Controle go / no-go avant ouverture au public
	bash scripts/preflight-check.sh

.PHONY: smoke
smoke: ## Tests de fumee sur les URLs publiques
	bash scripts/smoke-test.sh

.PHONY: status
status: ## Vue d'ensemble de la production
	@printf '\n$(BOLD)Noeuds$(RESET)\n';        kubectl get nodes -o wide
	@printf '\n$(BOLD)Application$(RESET)\n';   kubectl -n $(NAMESPACE) get pods,deploy,hpa
	@printf '\n$(BOLD)Ingress$(RESET)\n';       kubectl -n $(NAMESPACE) get ingress
	@printf '\n$(BOLD)Certificats$(RESET)\n';   kubectl get certificate -A
	@printf '\n$(BOLD)Observabilite$(RESET)\n'; kubectl -n monitoring get pods

.PHONY: logs
logs: ## Journaux du backend en direct
	kubectl -n $(NAMESPACE) logs -l app.kubernetes.io/name=xpeditis-backend -f --tail=100 --max-log-requests=6

.PHONY: logs-frontend
logs-frontend: ## Journaux du frontend en direct
	kubectl -n $(NAMESPACE) logs -l app.kubernetes.io/name=xpeditis-frontend -f --tail=100 --max-log-requests=6

.PHONY: events
events: ## Derniers evenements Kubernetes (diagnostic)
	kubectl -n $(NAMESPACE) get events --sort-by=.lastTimestamp | tail -40

# --- Validation locale ------------------------------------------------------

.PHONY: validate
validate: ## Valide les manifests sans rien appliquer
	@echo '>>> Validation cote serveur (dry-run)'
	@for f in k8s/base/*.yaml k8s/monitoring/*.yaml k8s/cluster/*.yaml; do \
	  case "$$f" in *secrets.template.yaml|*migration-job.yaml) continue;; esac; \
	  printf '  %s\n' "$$f"; \
	  kubectl apply --dry-run=server -f "$$f" >/dev/null || exit 1; \
	done
	@echo '>>> Terraform'
	@cd terraform && terraform validate
	@echo '>>> Scripts shell'
	@command -v shellcheck >/dev/null && shellcheck -S warning scripts/*.sh data-node/backup/*.sh || echo '  shellcheck absent, ignore'
	@echo 'Validation terminee.'
