# Makefile

.PHONY: help dev prod build logs shell clean migrate test lint format

# Variables
COMPOSE_FILE_DEV := docker-compose.yml
COMPOSE_FILE_PROD := docker-compose.prod.yml
DOCKER_COMPOSE_DEV := docker compose -f $(COMPOSE_FILE_DEV)
DOCKER_COMPOSE_PROD := docker compose -f $(COMPOSE_FILE_PROD)
BACKEND_CONTAINER_DEV := eiro-backend
BACKEND_CONTAINER_PROD := eiro-backend-prod
FRONTEND_CONTAINER_DEV := eiro-frontend
FRONTEND_CONTAINER_PROD := eiro-frontend-prod
POSTGRES_CONTAINER_DEV := eiro-postgres
POSTGRES_CONTAINER_PROD := eiro-postgres-prod

# Colors
CYAN := \033[0;36m
GREEN := \033[0;32m
YELLOW := \033[0;33m
RED := \033[0;31m
NC := \033[0m # No Color

## ============ HELP ============
help:
	@echo "$(CYAN)╔════════════════════════════════════════════════════════════╗$(NC)"
	@echo "$(CYAN)║                  Eiro - Make Commands                      ║$(NC)"
	@echo "$(CYAN)╚════════════════════════════════════════════════════════════╝$(NC)"
	@echo ""
	@echo "$(GREEN)GENERAL$(NC)"
	@echo "  $(YELLOW)make help$(NC)                 - Affiche cette aide"
	@echo ""
	@echo "$(GREEN)🚀 DEVELOPMENT$(NC)"
	@echo "  $(YELLOW)make dev-up$(NC)               - Démarrer l'env dev"
	@echo "  $(YELLOW)make dev-down$(NC)             - Arrêter l'env dev"
	@echo "  $(YELLOW)make dev-restart$(NC)          - Restart l'env dev"
	@echo "  $(YELLOW)make dev-build$(NC)            - Build l'env dev"
	@echo "  $(YELLOW)make dev-logs$(NC)             - Afficher les logs dev"
	@echo "  $(YELLOW)make dev-logs-backend$(NC)     - Logs du backend seulement"
	@echo "  $(YELLOW)make dev-logs-frontend$(NC)    - Logs du frontend seulement"
	@echo "  $(YELLOW)make dev-shell-backend$(NC)    - Shell Django dans le backend"
	@echo "  $(YELLOW)make dev-shell-frontend$(NC)   - Shell du frontend"
	@echo ""
	@echo "$(GREEN)🏗️  MIGRATION & DB (Dev)$(NC)"
	@echo "  $(YELLOW)make dev-migrate$(NC)          - Exécuter les migrations"
	@echo "  $(YELLOW)make dev-makemigrations$(NC)   - Créer les migrations"
	@echo "  $(YELLOW)make dev-createsuperuser$(NC)  - Créer un superuser"
	@echo "  $(YELLOW)make dev-fresh-db$(NC)         - Réinitialiser la BD (destructif)"
	@echo "  $(YELLOW)make dev-dumpdata$(NC)         - Faire un dump des données"
	@echo "  $(YELLOW)make dev-loaddata$(NC)         - Charger les données"
	@echo "  $(YELLOW)make dev-db-backup$(NC)        - Backup BD de dev"
	@echo ""
	@echo "$(GREEN)🧪 TESTING & QUALITY (Dev)$(NC)"
	@echo "  $(YELLOW)make dev-test$(NC)             - Lancer les tests"
	@echo "  $(YELLOW)make dev-test-backend$(NC)     - Tests du backend seulement"
	@echo "  $(YELLOW)make dev-test-frontend$(NC)    - Tests du frontend seulement"
	@echo "  $(YELLOW)make dev-coverage$(NC)         - Coverage report"
	@echo "  $(YELLOW)make dev-lint$(NC)             - Linter le code (pylint, eslint)"
	@echo "  $(YELLOW)make dev-format$(NC)           - Formater le code (black, prettier)"
# 	@echo ""
# 	@echo "$(GREEN)🔒 PRODUCTION$(NC)"
# 	@echo "  $(YELLOW)make prod-build$(NC)           - Construire les images prod"
# 	@echo "  $(YELLOW)make prod-up$(NC)              - Démarrer l'env prod"
# 	@echo "  $(YELLOW)make prod-down$(NC)            - Arrêter l'env prod"
# 	@echo "  $(YELLOW)make prod-logs$(NC)            - Afficher les logs prod"
# 	@echo "  $(YELLOW)make prod-migrate$(NC)         - Migrations en production"
# 	@echo "  $(YELLOW)make prod-backup$(NC)          - Backup la BD prod"
# 	@echo "  $(YELLOW)make prod-restore$(NC)         - Restore depuis un backup"
	@echo ""
	@echo "$(GREEN)🐳 DOCKER$(NC)"
	@echo "  $(YELLOW)make docker-clean$(NC)         - Nettoyer images/volumes/containers inutilisés"
	@echo "  $(YELLOW)make docker-prune$(NC)         - Prune agressif (attention!)"
# 	@echo ""
# 	@echo "$(GREEN)📦 BUILD$(NC)"
# 	@echo "  $(YELLOW)make build-backend$(NC)        - Builder le backend"
# 	@echo "  $(YELLOW)make build-frontend$(NC)       - Builder le frontend"
# 	@echo "  $(YELLOW)make build-all$(NC)            - Builder tout"
# 	@echo ""
# 	@echo "$(GREEN)🚀 DEPLOYMENT$(NC)"
# 	@echo "  $(YELLOW)make deploy-staging$(NC)       - Déployer en staging"
# 	@echo "  $(YELLOW)make deploy-prod$(NC)          - Déployer en production"
# 	@echo "  $(YELLOW)make deploy-rollback$(NC)      - Rollback version précédente"
	@echo ""

## ============ DEVELOPMENT ============

dev-up:
	@echo "$(GREEN)▶ Démarrage de l'environnement de développement...$(NC)"
	$(DOCKER_COMPOSE_DEV) up -d
	@echo "$(GREEN)✓ Environnement démarré$(NC)"
	@echo "  Backend:  http://localhost:8000"
	@echo "  Frontend: http://localhost:3000"
	@echo "  API:      http://localhost:8000/api/v1/"
	@echo "  Admin:    http://localhost:8000/admin"

dev-down:
	@echo "$(GREEN)▶ Arrêt de l'environnement de développement...$(NC)"
	$(DOCKER_COMPOSE_DEV) down
	@echo "$(GREEN)✓ Environnement arrêté$(NC)"

dev-restart:
	$(DOCKER_COMPOSE_DEV) down && $(DOCKER_COMPOSE_DEV) up --build
	@echo "$(GREEN)✓ Environnement redémarré$(NC)"

dev-build:
	$(DOCKER_COMPOSE_DEV) up --build -d
	@echo "$(GREEN)✓ Environnement buildé$(NC)"

dev-logs:
	$(DOCKER_COMPOSE_DEV) logs -f

dev-logs-backend:
	$(DOCKER_COMPOSE_DEV) logs -f $(BACKEND_CONTAINER_DEV)

dev-logs-frontend:
	$(DOCKER_COMPOSE_DEV) logs -f $(FRONTEND_CONTAINER_DEV)

dev-logs-postgres:
	$(DOCKER_COMPOSE_DEV) logs -f $(POSTGRES_CONTAINER_DEV)

dev-shell-backend:
	@echo "$(CYAN)Ouverture d'un shell Django...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec $(BACKEND_CONTAINER_DEV) python manage.py shell

dev-shell-frontend:
	@echo "$(CYAN)Ouverture d'un shell dans le frontend...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec $(FRONTEND_CONTAINER_DEV) sh

dev-bash-backend:
	$(DOCKER_COMPOSE_DEV) exec $(BACKEND_CONTAINER_DEV) bash

dev-bash-frontend:
	$(DOCKER_COMPOSE_DEV) exec $(FRONTEND_CONTAINER_DEV) bash

## ============ DATABASE & MIGRATIONS (DEV) ============

dev-migrate:
	@echo "$(GREEN)▶ Exécution des migrations...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) python manage.py migrate
	@echo "$(GREEN)✓ Migrations complétées$(NC)"

dev-makemigrations:
	@echo "$(GREEN)▶ Création des migrations...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) python manage.py makemigrations
	@echo "$(GREEN)✓ Migrations créées$(NC)"

dev-createsuperuser:
	@echo "$(GREEN)▶ Création d'un superuser...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec $(BACKEND_CONTAINER_DEV) python manage.py createsuperuser

dev-fresh-db:
	@echo "$(RED)⚠ ATTENTION: Cela va SUPPRIMER toute la BD!$(NC)"
	@read -p "Êtes-vous sûr? (y/N) " -n 1 -r; \
	echo; \
	if [[ $$REPLY =~ ^[Yy]$$ ]]; then \
		echo "$(GREEN)▶ Suppression et recréation de la BD...$(NC)"; \
		$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) python manage.py flush --noinput; \
		$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) python manage.py migrate; \
		echo "$(GREEN)✓ BD réinitialisée$(NC)"; \
	else \
		echo "$(YELLOW)Annulé$(NC)"; \
	fi

dev-dumpdata:
	@echo "$(GREEN)▶ Création du dump...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) python manage.py dumpdata database/initial_data.json
	@echo "$(GREEN)✓ Dump créé$(NC)"

dev-loaddata:
	@echo "$(GREEN)▶ Chargement des données initiales...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) python manage.py loaddata database/initial_data.json
	@echo "$(GREEN)✓ BD chargée$(NC)"

dev-db-backup:
	@echo "$(GREEN)▶ Backup de la BD de dev...$(NC)"
	@mkdir -p ./backups
	$(DOCKER_COMPOSE_DEV) exec -T $(POSTGRES_CONTAINER_DEV) pg_dump -U eiro eiro > ./backups/dev-backup-$$(date +%Y%m%d-%H%M%S).sql
	@echo "$(GREEN)✓ Backup créé$(NC)"

## ============ TESTING & QUALITY (DEV) ============

dev-test:
	@echo "$(GREEN)▶ Lancement des tests...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) python manage.py test --verbosity=2
	$(DOCKER_COMPOSE_DEV) exec -T $(FRONTEND_CONTAINER_DEV) npm test
	@echo "$(GREEN)✓ Tests complétés$(NC)"

dev-test-backend:
	@echo "$(GREEN)▶ Tests du backend...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) python manage.py test --verbosity=2
	@echo "$(GREEN)✓ Tests du backend complétés$(NC)"

dev-test-frontend:
	@echo "$(GREEN)▶ Tests du frontend...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(FRONTEND_CONTAINER_DEV) npm test
	@echo "$(GREEN)✓ Tests du frontend complétés$(NC)"

dev-coverage:
	@echo "$(GREEN)▶ Calcul du coverage...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) coverage run --source='.' manage.py test
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) coverage report
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) coverage html
	@echo "$(GREEN)✓ Rapport coverage généré (htmlcov/index.html)$(NC)"

dev-lint:
	@echo "$(GREEN)▶ Linting du code...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) pylint backend/
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) flake8 backend/
	$(DOCKER_COMPOSE_DEV) exec -T $(FRONTEND_CONTAINER_DEV) npm run lint
	@echo "$(GREEN)✓ Linting complété$(NC)"

