#!/usr/bin/env python3
"""
Setup OpenRouter Monitor per Kuki
Configura API key e testa la connessione
"""

import os
import json
import requests
from pathlib import Path
import yaml

def setup_api_key():
    """Setup guidato dell'API key OpenRouter"""
    print("🔧 **SETUP OPENROUTER MONITOR**")
    print()
    
    # Controlla se già configurata
    config_file = Path.home() / ".hermes" / "config.yaml"
    if config_file.exists():
        with open(config_file, 'r') as f:
            config = yaml.safe_load(f)
            
        providers = config.get('providers', {})
        openrouter = providers.get('openrouter', {})
        
        if openrouter.get('api_key'):
            print("✅ API key OpenRouter già configurata in config.yaml")
            return openrouter['api_key']
    
    print("❓ API key OpenRouter non trovata.")
    print("🔗 Vai su: https://openrouter.ai/keys")
    print("📋 Copia la tua API key")
    print()
    
    api_key = input("🔑 Incolla la tua OpenRouter API key: ").strip()
    
    if not api_key:
        print("❌ Nessuna API key inserita")
        return None
        
    # Test API key
    print("🧪 Testo la connessione...")
    
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.get(
            'https://openrouter.ai/api/v1/auth/key',
            headers=headers,
            timeout=10
        )
        
        if response.status_code == 200:
            data = response.json()
            print("✅ Connessione OK!")
            
            # Salva in config.yaml
            if not config_file.exists():
                config = {}
            else:
                with open(config_file, 'r') as f:
                    config = yaml.safe_load(f) or {}
                    
            if 'providers' not in config:
                config['providers'] = {}
            if 'openrouter' not in config['providers']:
                config['providers']['openrouter'] = {}
                
            config['providers']['openrouter']['api_key'] = api_key
            
            # Backup
            if config_file.exists():
                backup_file = config_file.with_suffix('.yaml.backup')
                import shutil
                shutil.copy2(config_file, backup_file)
                print(f"💾 Backup creato: {backup_file}")
            
            with open(config_file, 'w') as f:
                yaml.dump(config, f, default_flow_style=False)
                
            print(f"💾 API key salvata in: {config_file}")
            return api_key
            
        else:
            print(f"❌ API key non valida: {response.status_code}")
            return None
            
    except Exception as e:
        print(f"❌ Errore test connessione: {e}")
        return None

def main():
    """Setup principale"""
    api_key = setup_api_key()
    
    if api_key:
        print()
        print("🎉 **SETUP COMPLETATO!**")
        print()
        print("✅ Ora puoi usare:")
        print("   📊 python3 openrouter_monitor.py daily")
        print("   📈 python3 openrouter_monitor.py weekly")
        print()
        print("🔄 Prossimo step: configurare i cron job automatici")
        
        # Test rapido
        print("\n🧪 **TEST RAPIDO**")
        os.system("python3 /home/oem/.hermes/scripts/openrouter_monitor.py daily")
    else:
        print("❌ Setup non completato")

if __name__ == "__main__":
    main()