#!/usr/bin/env python3
"""
🔐 Générateur de Licence d'Exemple - Web Sentinel

Script pour créer des licences d'exemple pour tester l'intégration.
Selon PRIORITÉ 1 de AGENT_IA_GUIDE.md.
"""

import json
import sys
from datetime import datetime, timezone, timedelta
from pathlib import Path

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

from web_sentinel.license.generators.license_generator import build_licence
from web_sentinel.license.generators.key_manager import generate_key_pair


def create_example_license(output_path: Path, license_type: str = "PRO") -> None:
    """
    Créer une licence d'exemple pour les tests.
    
    Args:
        output_path: Chemin de sortie pour license.lic
        license_type: Type de licence (FREE, PRO, ENTERPRISE, GOVERNMENT, TRADING)
    """
    
    # Configuration selon le type de licence
    license_configs = {
        "FREE": {
            "licenseId": "FREE-DEMO-2024-001",
            "tier": "FREE",
            "max_users": 1,
            "max_domains": 3,
            "features": {
                "invasiveTests": False,
                "htmlExport": False,
                "apiAccess": False,
                "multiUser": False,
                "customReports": False
            }
        },
        "PRO": {
            "licenseId": "PRO-DEMO-2024-001", 
            "tier": "PRO",
            "max_users": 5,
            "max_domains": 20,
            "features": {
                "invasiveTests": True,
                "htmlExport": True,
                "apiAccess": False,
                "multiUser": True,
                "customReports": True
            }
        },
        "ENTERPRISE": {
            "licenseId": "ENT-DEMO-2024-001",
            "tier": "ENTERPRISE", 
            "max_users": 50,
            "max_domains": 500,
            "features": {
                "invasiveTests": True,
                "htmlExport": True,
                "apiAccess": True,
                "multiUser": True,
                "customReports": True,
                "advancedSecurity": True,
                "prioritySupport": True
            }
        },
        "GOVERNMENT": {
            "licenseId": "GOV-DEMO-2024-001",
            "tier": "GOVERNMENT",
            "max_users": 100,
            "max_domains": 1000,
            "features": {
                "invasiveTests": True,
                "htmlExport": True,
                "apiAccess": True,
                "multiUser": True,
                "customReports": True,
                "advancedSecurity": True,
                "prioritySupport": True,
                "sovereignMode": True,
                "airgapOperation": True
            }
        },
        "TRADING": {
            "licenseId": "TRD-DEMO-2024-001",
            "tier": "TRADING",
            "max_users": 200,
            "max_domains": 2000,
            "features": {
                "invasiveTests": True,
                "htmlExport": True,
                "apiAccess": True,
                "multiUser": True,
                "customReports": True,
                "advancedSecurity": True,
                "prioritySupport": True,
                "highFrequencyValidation": True,
                "realTimeAudit": True
            }
        }
    }
    
    if license_type not in license_configs:
        raise ValueError(f"Type de licence non supporté: {license_type}")
        
    base_config = license_configs[license_type]
    
    # Configuration complète de la licence
    now = datetime.now(timezone.utc)
    
    full_config = {
        "licenseId": base_config["licenseId"],
        "version": "1.0",
        "issuedAt": now.isoformat(),
        "subscription": {
            "tier": base_config["tier"],
            "validUntil": (now + timedelta(days=365)).isoformat(),  # 1 an
            "maxUsers": base_config["max_users"],
            "maxDomains": base_config["max_domains"],
            "features": base_config["features"]
        },
        "customer": {
            "organization": "Example Corp",
            "contactEmail": "admin@example.com",
            "licenseManager": "license-manager@example.com"
        },
        "superAdmin": {
            "email": "superadmin@example.com",
            "passwordHash": "sha256:demo_password_hash",
            "mustChangePassword": True
        },
        "encryption": {
            "dbKeySeed": "demo_encryption_seed_256_bits_example",
            "algorithm": "AES-256-GCM",
            "keyDerivation": "PBKDF2-SHA256"
        },
        "antiTampering": {
            "hardwareFingerprint": "",  # Optionnel pour demo
            "installationId": "demo-installation-uuid",
            "appChecksum": "demo_app_checksum_hash",
            "maxOfflineDays": 7
        },
        "validation": {
            "serverValidationUrl": "https://license.websentinel.com/validate",
            "lastServerValidation": now.isoformat(),
            "gracePeriodHours": 168,  # 7 jours
            "validationSecret": "demo_hmac_validation_secret"
        }
    }
    
    # Créer les clés si elles n'existent pas
    keys_dir = Path(__file__).parent / "demo_keys"
    keys_dir.mkdir(exist_ok=True)
    
    private_key_path = keys_dir / "demo_private.pem"
    public_key_path = keys_dir / "demo_public.pem"
    
    if not private_key_path.exists():
        print("🔑 Génération des clés de démonstration...")
        private_key, public_key = generate_key_pair()
        
        private_key_path.write_bytes(private_key)
        public_key_path.write_bytes(public_key)
        print(f"✅ Clés générées dans {keys_dir}")
    
    # Générer la licence
    print(f"🔐 Génération de la licence {license_type}...")
    licence_data = build_licence(full_config, private_key_path)
    
    # Construire le fichier final
    licence_file_content = {
        **licence_data.payload,
        "signature": licence_data.signature
    }
    
    # Sauvegarder
    output_path.parent.mkdir(parents=True, exist_ok=True)
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(licence_file_content, f, indent=2)
    
    print(f"✅ Licence {license_type} créée: {output_path}")
    print(f"📋 ID: {base_config['licenseId']}")
    print(f"🏷️ Tier: {base_config['tier']}")
    print(f"👥 Max Users: {base_config['max_users']}")
    print(f"🌐 Max Domains: {base_config['max_domains']}")
    print(f"⏰ Expire: {(now + timedelta(days=365)).strftime('%Y-%m-%d')}")


def main():
    """Point d'entrée du script."""
    import argparse
    
    parser = argparse.ArgumentParser(description="Générateur de licences d'exemple Web Sentinel")
    parser.add_argument(
        "--type", 
        choices=["FREE", "PRO", "ENTERPRISE", "GOVERNMENT", "TRADING"],
        default="PRO",
        help="Type de licence à générer (défaut: PRO)"
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=Path.cwd() / "license.lic",
        help="Chemin de sortie (défaut: ./license.lic)"
    )
    
    args = parser.parse_args()
    
    try:
        create_example_license(args.output, args.type)
        
        print(f"\n🎯 Pour tester la licence:")
        print(f"   1. Copiez {args.output} dans le répertoire Web Sentinel")
        print(f"   2. Ou définissez WS_LICENSE_FILE={args.output}")
        print(f"   3. Lancez Web Sentinel GUI ou CLI")
        
    except Exception as e:
        print(f"❌ Erreur: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()