dev-format:
	@echo "$(GREEN)▶ Formatage du code...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) black .
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) isort .
	$(DOCKER_COMPOSE_DEV) exec -T $(FRONTEND_CONTAINER_DEV) npm run format
	@echo "$(GREEN)✓ Formatage complété$(NC)"

dev-mypy:
	@echo "$(GREEN)▶ Type checking avec mypy...$(NC)"
	$(DOCKER_COMPOSE_DEV) exec -T $(BACKEND_CONTAINER_DEV) mypy .
	@echo "$(GREEN)✓ Type checking complété$(NC)"

## ============ PRODUCTION ============

prod-build:
	@echo "$(GREEN)▶ Construction des images production...$(NC)"
	docker-compose -f $(COMPOSE_FILE_PROD) build --no-cache
	@echo "$(GREEN)✓ Images construites$(NC)"

prod-up:
	@echo "$(GREEN)▶ Démarrage de la production...$(NC)"
	docker-compose -f $(COMPOSE_FILE_PROD) up -d
	@echo "$(GREEN)✓ Production démarrée$(NC)"
	@echo "  App: https://$$(grep APP_DOMAIN .env.prod | cut -d'=' -f2)"

prod-down:
	@echo "$(GREEN)▶ Arrêt de la production...$(NC)"
	docker-compose -f $(COMPOSE_FILE_PROD) down
	@echo "$(GREEN)✓ Production arrêtée$(NC)"

