#!/usr/bin/env python3
"""
🧪 Gestionnaire de comptes de test pour Web Sentinel
Permet de modifier facilement les comptes de test sans polluer l'application
"""

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

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

class TestAccountManager:
    """Gestionnaire des comptes de test"""
    
    def __init__(self):
        self.config_dir = Path(__file__).parent / "config"
        self.accounts_file = self.config_dir / "accounts.json"
        self.config_file = self.config_dir / "test_config.json"
        self.logs_dir = Path(__file__).parent / "logs"
        
        # Créer les répertoires si nécessaire
        self.logs_dir.mkdir(exist_ok=True)
        
        self.accounts = self._load_accounts()
        self.config = self._load_config()
    
    def _load_accounts(self) -> Dict[str, Any]:
        """Charger les comptes de test"""
        try:
            with open(self.accounts_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            return {"test_accounts": []}
    
    def _load_config(self) -> Dict[str, Any]:
        """Charger la configuration de test"""
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            return {}
    
    def _save_accounts(self):
        """Sauvegarder les comptes de test"""
        with open(self.accounts_file, 'w', encoding='utf-8') as f:
            json.dump(self.accounts, f, indent=2, ensure_ascii=False)
    
    def find_account(self, email: str) -> Optional[Dict[str, Any]]:
        """Trouver un compte par email"""
        for account in self.accounts.get("test_accounts", []):
            if account["email"] == email:
                return account
        return None
    
    def update_tier(self, email: str, new_tier: str) -> bool:
        """Mettre à jour le tier d'un compte"""
        account = self.find_account(email)
        if not account:
            print(f"❌ Compte {email} introuvable")
            return False
        
        if new_tier not in self.config.get("tiers", {}):
            print(f"❌ Tier {new_tier} invalide")
            print(f"   Tiers disponibles: {list(self.config.get('tiers', {}).keys())}")
            return False
        
        old_tier = account["tier"]
        account["tier"] = new_tier
        
        # Mettre à jour les features selon le tier
        tier_config = self.config["tiers"][new_tier]
        account["features"] = {
            "domains_limit": tier_config["domains_limit"],
            "export_formats": tier_config["export_formats"],
            "invasive_tests": tier_config["invasive_tests"],
            "api_access": tier_config["api_access"],
            "multi_user": tier_config["multi_user"]
        }
        
        # Ajouter les features spéciales pour les tiers premium
        if "compliance" in tier_config:
            account["features"]["compliance"] = tier_config["compliance"]
        if "air_gap" in tier_config:
            account["features"]["air_gap"] = tier_config["air_gap"]
        
        self._save_accounts()
        
        print(f"✅ Compte {email} mis à jour:")
        print(f"   {old_tier} → {new_tier}")
        print(f"   Prix: {tier_config['price']}€")
        print(f"   Features: {account['features']}")
        
        return True
    
    def extend_license(self, email: str, days: int) -> bool:
        """Étendre la licence d'un compte"""
        account = self.find_account(email)
        if not account:
            print(f"❌ Compte {email} introuvable")
            return False
        
        # Calculer nouvelle date d'expiration
        current_expiry = datetime.fromisoformat(account["license_expires"].replace('Z', '+00:00'))
        new_expiry = current_expiry + timedelta(days=days)
        account["license_expires"] = new_expiry.isoformat().replace('+00:00', 'Z')
        
        self._save_accounts()
        
        print(f"✅ Licence étendue pour {email}:")
        print(f"   Nouvelle expiration: {account['license_expires']}")
        print(f"   Jours ajoutés: {days}")
        
        return True
    
    def set_license_expiry(self, email: str, days_from_now: int) -> bool:
        """Définir l'expiration de licence (jours à partir d'aujourd'hui)"""
        account = self.find_account(email)
        if not account:
            print(f"❌ Compte {email} introuvable")
            return False
        
        new_expiry = datetime.now(timezone.utc) + timedelta(days=days_from_now)
        account["license_expires"] = new_expiry.isoformat().replace('+00:00', 'Z')
        
        self._save_accounts()
        
        status = "⚠️ EXPIRE BIENTÔT" if days_from_now <= 7 else "✅ Actif"
        print(f"{status} Expiration mise à jour pour {email}:")
        print(f"   Expire dans: {days_from_now} jours")
        print(f"   Date: {account['license_expires']}")
        
        return True
    
    def update_domains_used(self, email: str, domains_count: int) -> bool:
        """Mettre à jour le nombre de domaines utilisés"""
        account = self.find_account(email)
        if not account:
            print(f"❌ Compte {email} introuvable")
            return False
        
        old_count = account["domains_used"]
        account["domains_used"] = domains_count
        
        self._save_accounts()
        
        limit = account["features"]["domains_limit"]
        limit_text = f"/{limit}" if limit else "/∞"
        
        print(f"✅ Domaines mis à jour pour {email}:")
        print(f"   {old_count} → {domains_count}{limit_text}")
        
        if limit and domains_count >= limit:
            print("   ⚠️ LIMITE ATTEINTE")
        
        return True
    
    def show_account(self, email: str) -> bool:
        """Afficher les détails d'un compte"""
        account = self.find_account(email)
        if not account:
            print(f"❌ Compte {email} introuvable")
            return False
        
        print(f"\n📋 COMPTE: {account['email']}")
        print(f"   👤 Nom: {account['name']}")
        print(f"   🎯 Tier: {account['tier']}")
        print(f"   📊 Status: {account['status']}")
        print(f"   📅 Créé: {account['created_at']}")
        print(f"   ⏰ Expire: {account['license_expires']}")
        print(f"   🌐 Domaines: {account['domains_used']}")
        print(f"   🔑 Dernière connexion: {account['last_login']}")
        
        print(f"\n🎛️ FEATURES:")
        features = account['features']
        for key, value in features.items():
            icon = "✅" if value else "❌"
            if isinstance(value, list):
                print(f"   {icon} {key}: {', '.join(value)}")
            elif value is None:
                print(f"   ✅ {key}: illimité")
            else:
                print(f"   {icon} {key}: {value}")
        
        # Vérifier si la licence expire bientôt
        expiry = datetime.fromisoformat(account["license_expires"].replace('Z', '+00:00'))
        days_left = (expiry - datetime.now(timezone.utc)).days
        
        if days_left <= 0:
            print(f"\n❌ LICENCE EXPIRÉE (il y a {abs(days_left)} jours)")
        elif days_left <= 7:
            print(f"\n⚠️ LICENCE EXPIRE DANS {days_left} JOURS")
        else:
            print(f"\n✅ Licence valide ({days_left} jours restants)")
        
        return True
    
    def list_accounts(self):
        """Lister tous les comptes de test"""
        print("\n📋 COMPTES DE TEST DISPONIBLES:")
        print("=" * 80)
        
        for account in self.accounts.get("test_accounts", []):
            expiry = datetime.fromisoformat(account["license_expires"].replace('Z', '+00:00'))
            days_left = (expiry - datetime.now(timezone.utc)).days
            
            status_icon = "❌" if days_left <= 0 else "⚠️" if days_left <= 7 else "✅"
            tier_price = self.config["tiers"].get(account["tier"], {}).get("price", 0)
            
            print(f"{status_icon} {account['email']:<30} | {account['tier']:<12} | {tier_price:>8.2f}€ | {days_left:>3}j")
        
        print("=" * 80)
    
    def create_account(self, email: str, name: str, tier: str = "FREE") -> bool:
        """Créer un nouveau compte de test"""
        if self.find_account(email):
            print(f"❌ Le compte {email} existe déjà")
            return False
        
        if tier not in self.config.get("tiers", {}):
            print(f"❌ Tier {tier} invalide")
            return False
        
        tier_config = self.config["tiers"][tier]
        
        new_account = {
            "email": email,
            "name": name,
            "tier": tier,
            "status": "active",
            "created_at": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "license_expires": (datetime.now(timezone.utc) + timedelta(days=365)).isoformat().replace('+00:00', 'Z'),
            "domains_used": 0,
            "last_login": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "features": {
                "domains_limit": tier_config["domains_limit"],
                "export_formats": tier_config["export_formats"],
                "invasive_tests": tier_config["invasive_tests"],
                "api_access": tier_config["api_access"],
                "multi_user": tier_config["multi_user"]
            }
        }
        
        self.accounts["test_accounts"].append(new_account)
        self._save_accounts()
        
        print(f"✅ Compte créé: {email} ({tier})")
        return True


def main():
    parser = argparse.ArgumentParser(description="🧪 Gestionnaire de comptes de test Web Sentinel")
    parser.add_argument("--email", help="Email du compte à modifier")
    parser.add_argument("--tier", help="Nouveau tier (FREE/PRO/ENTERPRISE/GOVERNMENT/FINANCE/MEDICAL)")
    parser.add_argument("--extend", type=int, help="Étendre la licence de X jours")
    parser.add_argument("--expire-in", type=int, help="Définir expiration dans X jours")
    parser.add_argument("--domains", type=int, help="Nombre de domaines utilisés")
    parser.add_argument("--show", action="store_true", help="Afficher les détails du compte")
    parser.add_argument("--list", action="store_true", help="Lister tous les comptes")
    parser.add_argument("--create", action="store_true", help="Créer un nouveau compte")
    parser.add_argument("--name", help="Nom pour nouveau compte")
    
    args = parser.parse_args()
    
    manager = TestAccountManager()
    
    if args.list:
        manager.list_accounts()
        return
    
    if not args.email and not args.list:
        print("❌ Email requis (sauf pour --list)")
        parser.print_help()
        return
    
    if args.create:
        if not args.name:
            print("❌ --name requis pour créer un compte")
            return
        manager.create_account(args.email, args.name, args.tier or "FREE")
    
    elif args.tier:
        manager.update_tier(args.email, args.tier)
    
    elif args.extend:
        manager.extend_license(args.email, args.extend)
    
    elif args.expire_in is not None:
        manager.set_license_expiry(args.email, args.expire_in)
    
    elif args.domains is not None:
        manager.update_domains_used(args.email, args.domains)
    
    elif args.show:
        manager.show_account(args.email)
    
    else:
        print("📋 AIDE RAPIDE:")
        print("  --list                                    # Lister tous les comptes")
        print("  --email bruno@taaazzz-prog.fr --show     # Voir détails compte")
        print("  --email bruno@taaazzz-prog.fr --tier PRO # Changer tier")
        print("  --email bruno@taaazzz-prog.fr --expire-in 7 # Expire dans 7 jours")


if __name__ == "__main__":
    main()