#!/usr/bin/env python3
"""
🔧 Générateur de fichiers de configuration pour Web Sentinel
Crée tous les fichiers de configuration nécessaires pour l'environnement de test
"""

import json
import sys
import os
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, Any, List

# Ajouter le répertoire parent pour importer web_sentinel
sys.path.insert(0, str(Path(__file__).parent.parent))

class ConfigGenerator:
    """Générateur de configurations complètes"""
    
    def __init__(self):
        self.base_dir = Path(__file__).parent
        self.config_dir = self.base_dir / "config"
        self.templates_dir = self.base_dir / "templates"
        
        # Créer les répertoires
        self.config_dir.mkdir(exist_ok=True)
        self.templates_dir.mkdir(exist_ok=True)
    
    def generate_web_sentinel_config(self) -> Dict[str, Any]:
        """Configuration principale de Web Sentinel"""
        return {
            "application": {
                "name": "Web Sentinel",
                "version": "2.0.0",
                "environment": "test",
                "debug": True,
                "log_level": "DEBUG"
            },
            "security": {
                "license_validation": True,
                "require_https": False,  # Relaxé pour tests
                "max_scan_duration": 300,  # 5 minutes max
                "rate_limiting": {
                    "enabled": True,
                    "requests_per_minute": 60,
                    "burst_size": 10
                }
            },
            "scanning": {
                "default_modules": ["headers", "tls", "static-analysis"],
                "max_concurrent_scans": 5,
                "timeout_seconds": 30,
                "user_agent": "WebSentinel-Test/2.0",
                "follow_redirects": True,
                "verify_ssl": True
            },
            "database": {
                "type": "mysql",
                "host": "localhost",
                "port": 3306,
                "name": "web_sentinel_test",
                "user": "ws_test",
                "password": "test_password_2024",
                "pool_size": 10,
                "pool_timeout": 30
            },
            "redis": {
                "host": "localhost",
                "port": 6379,
                "db": 1,  # DB 1 pour tests
                "password": None,
                "timeout": 5
            },
            "logging": {
                "level": "DEBUG",
                "file": "logs/web_sentinel_test.log",
                "max_size_mb": 50,
                "backup_count": 5,
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            },
            "reporting": {
                "formats": ["json", "html", "xml"],
                "include_raw_data": True,
                "compress_reports": False,
                "retention_days": 30
            },
            "api": {
                "enabled": True,
                "host": "127.0.0.1",
                "port": 8080,
                "cors_enabled": True,
                "auth_required": False  # Simplifié pour tests
            }
        }
    
    def generate_license_tiers_config(self) -> Dict[str, Any]:
        """Configuration détaillée des tiers de licence"""
        return {
            "tiers": {
                "FREE": {
                    "name": "Gratuit",
                    "description": "Utilisation basique pour découvrir Web Sentinel",
                    "price_monthly": 0,
                    "limits": {
                        "domains_per_month": 5,
                        "scans_per_day": 3,
                        "concurrent_scans": 1,
                        "modules_available": ["headers", "static-analysis"],
                        "report_formats": ["json"],
                        "api_calls_per_hour": 50,
                        "retention_days": 7
                    },
                    "features": {
                        "basic_scanning": True,
                        "email_reports": False,
                        "api_access": True,
                        "custom_modules": False,
                        "priority_support": False,
                        "white_labeling": False,
                        "advanced_reporting": False,
                        "compliance_templates": False
                    }
                },
                "PRO": {
                    "name": "Professionnel",
                    "description": "Pour les développeurs et petites équipes",
                    "price_monthly": 29,
                    "limits": {
                        "domains_per_month": 100,
                        "scans_per_day": 50,
                        "concurrent_scans": 3,
                        "modules_available": ["headers", "tls", "static-analysis", "injection"],
                        "report_formats": ["json", "html", "xml"],
                        "api_calls_per_hour": 500,
                        "retention_days": 30
                    },
                    "features": {
                        "basic_scanning": True,
                        "email_reports": True,
                        "api_access": True,
                        "custom_modules": False,
                        "priority_support": False,
                        "white_labeling": False,
                        "advanced_reporting": True,
                        "compliance_templates": False
                    }
                },
                "ENTERPRISE": {
                    "name": "Entreprise",
                    "description": "Pour les moyennes et grandes entreprises",
                    "price_monthly": 199,
                    "limits": {
                        "domains_per_month": 1000,
                        "scans_per_day": 500,
                        "concurrent_scans": 10,
                        "modules_available": ["headers", "tls", "static-analysis", "injection", "third-party"],
                        "report_formats": ["json", "html", "xml", "pdf"],
                        "api_calls_per_hour": 5000,
                        "retention_days": 90
                    },
                    "features": {
                        "basic_scanning": True,
                        "email_reports": True,
                        "api_access": True,
                        "custom_modules": True,
                        "priority_support": True,
                        "white_labeling": True,
                        "advanced_reporting": True,
                        "compliance_templates": True
                    }
                },
                "GOVERNMENT": {
                    "name": "Gouvernement",
                    "description": "Pour les administrations publiques",
                    "price_monthly": 399,
                    "limits": {
                        "domains_per_month": 5000,
                        "scans_per_day": 1000,
                        "concurrent_scans": 20,
                        "modules_available": ["headers", "tls", "static-analysis", "injection", "third-party"],
                        "report_formats": ["json", "html", "xml", "pdf"],
                        "api_calls_per_hour": 10000,
                        "retention_days": 365
                    },
                    "features": {
                        "basic_scanning": True,
                        "email_reports": True,
                        "api_access": True,
                        "custom_modules": True,
                        "priority_support": True,
                        "white_labeling": True,
                        "advanced_reporting": True,
                        "compliance_templates": True,
                        "air_gap_deployment": True,
                        "government_compliance": True
                    }
                },
                "FINANCE": {
                    "name": "Finance",
                    "description": "Pour les institutions financières",
                    "price_monthly": 599,
                    "limits": {
                        "domains_per_month": 10000,
                        "scans_per_day": 2000,
                        "concurrent_scans": 30,
                        "modules_available": ["headers", "tls", "static-analysis", "injection", "third-party"],
                        "report_formats": ["json", "html", "xml", "pdf"],
                        "api_calls_per_hour": 20000,
                        "retention_days": 1095  # 3 ans
                    },
                    "features": {
                        "basic_scanning": True,
                        "email_reports": True,
                        "api_access": True,
                        "custom_modules": True,
                        "priority_support": True,
                        "white_labeling": True,
                        "advanced_reporting": True,
                        "compliance_templates": True,
                        "pci_compliance": True,
                        "sox_compliance": True,
                        "advanced_encryption": True
                    }
                },
                "MEDICAL": {
                    "name": "Médical",
                    "description": "Pour les organisations de santé",
                    "price_monthly": 799,
                    "limits": {
                        "domains_per_month": 15000,
                        "scans_per_day": 3000,
                        "concurrent_scans": 50,
                        "modules_available": ["headers", "tls", "static-analysis", "injection", "third-party"],
                        "report_formats": ["json", "html", "xml", "pdf"],
                        "api_calls_per_hour": 30000,
                        "retention_days": 2555  # 7 ans
                    },
                    "features": {
                        "basic_scanning": True,
                        "email_reports": True,
                        "api_access": True,
                        "custom_modules": True,
                        "priority_support": True,
                        "white_labeling": True,
                        "advanced_reporting": True,
                        "compliance_templates": True,
                        "hipaa_compliance": True,
                        "phi_protection": True,
                        "audit_trails": True,
                        "data_residency": True
                    }
                }
            }
        }
    
    def generate_scan_modules_config(self) -> Dict[str, Any]:
        """Configuration des modules de scan"""
        return {
            "modules": {
                "headers": {
                    "name": "Analyse des en-têtes HTTP",
                    "description": "Vérifie les en-têtes de sécurité HTTP",
                    "category": "passive",
                    "enabled": True,
                    "timeout": 10,
                    "config": {
                        "required_headers": [
                            "X-Frame-Options",
                            "X-Content-Type-Options",
                            "X-XSS-Protection",
                            "Strict-Transport-Security",
                            "Content-Security-Policy"
                        ],
                        "forbidden_headers": [
                            "Server",
                            "X-Powered-By",
                            "X-AspNet-Version"
                        ]
                    }
                },
                "tls": {
                    "name": "Analyse TLS/SSL",
                    "description": "Vérifie la configuration TLS/SSL",
                    "category": "passive",
                    "enabled": True,
                    "timeout": 15,
                    "config": {
                        "min_tls_version": "1.2",
                        "check_certificate": True,
                        "check_ciphers": True,
                        "check_vulnerabilities": True
                    }
                },
                "static-analysis": {
                    "name": "Analyse statique",
                    "description": "Analyse statique du contenu web",
                    "category": "passive",
                    "enabled": True,
                    "timeout": 20,
                    "config": {
                        "max_page_size": 1048576,  # 1MB
                        "follow_scripts": True,
                        "analyze_forms": True,
                        "check_comments": True
                    }
                },
                "injection": {
                    "name": "Test d'injection",
                    "description": "Détection de vulnérabilités d'injection",
                    "category": "active",
                    "enabled": True,
                    "timeout": 30,
                    "config": {
                        "test_sql": True,
                        "test_xss": True,
                        "test_commands": True,
                        "payloads_file": "payloads/injection.json"
                    }
                },
                "third-party": {
                    "name": "Intégrations tierces",
                    "description": "Intégration avec outils tiers",
                    "category": "passive",
                    "enabled": True,
                    "timeout": 60,
                    "config": {
                        "zap_enabled": False,
                        "burp_enabled": False,
                        "nikto_enabled": False
                    }
                }
            }
        }
    
    def generate_payloads_config(self) -> Dict[str, Any]:
        """Configuration des payloads de test"""
        return {
            "sql_injection": [
                "' OR '1'='1",
                "' UNION SELECT NULL--",
                "'; DROP TABLE users; --",
                "' OR 1=1 LIMIT 1 -- "
            ],
            "xss": [
                "<script>alert('XSS')</script>",
                "<img src=x onerror=alert('XSS')>",
                "javascript:alert('XSS')",
                "<svg onload=alert('XSS')>"
            ],
            "command_injection": [
                "; ls -la",
                "| whoami",
                "&& cat /etc/passwd",
                "`id`"
            ],
            "ldap_injection": [
                "*)(&",
                "*)(uid=*",
                "*)(|(mail=*",
                "*))%00"
            ],
            "xpath_injection": [
                "' or 1=1 or ''='",
                "' or ''='",
                "x' or 1=1 or 'x'='y",
                "//*[@*[contains(.,':')] or @*[contains(.,'::')]]"
            ]
        }
    
    def generate_docker_compose(self) -> str:
        """Générer docker-compose.yml pour l'environnement de test"""
        return """version: '3.8'

services:
  mysql_test:
    image: mysql:8.0
    container_name: web_sentinel_mysql_test
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_DATABASE: web_sentinel_test
      MYSQL_USER: ws_test
      MYSQL_PASSWORD: test_password_2024
    ports:
      - "3307:3306"  # Port différent pour éviter conflit
    volumes:
      - mysql_test_data:/var/lib/mysql
      - ./sql/init.sql:/docker-entrypoint-initdb.d/init.sql
    networks:
      - websentinel_test

  redis_test:
    image: redis:7-alpine
    container_name: web_sentinel_redis_test
    ports:
      - "6380:6379"  # Port différent pour éviter conflit
    volumes:
      - redis_test_data:/data
    networks:
      - websentinel_test

  zap_test:
    image: owasp/zap2docker-stable
    container_name: web_sentinel_zap_test
    ports:
      - "8081:8080"
    command: zap.sh -daemon -host 0.0.0.0 -port 8080 -config api.addrs.addr.name=.* -config api.addrs.addr.regex=true
    networks:
      - websentinel_test

  nginx_test:
    image: nginx:alpine
    container_name: web_sentinel_nginx_test
    ports:
      - "8082:80"
    volumes:
      - ./nginx/test-sites:/usr/share/nginx/html
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
    networks:
      - websentinel_test

volumes:
  mysql_test_data:
  redis_test_data:

networks:
  websentinel_test:
    driver: bridge
"""
    
    def generate_nginx_config(self) -> str:
        """Configuration Nginx pour sites de test"""
        return """events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # Site de test sécurisé
    server {
        listen 80;
        server_name secure.test.local;
        root /usr/share/nginx/html/secure;

        # Headers de sécurité
        add_header X-Frame-Options "DENY" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-XSS-Protection "1; mode=block" always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header Content-Security-Policy "default-src 'self'" always;
        
        # Masquer version nginx
        server_tokens off;
        
        location / {
            index index.html;
        }
    }

    # Site de test vulnérable (pour tests)
    server {
        listen 80;
        server_name vulnerable.test.local;
        root /usr/share/nginx/html/vulnerable;

        # Pas de headers de sécurité (volontairement vulnérable)
        add_header Server "Apache/2.4.41" always;
        add_header X-Powered-By "PHP/7.4.0" always;
        
        location / {
            index index.html;
        }
    }

    # Site de test mixte
    server {
        listen 80;
        server_name mixed.test.local;
        root /usr/share/nginx/html/mixed;

        # Headers partiels
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-Content-Type-Options "nosniff" always;
        
        location / {
            index index.html;
        }
    }
}
"""
    
    def generate_test_html_pages(self) -> Dict[str, str]:
        """Générer les pages HTML de test"""
        pages = {}
        
        # Page sécurisée
        pages["secure/index.html"] = """<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Site Sécurisé - Test Web Sentinel</title>
</head>
<body>
    <h1>Site de Test Sécurisé</h1>
    <p>Ce site implémente les bonnes pratiques de sécurité web.</p>
    <ul>
        <li>Headers de sécurité configurés</li>
        <li>CSP restrictive</li>
        <li>Pas d'informations sensibles exposées</li>
    </ul>
</body>
</html>"""

        # Page vulnérable
        pages["vulnerable/index.html"] = """<!DOCTYPE html>
<html>
<head>
    <title>Site Vulnérable - Test Web Sentinel</title>
    <!-- Version info exposée -->
    <meta name="generator" content="WordPress 5.0.0">
</head>
<body>
    <h1>Site de Test Vulnérable</h1>
    
    <!-- Commentaire sensible -->
    <!-- TODO: Changer le mot de passe admin par défaut 'admin123' -->
    
    <form method="GET" action="/search">
        <!-- Input XSS vulnérable -->
        <input type="text" name="q" value="">
        <input type="submit" value="Rechercher">
    </form>
    
    <!-- Script inline sans CSP -->
    <script>
        var apiKey = "sk-test-123456789"; // Clé exposée
        console.log("Debug mode enabled");
    </script>
    
    <!-- Frame sans protection -->
    <iframe src="http://external.com/widget"></iframe>
</body>
</html>"""

        # Page mixte
        pages["mixed/index.html"] = """<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Site Mixte - Test Web Sentinel</title>
</head>
<body>
    <h1>Site de Test Mixte</h1>
    <p>Ce site a une sécurité partielle.</p>
    
    <form method="POST" action="/contact">
        <input type="text" name="name" required>
        <input type="email" name="email" required>
        <textarea name="message"></textarea>
        <!-- Token CSRF manquant -->
        <input type="submit" value="Envoyer">
    </form>
    
    <!-- Bon: utilisation HTTPS pour ressources externes -->
    <script src="https://cdn.example.com/lib.js"></script>
    
    <!-- Problème: ressource HTTP mixte -->
    <img src="http://example.com/image.jpg" alt="Test">
</body>
</html>"""

        return pages
    
    def create_all_configs(self) -> None:
        """Créer tous les fichiers de configuration"""
        print("🔧 GÉNÉRATION CONFIGURATION COMPLÈTE")
        print("=" * 60)
        
        configs = [
            ("web_sentinel_config.json", self.generate_web_sentinel_config()),
            ("license_tiers.json", self.generate_license_tiers_config()),
            ("scan_modules.json", self.generate_scan_modules_config()),
            ("payloads.json", self.generate_payloads_config())
        ]
        
        # Créer les configs JSON
        for filename, config_data in configs:
            config_path = self.config_dir / filename
            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, indent=2, ensure_ascii=False)
            print(f"✅ {filename}")
        
        # Créer docker-compose.yml
        docker_compose_path = self.base_dir / "docker-compose.yml"
        with open(docker_compose_path, 'w', encoding='utf-8') as f:
            f.write(self.generate_docker_compose())
        print("✅ docker-compose.yml")
        
        # Créer nginx config
        nginx_dir = self.base_dir / "nginx"
        nginx_dir.mkdir(exist_ok=True)
        
        nginx_config_path = nginx_dir / "nginx.conf"
        with open(nginx_config_path, 'w', encoding='utf-8') as f:
            f.write(self.generate_nginx_config())
        print("✅ nginx/nginx.conf")
        
        # Créer pages HTML de test
        test_sites_dir = nginx_dir / "test-sites"
        test_sites_dir.mkdir(exist_ok=True)
        
        html_pages = self.generate_test_html_pages()
        for page_path, content in html_pages.items():
            full_path = test_sites_dir / page_path
            full_path.parent.mkdir(parents=True, exist_ok=True)
            
            with open(full_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✅ nginx/test-sites/{page_path}")
        
        print("=" * 60)
        print("✅ CONFIGURATION COMPLÈTE GÉNÉRÉE!")
        print("📁 Fichiers créés:")
        print(f"   - {len(configs)} fichiers de configuration JSON")
        print("   - 1 docker-compose.yml pour environnement isolé")
        print("   - 1 nginx.conf avec 3 sites de test")
        print("   - 3 pages HTML de test (sécurisé/vulnérable/mixte)")
        print("\n🚀 Prêt pour:")
        print("   - Tests de licence automatisés")
        print("   - Environnement Docker isolé")
        print("   - Sites de test variés")


def main():
    import argparse
    
    parser = argparse.ArgumentParser(description="🔧 Générateur configurations Web Sentinel")
    parser.add_argument("--all", action="store_true", help="Générer toutes les configurations")
    parser.add_argument("--docker", action="store_true", help="Générer seulement docker-compose")
    parser.add_argument("--nginx", action="store_true", help="Générer seulement config nginx")
    parser.add_argument("--json", action="store_true", help="Générer seulement configs JSON")
    
    args = parser.parse_args()
    
    generator = ConfigGenerator()
    
    if args.all or not any([args.docker, args.nginx, args.json]):
        generator.create_all_configs()
    else:
        if args.json:
            # Seulement les configs JSON
            configs = [
                ("web_sentinel_config.json", generator.generate_web_sentinel_config()),
                ("license_tiers.json", generator.generate_license_tiers_config()),
                ("scan_modules.json", generator.generate_scan_modules_config()),
                ("payloads.json", generator.generate_payloads_config())
            ]
            
            for filename, config_data in configs:
                config_path = generator.config_dir / filename
                with open(config_path, 'w', encoding='utf-8') as f:
                    json.dump(config_data, f, indent=2, ensure_ascii=False)
                print(f"✅ {filename}")
        
        if args.docker:
            docker_compose_path = generator.base_dir / "docker-compose.yml"
            with open(docker_compose_path, 'w', encoding='utf-8') as f:
                f.write(generator.generate_docker_compose())
            print("✅ docker-compose.yml")
        
        if args.nginx:
            nginx_dir = generator.base_dir / "nginx"
            nginx_dir.mkdir(exist_ok=True)
            
            nginx_config_path = nginx_dir / "nginx.conf"
            with open(nginx_config_path, 'w', encoding='utf-8') as f:
                f.write(generator.generate_nginx_config())
            print("✅ nginx/nginx.conf")


if __name__ == "__main__":
    main()