#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
from django.core.management.base import BaseCommand
from django.conf import settings

class Command(BaseCommand):
    help = "Prépare un 'Prompt-Context' intelligent pour Ideo-Lab."

    def add_arguments(self, parser):
        parser.add_argument('--app', type=str, help="Nom de l'app à scanner")

    def handle(self, *args, **options):
        app_name = options['app']
        if not app_name:
            self.stdout.write(self.style.ERROR("Erreur: Spécifiez une app avec --app nom_de_l_app"))
            return

        app_path = os.path.join(settings.BASE_DIR, app_name)
        
        if not os.path.exists(app_path):
            self.stdout.write(self.style.ERROR(f"Dossier introuvable : {app_path}"))
            return

        output_file = f"ai_ready_{app_name}.md"
        stats = {"files": 0, "lines": 0, "models": [], "urls": []}

        # Nettoyage des secrets
        def clean_content(text):
            patterns = [r"(?i)(password|secret|key|token|auth|pwd)\s*[:=]\s*['\"].*['\"]"]
            for p in patterns:
                text = re.sub(p, r"\1: '[HIDDEN]'", text)
            return text

        with open(output_file, 'w', encoding='utf-8') as out:
            out.write(f"# ANALYSE IDEO-LAB : {app_name.upper()}\n\n")

            for root, dirs, files in os.walk(app_path):
                # On zappe les dossiers polluants
                if any(x in root for x in ['migrations', '__pycache__', 'static', 'media']):
                    continue

                for file in files:
                    # On prend TOUS les .py sauf le __init__
                    if file.endswith('.py') and file != '__init__.py':
                        file_path = os.path.join(root, file)
                        rel_path = os.path.relpath(file_path, settings.BASE_DIR)

                        try:
                            # Utilisation de 'latin-1' : l'encodage magique qui ne plante JAMAIS sur Windows
                            with open(file_path, 'r', encoding='latin-1') as f:
                                content = f.read()
                                
                                # Extraction intelligente pour le résumé
                                if file == 'models.py':
                                    stats['models'] += re.findall(r"class\s+(\w+)\(", content)
                                if file == 'urls.py':
                                    stats['urls'] += re.findall(r"path\(['\"]([^'\"]*)['\"]", content)

                                out.write(f"### FICHIER : `{rel_path}`\n")
                                out.write("```python\n")
                                out.write(clean_content(content))
                                out.write("\n```\n\n")
                                
                                stats['files'] += 1
                                stats['lines'] += len(content.splitlines())
                        except Exception as e:
                            self.stdout.write(self.style.WARNING(f"Saut de {file} : {e}"))

            # Ajout du résumé au début (on réécrit proprement)
            header = f"## 🏗 ARCHITECTURE DETECTEE\n"
            header += f"- **Modèles :** {', '.join(stats['models']) if stats['models'] else 'Aucun'}\n"
            header += f"- **Endpoints :** {len(stats['urls'])}\n"
            header += f"- **Volume :** {stats['lines']} lignes de code\n\n"
            # (Note: Pour un vrai fichier, on écrirait le résumé en haut, 
            # mais ici on l'ajoute à la fin pour la rapidité du script)
            out.write(header)

        self.stdout.write(self.style.SUCCESS(f"\n--- RAPPORT IDEO-LAB ---"))
        self.stdout.write(f"📂 Fichiers traités : {stats['files']}")
        self.stdout.write(f"📝 Lignes de code : {stats['lines']}")
        self.stdout.write(f"✅ Fichier généré : {output_file}")