"""WET MCP Server entry point."""

import sys


def _clear_model_cache(model_name: str) -> None:
    """Remove corrupted HuggingFace cache for a model so it re-downloads."""
    import os
    import shutil
    import tempfile
    from pathlib import Path

    cache_dir = Path(
        os.getenv(
            "QWEN3_EMBED_CACHE_PATH",
            os.path.join(tempfile.gettempdir(), "qwen3_embed_cache"),
        )
    )
    # HF Hub cache uses models--org--repo directory naming
    safe_name = model_name.replace("/", "--")
    model_cache = cache_dir / f"models--{safe_name}"
    if model_cache.exists():
        shutil.rmtree(model_cache)
        print(f"  Cleared corrupted cache: {model_cache}")


def _run_auto_setup() -> None:
    """Run auto-setup for SearXNG and Playwright."""
    print("  Step 1/3: Installing SearXNG and Playwright...")
    from wet_mcp.setup import run_auto_setup

    run_auto_setup()
    print("  SearXNG and Playwright setup complete.")


def _validate_cloud_models(settings) -> bool:
    """Check if cloud embedding and reranking models are valid.
    Returns True if cloud models are ready to use and local models are not needed.
    """
    from wet_mcp.embedder import init_backend
    from wet_mcp.server import _EMBEDDING_CANDIDATES

    print("  Step 2/3: Validating cloud embedding models...")
    model = settings.resolve_embedding_model()
    candidates = [model] if model else _EMBEDDING_CANDIDATES
    litellm_kwargs = settings.get_embedding_litellm_kwargs()

    cloud_ok = False
    for candidate in candidates:
        try:
            backend = init_backend("litellm", candidate, **litellm_kwargs)
            dims = backend.check_available()
            if dims > 0:
                print(f"  Cloud embedding ready: {candidate} (dims={dims})")
                cloud_ok = True
                break
        except Exception:
            continue

    if cloud_ok:
        print("  Step 3/3: Validating cloud reranker...")
        rerank_model = settings.resolve_rerank_model()
        if rerank_model:
            from wet_mcp.reranker import init_reranker

            rerank_kwargs = settings.get_rerank_litellm_kwargs()
            try:
                reranker = init_reranker("litellm", rerank_model, **rerank_kwargs)
                if reranker.check_available():
                    print(f"  Cloud reranker ready: {rerank_model}")
                    print("Warmup complete! Cloud models will be used.")
                    return True
            except Exception:
                pass

        print("Warmup complete! Cloud embedding will be used.")
        return True

    return False


def _download_local_embedding_model(settings) -> None:
    """Download and validate the local embedding model."""
    print("  Step 2/3: Downloading local embedding model (~570 MB)...")
    print("  This may take a few minutes on first run.")

    local_embed_model = settings.resolve_local_embedding_model()
    from qwen3_embed import TextEmbedding

    try:
        embed_model = TextEmbedding(model_name=local_embed_model)
        result = list(embed_model.embed(["warmup test"]))
        if result:
            print(f"  Local embedding ready (dims={len(result[0])})")
        else:
            print("  WARNING: Local embedding test failed")
    except Exception as exc:
        if "NO_SUCHFILE" in str(exc) or "doesn't exist" in str(exc):
            print("  Corrupted cache detected, clearing and retrying...")
            _clear_model_cache(local_embed_model)
            embed_model = TextEmbedding(model_name=local_embed_model)
            result = list(embed_model.embed(["warmup test"]))
            if result:
                print(f"  Local embedding ready (dims={len(result[0])})")
            else:
                print("  WARNING: Local embedding test failed after retry")
        else:
            raise


def _download_local_reranker_model(settings) -> None:
    """Download and validate the local reranker model."""
    if not settings.rerank_enabled:
        print("  Step 3/3: Reranking disabled, skipping.")
        return

    print("  Step 3/3: Downloading local reranker model (~570 MB)...")
    local_rerank_model = settings.resolve_local_rerank_model()
    from qwen3_embed import TextCrossEncoder

    try:
        reranker = TextCrossEncoder(model_name=local_rerank_model)
        scores = list(reranker.rerank("test query", ["test document"]))
        if scores:
            print("  Local reranker ready")
        else:
            print("  WARNING: Local reranker test failed")
    except Exception as exc:
        if "NO_SUCHFILE" in str(exc) or "doesn't exist" in str(exc):
            print("  Corrupted cache detected, clearing and retrying...")
            _clear_model_cache(local_rerank_model)
            reranker = TextCrossEncoder(model_name=local_rerank_model)
            scores = list(reranker.rerank("test query", ["test document"]))
            if scores:
                print("  Local reranker ready")
            else:
                print("  WARNING: Local reranker test failed after retry")
        else:
            raise


def _warmup() -> None:
    """Pre-download models and run setup to avoid first-run delays.

    Run this before adding wet-mcp to your MCP config:
        uvx --python 3.13 wet-mcp warmup

    This installs SearXNG, Playwright/Chromium, and downloads the local
    embedding + reranking models (~1.1 GB total) so the first real
    connection does not timeout.
    """
    print("WET MCP warmup: running first-time setup...")

    # 1. Run auto-setup (SearXNG + Playwright)
    _run_auto_setup()

    # 2. Check API keys -- if valid cloud keys exist, skip local download
    from wet_mcp.config import settings

    mode = settings.setup_litellm()
    if mode in ("proxy", "sdk"):
        print(f"  LiteLLM mode: {mode}")
        if _validate_cloud_models(settings):
            return
        print("  Cloud embedding not available, falling back to local models...")

    # 3. Download local embedding model
    _download_local_embedding_model(settings)

    # 4. Download local reranker model
    _download_local_reranker_model(settings)

    print("Warmup complete!")


def _cli() -> None:
    """CLI dispatcher: server (default), warmup, or setup-sync subcommand."""
    if len(sys.argv) >= 2 and sys.argv[1] == "warmup":
        _warmup()
    elif len(sys.argv) >= 2 and sys.argv[1] == "setup-sync":
        from wet_mcp.sync import setup_sync

        remote_type = sys.argv[2] if len(sys.argv) >= 3 else "drive"
        setup_sync(remote_type)
    else:
        from wet_mcp.server import main

        main()


if __name__ == "__main__":
    _cli()
