#!/usr/bin/env python3
"""Upload trained model to HuggingFace Hub."""

from pathlib import Path
from huggingface_hub import HfApi, create_repo

# ⚠️ CONFIGURAÇÃO - MUDAR PARA SEU USERNAME DO HUGGINGFACE!
REPO_ID = "mlima001/denes-router"

# Paths
MODEL_DIR = Path(__file__).parent / "models" / "domain-classifier"

def upload_model():
    """Upload model to HuggingFace Hub."""

    print("=" * 70)
    print("🤗 HuggingFace Model Upload")
    print("=" * 70)
    print()

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

    # Verificar se modelo existe
    if not MODEL_DIR.exists():
        print(f"❌ ERROR: Model directory not found at {MODEL_DIR}")
        print()
        print("Make sure you have trained the model first:")
        print("   cd ../")
        print("   uv run python cli.py train")
        print()
        return

    if not (MODEL_DIR / "model.safetensors").exists():
        print(f"❌ ERROR: model.safetensors not found in {MODEL_DIR}")
        print()
        print("Files found:")
        for file in MODEL_DIR.iterdir():
            print(f"   - {file.name}")
        print()
        return

    print(f"📦 Model directory: {MODEL_DIR}")
    print(f"📤 Target repository: {REPO_ID}")
    print(f"🔒 Visibility: Private (requires HF Pro)")
    print()

    # Listar arquivos que serão uploadados
    files = list(MODEL_DIR.glob("*"))
    total_size = sum(f.stat().st_size for f in files if f.is_file())

    print(f"📋 Files to upload ({len(files)}):")
    for file in sorted(files):
        if file.is_file():
            size_mb = file.stat().st_size / (1024 * 1024)
            print(f"   • {file.name:30s} ({size_mb:>7.1f} MB)")

    print(f"\n   Total size: {total_size / (1024 * 1024):.1f} MB")
    print()

    # Confirmar upload
    response = input("Continue with upload? (y/N): ")
    if response.lower() != "y":
        print("\n❌ Upload cancelled")
        return

    print("\n" + "=" * 70)
    print("Starting upload...")
    print("=" * 70 + "\n")

    # Criar API client
    api = HfApi()

    # Criar repositório (se não existir)
    try:
        print("📝 Creating/verifying repository...")
        create_repo(
            repo_id=REPO_ID,
            repo_type="model",
            private=True,  # Modelo privado (requer HF Pro)
            exist_ok=True
        )
        print("   ✓ Repository ready")
    except Exception as e:
        print(f"   ⚠️  Warning: {e}")
        print("   Continuing with upload...")

    # Upload de todos os arquivos
    print("\n📤 Uploading files to HuggingFace Hub...")
    print("   (This may take a few minutes for large files)\n")

    try:
        api.upload_folder(
            folder_path=str(MODEL_DIR),
            repo_id=REPO_ID,
            repo_type="model",
            commit_message="Upload BERT domain classifier model (trained on 1577 examples, 100% test accuracy)",
        )

        print("\n" + "=" * 70)
        print("✅ Upload Complete!")
        print("=" * 70)
        print()
        print(f"🔗 View your model at:")
        print(f"   https://huggingface.co/{REPO_ID}")
        print()
        print("📝 Next steps:")
        print(f"   1. Edit model_loader.py and change HF_REPO_ID to: {REPO_ID}")
        print("   2. Test download: python test_hf_download.py")
        print("   3. Deploy to production!")
        print()

    except Exception as e:
        print(f"\n❌ Upload failed: {e}")
        print()
        print("Common issues:")
        print("   • Not logged in: Run 'huggingface-cli login'")
        print("   • No HF Pro: Private repos require Pro subscription")
        print("   • Network error: Check your internet connection")
        print()


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