#!/usr/bin/env python3
"""
Script pour mettre à jour la navigation et le footer sur toutes les pages restantes
"""
import re
from pathlib import Path

# CSS pour le dropdown
DROPDOWN_CSS = """        .nav-links li { position: relative; }
        .dropdown { position: relative; }
        .dropdown-content { display: none; position: absolute; top: 100%; left: 0; background: #34495e; min-width: 200px; box-shadow: 0 8px 16px rgba(0,0,0,0.2); border-radius: 5px; margin-top: 0; padding-top: 10px; z-index: 1000; }
        .dropdown-content a { padding: 12px 16px; display: block; border-radius: 5px; }
        .dropdown-content a:hover { background: #2c3e50; }
        .dropdown:hover .dropdown-content { display: block; }
        @media (max-width: 768px) { .nav-container { flex-direction: column; gap: 15px; } .nav-links { flex-direction: column; align-items: center; } .dropdown-content { position: static; margin-top: 5px; } }"""

# Menu dropdown HTML
DROPDOWN_MENU = """                <li class="dropdown">
                    <a href="https://docs.web-sentinel.taaazzz-prog.fr">📖 Documentation ▾</a>
                    <div class="dropdown-content">
                        <a href="https://docs.web-sentinel.taaazzz-prog.fr">📚 API Reference</a>
                        <a href="https://web-sentinel.taaazzz-prog.fr/docs/auth-api.html">🔐 Authentification</a>
                        <a href="https://web-sentinel.taaazzz-prog.fr/docs/tier-limits.html">📊 Limites & Quotas</a>
                        <a href="https://web-sentinel.taaazzz-prog.fr/docs/changelog.html">📝 Changelog</a>
                        <a href="https://web-sentinel.taaazzz-prog.fr/docs/faq.html">❓ FAQ</a>
                    </div>
                </li>"""

# Footer complet
FOOTER_LINKS = """            <a href="https://web-sentinel.taaazzz-prog.fr">Accueil</a>
            <a href="https://docs.web-sentinel.taaazzz-prog.fr">API Docs</a>
            <a href="https://web-sentinel.taaazzz-prog.fr/docs/changelog.html">Changelog</a>
            <a href="https://web-sentinel.taaazzz-prog.fr/docs/faq.html">FAQ</a>
            <a href="https://install.web-sentinel.taaazzz-prog.fr">Installation</a>
            <a href="https://stats.web-sentinel.taaazzz-prog.fr">Statistiques</a>
            <a href="https://web-sentinel.taaazzz-prog.fr/privacy">Confidentialité</a>
            <a href="https://web-sentinel.taaazzz-prog.fr/legal">Mentions Légales</a>
            <a href="https://web-sentinel.taaazzz-prog.fr/terms">CGU</a>
            <a href="mailto:contact@taaazzz-prog.fr">Contact</a>"""

def update_file(filepath):
    """Met à jour un fichier HTML avec le menu dropdown et footer"""
    print(f"\n📝 Traitement de {filepath.name}...")
    
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
    
    original_content = content
    
    # 1. Ajouter le CSS du dropdown si pas présent
    if '.dropdown {' not in content:
        # Chercher la ligne avec @media et ajouter avant
        pattern = r'(@media \(max-width: 768px\)[^\}]+\.nav-links[^\}]+\})'
        if re.search(pattern, content):
            content = re.sub(
                pattern,
                DROPDOWN_CSS,
                content,
                count=1
            )
            print("  ✅ CSS dropdown ajouté")
        else:
            # Ajouter après .nav-links a.active
            pattern = r'(\.nav-links a\.active[^\}]+\})'
            content = re.sub(
                pattern,
                r'\1\n' + DROPDOWN_CSS,
                content,
                count=1
            )
            print("  ✅ CSS dropdown ajouté (méthode alternative)")
    
    # 2. Remplacer le lien Documentation simple par le dropdown
    # Pattern: <li><a href="https://docs.web-sentinel.taaazzz-prog.fr">📖 Documentation</a></li>
    doc_pattern = r'<li><a href="https://docs\.web-sentinel\.taaazzz-prog\.fr"[^>]*>📖 Documentation</a></li>'
    if re.search(doc_pattern, content):
        content = re.sub(
            doc_pattern,
            DROPDOWN_MENU,
            content
        )
        print("  ✅ Menu dropdown ajouté")
    
    # 3. Ajouter "Mon Compte" si manquant (avant le lien API)
    if '👤 Mon Compte' not in content:
        # Chercher le lien API et ajouter Mon Compte avant
        api_pattern = r'(<li><a href="https://api\.web-sentinel\.taaazzz-prog\.fr/api/v1/health")'
        if re.search(api_pattern, content):
            content = re.sub(
                api_pattern,
                r'<li><a href="https://web-sentinel.taaazzz-prog.fr/account.html">👤 Mon Compte</a></li>\n                \1',
                content
            )
            print("  ✅ Lien 'Mon Compte' ajouté")
    
    # 4. Mettre à jour le footer
    # Chercher les liens du footer et les remplacer
    footer_pattern = r'(<div class="footer-links">)(.*?)(</div>)'
    
    def replace_footer(match):
        return match.group(1) + '\n' + FOOTER_LINKS + '\n        ' + match.group(3)
    
    if re.search(footer_pattern, content, re.DOTALL):
        old_footer = re.search(footer_pattern, content, re.DOTALL).group(2)
        if 'Changelog' not in old_footer or 'FAQ' not in old_footer:
            content = re.sub(footer_pattern, replace_footer, content, flags=re.DOTALL)
            print("  ✅ Footer mis à jour")
    
    # 5. Corriger le dropdown existant (margin-top)
    if 'margin-top: 10px' in content and '.dropdown-content' in content:
        content = content.replace(
            'margin-top: 10px; z-index: 1000',
            'margin-top: 0; padding-top: 10px; z-index: 1000'
        )
        print("  ✅ Dropdown spacing corrigé")
    
    # Sauvegarder seulement si des changements ont été faits
    if content != original_content:
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"  💾 {filepath.name} sauvegardé")
        return True
    else:
        print(f"  ⏭️  Aucune modification nécessaire")
        return False

def main():
    """Point d'entrée"""
    workspace = Path(__file__).parent.parent
    
    files_to_update = [
        workspace / 'web' / 'stats' / 'index.html',
        workspace / 'web' / 'legal' / 'index.html',
        workspace / 'web' / 'terms' / 'index.html',
        workspace / 'web' / 'privacy' / 'index.html',
    ]
    
    updated = 0
    for filepath in files_to_update:
        if filepath.exists():
            if update_file(filepath):
                updated += 1
        else:
            print(f"❌ Fichier introuvable: {filepath}")
    
    print(f"\n✨ Terminé ! {updated} fichier(s) mis à jour.")

if __name__ == '__main__':
    main()