prod-restart: prod-down prod-up
	@echo "$(GREEN)✓ Production redémarrée$(NC)"

prod-logs:
	docker-compose -f $(COMPOSE_FILE_PROD) logs -f --tail=100

prod-logs-backend:
	docker-compose -f $(COMPOSE_FILE_PROD) logs -f $(BACKEND_CONTAINER_PROD)

prod-logs-traefik:
	docker-compose -f $(COMPOSE_FILE_PROD) logs -f traefik

prod-migrate:
	@echo "$(GREEN)▶ Migrations en production...$(NC)"
	docker-compose -f $(COMPOSE_FILE_PROD) exec -T $(BACKEND_CONTAINER_PROD) python manage.py migrate
	@echo "$(GREEN)✓ Migrations complétées$(NC)"

prod-backup:
	@echo "$(GREEN)▶ Backup de la BD production...$(NC)"
	@mkdir -p ./backups
	docker-compose -f $(COMPOSE_FILE_PROD) exec -T $(POSTGRES_CONTAINER_PROD) pg_dump -U $$(grep DB_USER .env.prod | cut -d'=' -f2) $$(grep DB_NAME .env.prod | cut -d'=' -f2) > ./backups/prod-backup-$$(date +%Y%m%d-%H%M%S).sql
	@echo "$(GREEN)✓ Backup créé: ./backups/prod-backup-*.sql$(NC)"

