.DEFAULT_GOAL := help

## —— Help ————————————————————————————————————————
help: ## Affiche la liste des commandes disponibles
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'

## —— Docker ——————————————————————————————————————
build_dev: ## Build les images Docker pour le dev
	docker compose -f docker-compose-dev.yml build

build_prod: ## Build les images Docker pour la prod
	docker compose -f docker-compose-prod.yml build

start_dev: ## Lance les containers dev
	docker compose -f docker-compose-dev.yml up

start_prod: ## Lance les containers prod en background
	docker compose -f docker-compose-prod.yml up -d

stop_dev: ## Arrete les containers dev
	docker compose -f docker-compose-dev.yml down

purge_dev: ## Arrete et purge les containers dev (volumes inclus)
	docker compose -f docker-compose-dev.yml down -v

stop_prod: ## Arrete les containers prod
	docker compose -f docker-compose-prod.yml down

## —— Git ——————————————————————————————————————————
pull_dev: ## Pull les images Docker dev
	docker compose -f docker-compose-dev.yml pull

pull_prod: ## Pull les images Docker prod
	docker compose -f docker-compose-prod.yml pull

## —— Ansible —————————————————————————————————————
deploy_prod: ## Deploy en prod via Ansible (demande le vault password)
	 ansible-playbook ansible/deploy.yml -i ansible/hosts.ini --ask-vault-pass

## —— Install ——————————————————————————————————————
install_dev: ## Install les dependances dev via Docker
	docker compose -f docker-compose-dev.yml exec php composer install
	docker compose -f docker-compose-dev.yml exec bun bun install

install_prod: ## Install les dependances et build les assets pour la prod
	docker compose -f docker-compose-prod.yml exec php composer install --no-dev --optimize-autoloader
	bun install
	bun run build

## —— Tests ————————————————————————————————————————
test_db_create: ## Cree la base de donnees de test
	docker compose -f docker-compose-dev.yml exec database psql -U app -d crm_siteconseil -tc "SELECT 1 FROM pg_database WHERE datname = 'crm_siteconseil_test'" | grep -q 1 || \
		docker compose -f docker-compose-dev.yml exec database psql -U app -d crm_siteconseil -c "CREATE DATABASE crm_siteconseil_test"

test_db_schema: ## Cree/met a jour le schema de la base de test
	docker compose -f docker-compose-dev.yml exec php php bin/console doctrine:schema:update --force --env=test

test_db_migrate: ## Execute les migrations sur la base de test
	docker compose -f docker-compose-dev.yml exec php php bin/console doctrine:migrations:migrate --no-interaction --env=test

test_db_reset: ## Supprime et recree la base de test depuis zero
	docker compose -f docker-compose-dev.yml exec database psql -U app -d crm_siteconseil -c "DROP DATABASE IF EXISTS crm_siteconseil_test"
	docker compose -f docker-compose-dev.yml exec database psql -U app -d crm_siteconseil -c "CREATE DATABASE crm_siteconseil_test"
	$(MAKE) test_db_schema

test_db_setup: ## Setup complet de la base de test (cree si besoin + schema)
	$(MAKE) test_db_create
	$(MAKE) test_db_schema

run_test: ## Lance les tests PHP et JS via Docker dev
	docker compose -f docker-compose-dev.yml exec php php bin/phpunit
	docker compose -f docker-compose-dev.yml exec bun bun run test

run_test_php: ## Lance uniquement les tests PHP via Docker dev
	docker compose -f docker-compose-dev.yml exec php php bin/phpunit

run_test_js: ## Lance uniquement les tests JS via Docker dev
	docker compose -f docker-compose-dev.yml exec bun bun run test

run_test_coverage_php: ## Lance les tests PHP avec couverture via Docker dev
	docker compose -f docker-compose-dev.yml exec php php bin/phpunit --coverage-text --coverage-html=coverage/php

run_test_coverage_js: ## Lance les tests JS avec couverture via Docker dev
	docker compose -f docker-compose-dev.yml exec bun bun run test -- --coverage

run_test_file: ## Lance un fichier de test PHP specifique (usage: make run_test_file FILE=tests/Service/AuditServiceTest.php)
	docker compose -f docker-compose-dev.yml exec php php bin/phpunit $(FILE)

## —— PWA —————————————————————————————————————————
pwa_dev: ## Compile les assets PWA en dev via Docker
	docker compose -f docker-compose-dev.yml exec php php bin/console pwa:compile

