#!/usr/bin/env python3
"""
Script pour ajouter automatiquement les clés i18n manquantes dans les nouveaux modules Web Sentinel.
"""

import re
import os
from pathlib import Path

# Mapping des patterns de Finding vers les clés i18n
FINDING_MAPPINGS = {
    # Backend Config
    ("backend-config", "Backend analysis requires invasive mode"): "backend.analysis_requires_invasive",
    ("backend-config", "Security.txt found"): "backend.security_txt_found", 
    ("backend-config", "Sensitive configuration file exposed"): "backend.config_file_exposed",
    ("backend-config", "Detailed health endpoint exposed"): "backend.actuator_details_exposed",
    ("backend-config", "Verbose error pages detected"): "backend.verbose_error_pages",
    ("backend-config", "Development tool accessible in production"): "backend.dev_tool_accessible",
    ("backend-config", "Permissive CORS configuration detected"): "backend.permissive_cors",
    
    # API Security
    ("api-security", "API endpoint .* unreachable"): "api.endpoint_unreachable",
    ("api-security", "Permissive CORS on API endpoint"): "api.permissive_cors",
    ("api-security", "API endpoint accessible without authentication"): "api.unauthenticated_access",
    ("api-security", "No rate limiting headers detected"): "api.no_rate_limiting",
    ("api-security", "Potential .* exposure in API"): "api.sensitive_data_exposure",
    ("api-security", "Verbose API error messages"): "api.verbose_errors",
    ("api-security", "Potentially dangerous HTTP methods allowed"): "api.dangerous_methods",
    ("api-security", "Multiple API versions accessible"): "api.multiple_versions",
    ("api-security", "No rate limiting detected on API"): "api.no_rate_limiting_detected",
    ("api-security", "Potential authentication bypass via headers"): "api.auth_bypass_detected",
    
    # Modern Web
    ("modern-web", "Cannot analyze modern web technologies"): "modern.analysis_failed",
    ("modern-web", "JavaScript frameworks detected"): "modern.frameworks_detected",
    ("modern-web", "React development build detected"): "modern.react_dev_build",
    ("modern-web", "Angular development mode detected"): "modern.angular_dev_mode",
    ("modern-web", "Environment variables exposed in client"): "modern.env_vars_exposed",
    ("modern-web", "Deployment platform detected"): "modern.deployment_platform",
    ("modern-web", "Sensitive information in Server-Timing header"): "modern.server_timing_sensitive",
    ("modern-web", "Potential .* exposed in client code"): "modern.credentials_exposed",
    ("modern-web", "External API URLs hardcoded in client"): "modern.external_apis_hardcoded",
    ("modern-web", "PWA manifest detected"): "modern.pwa_detected",
    ("modern-web", "PWA scope too permissive"): "modern.pwa_scope_permissive",
    ("modern-web", "PWA icon served over HTTP"): "modern.pwa_insecure_icon",
    ("modern-web", "Invalid PWA manifest format"): "modern.pwa_invalid_manifest",
    ("modern-web", "Service Worker caches HTTP resources"): "modern.sw_insecure_resources",
    ("modern-web", "Potentially aggressive caching strategy"): "modern.sw_aggressive_caching",
    ("modern-web", "Android App Links configured"): "modern.android_app_links",
    ("modern-web", "iOS Universal Links configured"): "modern.ios_universal_links",
}

def add_i18n_keys_to_file(file_path: Path):
    """Ajoute les clés i18n manquantes à un fichier de module."""
    print(f"Traitement de {file_path}")
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    original_content = content
    
    # Pattern pour trouver les Finding sans i18n_key
    finding_pattern = r'Finding\s*\(\s*check="([^"]+)",\s*title="([^"]+)"[^)]*?\)'
    
    def replace_finding(match):
        check = match.group(1)
        title = match.group(2)
        
        # Cherche la clé i18n correspondante
        i18n_key = None
        for (check_pattern, title_pattern), key in FINDING_MAPPINGS.items():
            if check == check_pattern and re.search(title_pattern, title):
                i18n_key = key
                break
        
        if i18n_key and 'i18n_key=' not in match.group(0):
            # Ajoute la clé i18n avant la parenthèse fermante
            full_match = match.group(0)
            if full_match.endswith(')'):
                return full_match[:-1] + f',\n                i18n_key="{i18n_key}",\n            )'
            else:
                return full_match + f',\n                i18n_key="{i18n_key}"'
        
        return match.group(0)
    
    content = re.sub(finding_pattern, replace_finding, content, flags=re.DOTALL)
    
    # Écrit le fichier seulement si modifié
    if content != original_content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"✅ Mis à jour {file_path}")
    else:
        print(f"ℹ️ Aucune modification nécessaire pour {file_path}")

def main():
    """Point d'entrée principal."""
    # Fichiers à traiter
    files_to_process = [
        Path("web_sentinel/checks/backend_config.py"),
        Path("web_sentinel/checks/api_security.py"), 
        Path("web_sentinel/checks/modern_web.py"),
    ]
    
    for file_path in files_to_process:
        if file_path.exists():
            add_i18n_keys_to_file(file_path)
        else:
            print(f"❌ Fichier introuvable : {file_path}")

if __name__ == "__main__":
    main()