prod-restore:
	@echo "$(YELLOW)Fichiers de backup disponibles:$(NC)"
	@ls -lh ./backups/prod-backup-*.sql 2>/dev/null || echo "  Aucun backup trouvé"
	@read -p "Entrer le chemin du fichier (ou laisser vide pour annuler): " backup_file; \
	if [ -n "$$backup_file" ] && [ -f "$$backup_file" ]; then \
		echo "$(RED)⚠ ATTENTION: Cela va RESTAURER une ancienne BD!$(NC)"; \
		read -p "Êtes-vous sûr? (y/N) " -n 1 -r; \
		echo; \
		if [[ $$REPLY =~ ^[Yy]$$ ]]; then \
			echo "$(GREEN)▶ Restore en cours...$(NC)"; \
			docker-compose -f $(COMPOSE_FILE_PROD) exec -T $(POSTGRES_CONTAINER_PROD) psql -U $$(grep DB_USER .env.prod | cut -d'=' -f2) $$(grep DB_NAME .env.prod | cut -d'=' -f2) < $$backup_file; \
			echo "$(GREEN)✓ Restore complété$(NC)"; \
		else \
			echo "$(YELLOW)Annulé$(NC)"; \
		fi; \
	else \
		echo "$(YELLOW)Fichier invalide ou annulé$(NC)"; \
	fi

prod-shell-backend:
	docker-compose -f $(COMPOSE_FILE_PROD) exec $(BACKEND_CONTAINER_PROD) bash

## ============ BUILD ============

build-backend:
	@echo "$(GREEN)▶ Construction du backend...$(NC)"
	docker build -t eiro-backend:latest -f backend.Dockerfile ./backend
	@echo "$(GREEN)✓ Backend construit$(NC)"

build-frontend:
	@echo "$(GREEN)▶ Construction du frontend...$(NC)"
	docker build -t eiro-frontend:latest -f frontend.Dockerfile ./frontend
	@echo "$(GREEN)✓ Frontend construit$(NC)"

build-all: build-backend build-frontend
	@echo "$(GREEN)✓ Tous les services construits$(NC)"

## ============ DOCKER CLEANUP ============

docker-clean:
	@echo "$(GREEN)▶ Nettoyage Docker...$(NC)"
	docker system prune -f
	@echo "$(GREEN)✓ Nettoyage complété$(NC)"

docker-clean-volumes:
	@echo "$(RED)⚠ Attention: Cela va supprimer les volumes!$(NC)"
	@read -p "Êtes-vous sûr? (y/N) " -r REPLY; \
	echo; \
	if [ "$$REPLY" = "Y" ] || [ "$$REPLY" = "y" ]; then \
		docker system prune -f --volumes; \
		echo "$(GREEN)✓ Volumes supprimés$(NC)"; \
	else \
		echo "$(YELLOW)Annulé$(NC)"; \
	fi

docker-prune:
	@echo "$(RED)⚠ Prune AGRESSIF - Cela va supprimer beaucoup de choses!$(NC)"
	@read -p "Êtes-vous sûr? (y/N) " -r REPLY; \
	echo; \
	if [ "$$REPLY" = "Y" ] || [ "$$REPLY" = "y" ]; then \
		docker system prune -a -f --volumes; \
		echo "$(GREEN)✓ Prune complété$(NC)"; \
	else \
		echo "$(YELLOW)Annulé$(NC)"; \
	fi

## ============ UTILS ============

status:
	@echo "$(CYAN)╔════════════════════════════════════════════════════════════╗$(NC)"
	@echo "$(CYAN)║           Eiro - Status Services                   ║$(NC)"
	@echo "$(CYAN)╚════════════════════════════════════════════════════════════╝$(NC)"
	@echo ""
	@echo "$(GREEN)Development:$(NC)"
	@$(DOCKER_COMPOSE_DEV) ps
	@echo ""

version:
	@echo "Eiro v1.0.0"
	@echo "Docker: $$(docker --version)"
	@echo "Docker Compose: $$(docker-compose --version)"

## ============ SHORTCUTS ============

up: dev-up
down: dev-down
restart: dev-restart
build: dev-build
logs: dev-logs
test: dev-test
migrate: dev-migrate
fresh: dev-fresh-db
lint: dev-lint
format: dev-format
shell: dev-shell-backend
