#!/usr/bin/env python3
"""
📊 Gestionnaire de configuration pour tests Web Sentinel
Centralise la configuration et fournit des outils de gestion
"""

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

class ConfigManager:
    """Gestionnaire de configuration centralisée"""
    
    def __init__(self):
        self.config_dir = Path(__file__).parent / "config"
        self.config_file = self.config_dir / "test_config.json"
        self.accounts_file = self.config_dir / "accounts.json"
        
        self.config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """Charger la configuration"""
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            return {}
    
    def _save_config(self):
        """Sauvegarder la configuration"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.config, f, indent=2, ensure_ascii=False)
    
    def get_tier_config(self, tier: str) -> Dict[str, Any]:
        """Obtenir la configuration d'un tier"""
        return self.config.get("tiers", {}).get(tier, {})
    
    def list_tiers(self):
        """Lister tous les tiers disponibles"""
        print("\n💰 TIERS DISPONIBLES:")
        print("=" * 100)
        print(f"{'TIER':<12} | {'PRIX':<10} | {'DOMAINES':<10} | {'FORMATS':<15} | {'INVASIF':<8} | {'API':<5} | {'MULTI':<5}")
        print("=" * 100)
        
        for tier_name, tier_config in self.config.get("tiers", {}).items():
            price = f"{tier_config['price']}€" if tier_config['price'] > 0 else "GRATUIT"
            domains = str(tier_config['domains_limit']) if tier_config['domains_limit'] else "∞"
            formats = ",".join(tier_config['export_formats'])
            invasive = "✅" if tier_config['invasive_tests'] else "❌"
            api = "✅" if tier_config['api_access'] else "❌"
            multi = "✅" if tier_config['multi_user'] else "❌"
            
            print(f"{tier_name:<12} | {price:<10} | {domains:<10} | {formats:<15} | {invasive:<8} | {api:<5} | {multi:<5}")
        
        print("=" * 100)
    
    def update_tier_price(self, tier: str, new_price: float) -> bool:
        """Mettre à jour le prix d'un tier"""
        if tier not in self.config.get("tiers", {}):
            print(f"❌ Tier {tier} introuvable")
            return False
        
        old_price = self.config["tiers"][tier]["price"]
        self.config["tiers"][tier]["price"] = new_price
        
        self._save_config()
        
        print(f"✅ Prix mis à jour pour {tier}:")
        print(f"   {old_price}€ → {new_price}€")
        
        return True
    
    def update_tier_features(self, tier: str, features: Dict[str, Any]) -> bool:
        """Mettre à jour les fonctionnalités d'un tier"""
        if tier not in self.config.get("tiers", {}):
            print(f"❌ Tier {tier} introuvable")
            return False
        
        for feature, value in features.items():
            if feature in self.config["tiers"][tier]:
                old_value = self.config["tiers"][tier][feature]
                self.config["tiers"][tier][feature] = value
                print(f"   {feature}: {old_value} → {value}")
        
        self._save_config()
        
        print(f"✅ Features mises à jour pour {tier}")
        return True
    
    def add_test_scenario(self, name: str, description: str, config: Dict[str, Any]) -> bool:
        """Ajouter un nouveau scénario de test"""
        if "test_scenarios" not in self.config:
            self.config["test_scenarios"] = {}
        
        self.config["test_scenarios"][name] = {
            "description": description,
            **config
        }
        
        self._save_config()
        
        print(f"✅ Scénario ajouté: {name}")
        print(f"   Description: {description}")
        
        return True
    
    def list_scenarios(self):
        """Lister tous les scénarios de test"""
        print("\n🎬 SCÉNARIOS DE TEST:")
        print("=" * 80)
        
        scenarios = self.config.get("test_scenarios", {})
        
        if not scenarios:
            print("   Aucun scénario configuré")
            return
        
        for name, config in scenarios.items():
            print(f"📋 {name}")
            print(f"   Description: {config['description']}")
            
            # Afficher les paramètres spécifiques
            for key, value in config.items():
                if key != "description":
                    print(f"   {key}: {value}")
            print()
        
        print("=" * 80)
    
    def reset_to_defaults(self) -> bool:
        """Remettre la configuration par défaut"""
        default_config = {
            "database": {
                "host": "localhost",
                "port": 3306,
                "name": "web_sentinel_test",
                "user": "test_user",
                "password": "test_password"
            },
            "license_settings": {
                "default_duration_days": 365,
                "grace_period_days": 7,
                "test_mode": True,
                "auto_generate": True
            },
            "tiers": {
                "FREE": {
                    "domains_limit": 3,
                    "export_formats": ["json"],
                    "invasive_tests": False,
                    "api_access": False,
                    "multi_user": False,
                    "price": 0
                },
                "PRO": {
                    "domains_limit": None,
                    "export_formats": ["json", "html"],
                    "invasive_tests": True,
                    "api_access": False,
                    "multi_user": False,
                    "price": 9.99
                },
                "ENTERPRISE": {
                    "domains_limit": None,
                    "export_formats": ["json", "html", "pdf"],
                    "invasive_tests": True,
                    "api_access": True,
                    "multi_user": True,
                    "price": 99.0
                },
                "GOVERNMENT": {
                    "domains_limit": None,
                    "export_formats": ["json", "html", "pdf"],
                    "invasive_tests": True,
                    "api_access": True,
                    "multi_user": True,
                    "air_gap": True,
                    "price": 15000.0
                },
                "FINANCE": {
                    "domains_limit": None,
                    "export_formats": ["json", "html", "pdf"],
                    "invasive_tests": True,
                    "api_access": True,
                    "multi_user": True,
                    "compliance": ["PCI-DSS", "SOX"],
                    "price": 50000.0
                },
                "MEDICAL": {
                    "domains_limit": None,
                    "export_formats": ["json", "html", "pdf"],
                    "invasive_tests": True,
                    "api_access": True,
                    "multi_user": True,
                    "compliance": ["HIPAA", "FDA"],
                    "price": 200000.0
                }
            }
        }
        
        self.config = default_config
        self._save_config()
        
        print("✅ Configuration remise aux valeurs par défaut")
        return True
    
    def backup_config(self) -> str:
        """Créer une sauvegarde de la configuration"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_file = self.config_dir / f"test_config_backup_{timestamp}.json"
        
        with open(backup_file, 'w', encoding='utf-8') as f:
            json.dump(self.config, f, indent=2, ensure_ascii=False)
        
        print(f"✅ Sauvegarde créée: {backup_file}")
        return str(backup_file)
    
    def restore_config(self, backup_file: str) -> bool:
        """Restaurer une sauvegarde de configuration"""
        backup_path = Path(backup_file)
        
        if not backup_path.exists():
            print(f"❌ Fichier de sauvegarde introuvable: {backup_file}")
            return False
        
        try:
            with open(backup_path, 'r', encoding='utf-8') as f:
                backup_config = json.load(f)
            
            self.config = backup_config
            self._save_config()
            
            print(f"✅ Configuration restaurée depuis: {backup_file}")
            return True
            
        except Exception as e:
            print(f"❌ Erreur restauration: {e}")
            return False
    
    def validate_config(self) -> bool:
        """Valider la configuration actuelle"""
        print("🔍 VALIDATION DE LA CONFIGURATION:")
        print("=" * 50)
        
        errors = []
        warnings = []
        
        # Vérifier la structure des tiers
        required_tier_fields = ["domains_limit", "export_formats", "invasive_tests", "api_access", "multi_user", "price"]
        
        for tier_name, tier_config in self.config.get("tiers", {}).items():
            for field in required_tier_fields:
                if field not in tier_config:
                    errors.append(f"Champ manquant '{field}' dans tier {tier_name}")
            
            # Vérifier cohérence prix
            if tier_config.get("price", 0) < 0:
                errors.append(f"Prix négatif dans tier {tier_name}")
            
            # Vérifier export_formats
            if not isinstance(tier_config.get("export_formats"), list):
                errors.append(f"export_formats doit être une liste dans tier {tier_name}")
        
        # Vérifier database config
        if "database" in self.config:
            db_config = self.config["database"]
            if "host" not in db_config or "port" not in db_config:
                warnings.append("Configuration database incomplète")
        
        # Afficher résultats
        if errors:
            print("❌ ERREURS:")
            for error in errors:
                print(f"   • {error}")
        
        if warnings:
            print("⚠️ AVERTISSEMENTS:")
            for warning in warnings:
                print(f"   • {warning}")
        
        if not errors and not warnings:
            print("✅ Configuration valide")
        
        print("=" * 50)
        
        return len(errors) == 0


def main():
    parser = argparse.ArgumentParser(description="📊 Gestionnaire de configuration Web Sentinel")
    parser.add_argument("--list-tiers", action="store_true", help="Lister tous les tiers")
    parser.add_argument("--list-scenarios", action="store_true", help="Lister tous les scénarios")
    parser.add_argument("--tier", help="Tier à modifier")
    parser.add_argument("--price", type=float, help="Nouveau prix")
    parser.add_argument("--backup", action="store_true", help="Créer une sauvegarde")
    parser.add_argument("--restore", help="Restaurer depuis une sauvegarde")
    parser.add_argument("--reset", action="store_true", help="Remettre aux valeurs par défaut")
    parser.add_argument("--validate", action="store_true", help="Valider la configuration")
    
    args = parser.parse_args()
    
    manager = ConfigManager()
    
    if args.list_tiers:
        manager.list_tiers()
    
    elif args.list_scenarios:
        manager.list_scenarios()
    
    elif args.tier and args.price is not None:
        manager.update_tier_price(args.tier, args.price)
    
    elif args.backup:
        manager.backup_config()
    
    elif args.restore:
        manager.restore_config(args.restore)
    
    elif args.reset:
        print("⚠️ Êtes-vous sûr de vouloir remettre la configuration par défaut ? (y/N)")
        response = input().lower()
        if response == 'y':
            manager.reset_to_defaults()
        else:
            print("❌ Annulé")
    
    elif args.validate:
        manager.validate_config()
    
    else:
        print("📊 AIDE RAPIDE:")
        print("  --list-tiers                    # Lister tous les tiers")
        print("  --list-scenarios                # Lister tous les scénarios")
        print("  --tier PRO --price 12.99        # Changer prix tier PRO")
        print("  --backup                        # Créer sauvegarde")
        print("  --restore backup_file.json      # Restaurer sauvegarde")
        print("  --reset                         # Remettre par défaut")
        print("  --validate                      # Valider configuration")


if __name__ == "__main__":
    main()