#!/usr/bin/env python3
"""Test HuggingFace model download and classification."""

import os
import sys
from pathlib import Path
import time

# Add src to path for local testing
sys.path.insert(0, str(Path(__file__).parent / "src"))

# ⚠️ CONFIGURAÇÃO - MUDAR PARA SEU USERNAME DO HUGGINGFACE!
HF_REPO_ID = "SEU_USERNAME/denes-domain-classifier"  # Exemplo: "john-doe/denes-domain-classifier"

# Force HuggingFace Hub usage (override local model)
os.environ["DENES_USE_HF_HUB"] = "true"
os.environ["DENES_MODEL_REPO"] = HF_REPO_ID

def test_download():
    """Test model download from HuggingFace Hub."""

    print("=" * 70)
    print("🧪 Testing HuggingFace Hub Download")
    print("=" * 70)
    print()

    # Verificar configuração
    if "SEU_USERNAME" in HF_REPO_ID:
        print("❌ ERROR: You need to configure your HuggingFace username!")
        print()
        print("Edit this file (test_hf_download.py) and change:")
        print('   HF_REPO_ID = "SEU_USERNAME/denes-domain-classifier"')
        print("to:")
        print('   HF_REPO_ID = "your-real-username/denes-domain-classifier"')
        print()
        return

    print(f"📦 Repository: {HF_REPO_ID}")
    print(f"🔐 Auth: Using token from huggingface-cli login")
    print()

    # Verificar se token existe
    token_path = Path.home() / ".huggingface" / "token"
    if not token_path.exists():
        print("⚠️  WARNING: HuggingFace token not found!")
        print()
        print("You need to login first:")
        print("   pip install huggingface_hub")
        print("   huggingface-cli login")
        print()
        print("This will save your token to: ~/.huggingface/token")
        print()
        return

    print("✓ HuggingFace token found")
    print()

    # Renomear modelo local se existir (para forçar download)
    local_model = Path(__file__).parent / "models" / "domain-classifier"
    local_backup = Path(__file__).parent / "models" / "domain-classifier.backup"

    if local_model.exists():
        print(f"📁 Local model found at: {local_model}")
        print("   Moving to backup to force HF download...")
        if local_backup.exists():
            import shutil
            shutil.rmtree(local_backup)
        local_model.rename(local_backup)
        print("   ✓ Local model backed up")
        print()

    # Import e teste
    print("📥 Importing classifier (will trigger download)...")
    print("   (First download may take 1-2 minutes)")
    print()

    try:
        start = time.perf_counter()

        from denes_router_classifier import classify_domain

        load_time = time.perf_counter() - start

        print(f"✓ Model loaded in {load_time:.1f}s")
        print()

        # Test queries
        test_cases = [
            "Busca el clima en Asunción",
            "No tengo internet",
            "¿Cuál es la capital de Francia?",
        ]

        print("🧪 Testing classifications...")
        print()

        all_correct = True
        for text in test_cases:
            result = classify_domain(text)
            print(f"   '{text}'")
            print(f"   → {result.primary} ({result.confidence * 100:.1f}%)")
            print()

        print("=" * 70)
        print("✅ SUCCESS!")
        print("=" * 70)
        print()
        print("HuggingFace Hub integration is working correctly!")
        print()
        print("📊 Cache location:")
        hf_cache = Path.home() / ".cache" / "huggingface"
        if hf_cache.exists():
            cache_size = sum(f.stat().st_size for f in hf_cache.rglob("*") if f.is_file())
            print(f"   {hf_cache}")
            print(f"   Size: {cache_size / (1024**3):.2f} GB")
        print()

        # Restaurar modelo local
        if local_backup.exists():
            print("📁 Restoring local model...")
            if local_model.exists():
                import shutil
                shutil.rmtree(local_model)
            local_backup.rename(local_model)
            print("   ✓ Local model restored")
            print()

        print("✅ You can now deploy to production!")
        print()

    except Exception as e:
        print(f"\n❌ Test failed: {e}")
        print()
        print("Common issues:")
        print("   • Not logged in: Run 'huggingface-cli login'")
        print("   • Wrong repo ID: Check your username in HF_REPO_ID")
        print("   • Private repo without Pro: Make repo public or upgrade to HF Pro")
        print("   • Network error: Check your internet connection")
        print()

        # Restaurar modelo local em caso de erro
        if local_backup.exists():
            print("📁 Restoring local model from backup...")
            if local_model.exists():
                import shutil
                shutil.rmtree(local_model)
            local_backup.rename(local_model)
            print("   ✓ Local model restored")


if __name__ == "__main__":
    try:
        test_download()
    except KeyboardInterrupt:
        print("\n\n❌ Test cancelled by user")
    except Exception as e:
        print(f"\n❌ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