pwa_prod: ## Compile les assets PWA en prod via Docker
	docker compose -f docker-compose-prod.yml exec php php bin/console pwa:compile --env=prod

## —— Traductions ——————————————————————————————————
trans: ## Traduit les fichiers YAML FR vers EN/ES/DE/IT via LibreTranslate (Docker dev)
	docker compose -f docker-compose-dev.yml exec php php bin/console app:translate
	docker compose -f docker-compose-dev.yml stop libretranslate

trans_prod: ## Traduit les fichiers YAML FR vers EN/ES/DE/IT via LibreTranslate (Docker prod)
	docker compose -f docker-compose-prod.yml exec -T php php bin/console app:translate --env=prod
	docker compose -f docker-compose-prod.yml stop libretranslate

## —— Symfony ——————————————————————————————————————
entity: ## Creer ou modifier une entite via Docker dev
	docker compose -f docker-compose-dev.yml exec php php bin/console make:entity

## —— Database ——————————————————————————————————————
migration_dev: ## Genere une migration via Docker dev
	docker compose -f docker-compose-dev.yml exec php php bin/console make:migration

migrate_dev: ## Execute les migrations via Docker dev
	docker compose -f docker-compose-dev.yml exec php php bin/console doctrine:migrations:migrate --no-interaction

force_sql_dev: ## Force la mise a jour du schema de la base de donnees dev
	docker compose -f docker-compose-dev.yml exec php php bin/console doctrine:schema:update --force

migrate_prod: ## Execute les migrations en prod via Docker
	docker compose -f docker-compose-prod.yml exec php php bin/console doctrine:migrations:migrate --no-interaction --env=prod

## —— Cache ————————————————————————————————————————
clear_prod: ## Clear le cache Symfony et le pool opcache en prod via Docker
	docker compose -f docker-compose-prod.yml exec php php bin/console cache:clear --env=prod
	docker compose -f docker-compose-prod.yml exec php php bin/console cache:pool:clear --all --env=prod

purge_liip_dev: ## Purge le cache Liip Imagine en dev via Docker
	docker compose -f docker-compose-dev.yml exec php php bin/console liip:imagine:cache:remove

purge_liip_prod: ## Purge le cache Liip Imagine en prod via Docker
	docker compose -f docker-compose-prod.yml exec php php bin/console liip:imagine:cache:remove --env=prod

## —— Maintenance ——————————————————————————————————
maintenance_on: ## Active le mode maintenance
	touch public/.update

maintenance_off: ## Desactive le mode maintenance
	rm -f public/.update


## —— Qualite ──────────────────────────────────────
qa: lint phpstan cs_check ## Lance tous les checks qualite (lint + analyse + sécurité)

qa_full: qa test_coverage infection phpmetrics ## Lance la suite complète (qa + tests coverage + mutation + metrics)

lint: ## Lance tous les linters (Twig, YAML, Container, ESLint, Stylelint)
	docker compose -f docker-compose-dev.yml exec php php bin/console lint:twig templates/
	docker compose -f docker-compose-dev.yml exec php php bin/console lint:yaml config/
	docker compose -f docker-compose-dev.yml exec php php bin/console lint:container
	docker compose -f docker-compose-dev.yml exec bun bunx eslint assets/ --ext .js,.ts
	docker compose -f docker-compose-dev.yml exec bun bunx stylelint "assets/**/*.scss"

phpstan: ## Lance PHPStan niveau 6
	docker compose -f docker-compose-dev.yml exec php vendor/bin/phpstan analyse src/ --level=6 --memory-limit=512M

phpstan_report: ## Lance PHPStan et genere le rapport JSON pour SonarQube
	docker compose -f docker-compose-dev.yml exec php sh -c 'mkdir -p var/reports && vendor/bin/phpstan analyse src/ --level=6 --memory-limit=512M --no-progress --error-format=json > var/reports/phpstan-report.json || true'
	sed -i 's|/app/||g' var/reports/phpstan-report.json

cs_check: ## Verifie le code style (dry-run)
	docker compose -f docker-compose-dev.yml exec php vendor/bin/php-cs-fixer fix --dry-run --diff

cs_fix: ## Corrige automatiquement le code style
	docker compose -f docker-compose-dev.yml exec php vendor/bin/php-cs-fixer fix

