"""Vexor semantic search tool installation and configuration."""

from __future__ import annotations

import json
import subprocess
from pathlib import Path
from typing import Any

from installer.platform_utils import command_exists
from installer.steps.deps_utils import _run_bash_with_retry


def _configure_vexor_defaults() -> bool:
    """Configure Vexor with recommended defaults for semantic search (OpenAI)."""

    config_dir = Path.home() / ".vexor"
    config_path = config_dir / "config.json"

    try:
        config_dir.mkdir(parents=True, exist_ok=True)

        if config_path.exists():
            config = json.loads(config_path.read_text())
        else:
            config = {}

        config.update(
            {
                "model": "text-embedding-3-small",
                "batch_size": 64,
                "embed_concurrency": 4,
                "extract_concurrency": 4,
                "extract_backend": "auto",
                "provider": "openai",
                "auto_index": True,
                "local_cuda": False,
                "rerank": "bm25",
            }
        )
        config_path.write_text(json.dumps(config, indent=2) + "\n")
        return True
    except Exception:
        return False


def _configure_vexor_local() -> bool:
    """Configure Vexor for local embeddings (no API key needed)."""

    config_dir = Path.home() / ".vexor"
    config_path = config_dir / "config.json"

    try:
        config_dir.mkdir(parents=True, exist_ok=True)

        if config_path.exists():
            config = json.loads(config_path.read_text())
        else:
            config = {}

        config.update(
            {
                "model": "intfloat/multilingual-e5-small",
                "batch_size": 64,
                "embed_concurrency": 4,
                "extract_concurrency": 4,
                "extract_backend": "auto",
                "provider": "local",
                "auto_index": True,
                "local_cuda": False,
                "rerank": "bm25",
            }
        )
        config_path.write_text(json.dumps(config, indent=2) + "\n")
        return True
    except Exception:
        return False


def _is_vexor_local_model_installed() -> bool:
    """Check if the local embedding model is already downloaded."""
    cache_dirs = [
        Path.home() / ".vexor" / "models",
        Path.home() / ".cache" / "huggingface" / "hub",
        Path.home() / ".cache" / "torch" / "sentence_transformers",
    ]
    model_name = "intfloat--multilingual-e5-small"

    for cache_dir in cache_dirs:
        if cache_dir.exists():
            for model_dir in cache_dir.glob(f"*{model_name}*"):
                if model_dir.is_dir():
                    return True
            for model_dir in cache_dir.glob(f"models--{model_name}*"):
                if model_dir.is_dir():
                    return True
    return False


def _setup_vexor_local_model(ui: Any = None) -> bool:
    """Download and setup the local embedding model for Vexor."""
    if _is_vexor_local_model_installed():
        return True

    try:
        if ui:
            with ui.spinner("Downloading local embedding model..."):
                result = subprocess.run(
                    ["vexor", "local", "--setup", "--model", "intfloat/multilingual-e5-small"],
                    capture_output=True,
                    text=True,
                )
            return result.returncode == 0
        else:
            result = subprocess.run(
                ["vexor", "local", "--setup", "--model", "intfloat/multilingual-e5-small"],
                capture_output=True,
                text=True,
            )
            return result.returncode == 0
    except Exception:
        return False


def install_vexor(use_local: bool = False, ui: Any = None) -> bool:
    """Install Vexor semantic search tool and configure defaults."""
    if use_local:
        if command_exists("vexor") and _is_vexor_local_model_installed():
            _configure_vexor_local()
            return True
        if not command_exists("vexor"):
            if not _run_bash_with_retry("uv pip install 'vexor[local]'"):
                return False
        _configure_vexor_local()
        return _setup_vexor_local_model(ui)
    else:
        if command_exists("vexor"):
            _configure_vexor_defaults()
            return True
        _configure_vexor_defaults()
        return True