eslint: ## Lance ESLint sur les assets JS/TS
	docker compose -f docker-compose-dev.yml exec bun bunx eslint assets/ --ext .js,.ts

eslint_fix: ## Corrige automatiquement les erreurs ESLint
	docker compose -f docker-compose-dev.yml exec bun bunx eslint assets/ --ext .js,.ts --fix

eslint_report: ## Lance ESLint et genere le rapport JSON pour SonarQube
	docker compose -f docker-compose-dev.yml exec bun sh -c 'mkdir -p var/reports && bunx eslint assets/ --ext .js,.ts -f json -o var/reports/eslint-report.json || true'

stylelint: ## Lance Stylelint sur les fichiers SCSS
	docker compose -f docker-compose-dev.yml exec bun bunx stylelint "assets/**/*.scss"

stylelint_fix: ## Corrige automatiquement les erreurs Stylelint
	docker compose -f docker-compose-dev.yml exec bun bunx stylelint "assets/**/*.scss" --fix

test_coverage: ## Lance les tests PHP avec couverture (clover + HTML + JUnit)
	docker compose -f docker-compose-dev.yml exec php sh -c 'mkdir -p var/reports && php -d memory_limit=512M bin/phpunit --testdox --log-junit var/reports/phpunit.xml --coverage-clover var/reports/coverage.xml --coverage-html var/reports/coverage-html --coverage-text'
	sed -i 's|/app/||g' var/reports/coverage.xml

infection: ## Lance Infection (mutation testing) sur les tests PHP
	docker compose -f docker-compose-dev.yml exec php sh -c 'mkdir -p var/reports && vendor/bin/infection --threads=4 --min-msi=50 --min-covered-msi=60 --logger-json=var/reports/infection-report.json || true'

infection_full: test_coverage infection ## Lance les tests avec couverture puis Infection

phpmetrics: ## Genere le rapport PHPMetrics HTML
	docker compose -f docker-compose-dev.yml exec php sh -c 'mkdir -p var/reports && curl -sLo /tmp/phpmetrics.phar https://github.com/phpmetrics/PhpMetrics/releases/latest/download/phpmetrics.phar && php /tmp/phpmetrics.phar --report-html=var/reports/phpmetrics-report src/'

hadolint: ## Lance Hadolint sur les Dockerfiles
	docker run --rm -v "$(PWD):/app" -w /app hadolint/hadolint hadolint docker/php/dev/Dockerfile
	docker run --rm -v "$(PWD):/app" -w /app hadolint/hadolint hadolint docker/php/prod/Dockerfile

hadolint_report: ## Lance Hadolint sur le Dockerfile prod et genere le rapport JSON
	mkdir -p var/reports
	# Use -i (interactive) and ensure no TTY is allocated to avoid escape characters
	docker run --rm -v "$(PWD):/app" -w /app hadolint/hadolint \
		hadolint docker/php/prod/Dockerfile -f json > var/reports/hadolint-raw.json || true

	# Cleanup: Ensure the file isn't empty and contains valid JSON brackets
	@if [ ! -s var/reports/hadolint-raw.json ]; then echo "[]" > var/reports/hadolint-raw.json; fi
	# Optional: Strip potential Docker/System noise from the file
	@sed -i 's/^[^{|[ ]*//g' var/reports/hadolint-raw.json
audit: ## Lance l'audit de securite Composer
	docker compose -f docker-compose-dev.yml exec php composer audit

reports: phpstan_report eslint_report run_test_coverage_js test_coverage hadolint_report phpmetrics ## Genere tous les rapports pour SonarQube

## —— SonarQube ————————————————————————————————————
sonar: reports ## Genere les rapports puis lance le scan SonarQube
	docker run --rm -v "$(PWD):/usr/src" -e SONAR_HOST_URL=https://sn.esy-web.dev -e SONAR_TOKEN=sqp_3e02f4de4c73f6d9cc5b6ce6546a7871d6ac0756 sonarsource/sonar-scanner-cli

sonar_quick: ## Lance le scan SonarQube sans regenerer les rapports
	docker run --rm -v "$(PWD):/usr/src" -e SONAR_HOST_URL=https://sn.esy-web.dev -e SONAR_TOKEN=$(shell grep SONAR_TOKEN .env.local 2>/dev/null | cut -d= -f2 || echo "") sonarsource/sonar-scanner-cli
