"""linear-canal profile — View and switch embedding profiles.

Profiles control which embedding model is used and how much RAM is allocated.
Settings are stored locally in ~/.linear-canal/profile.json — no server needed.

Profiles
--------
  minimal   BAAI/bge-small-en-v1.5  384-dim  ~500 MB RAM   Fast, low memory
  standard  BAAI/bge-base-en-v1.5   768-dim  ~1.5 GB RAM   Better recall
"""
from __future__ import annotations

import json
from pathlib import Path

import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel

console = Console()

_PROFILE_FILE = Path.home() / ".linear-canal" / "profile.json"

_PROFILES = {
    "minimal": {
        "model":       "BAAI/bge-small-en-v1.5",
        "dims":        384,
        "table":       "lc_chunks_384",
        "ram":         "~500 MB",
        "description": "Fast, low memory — good for laptops",
    },
    "standard": {
        "model":       "BAAI/bge-base-en-v1.5",
        "dims":        768,
        "table":       "lc_chunks_768",
        "ram":         "~1.5 GB",
        "description": "Better recall — recommended for desktops",
    },
}


def _read_profile() -> str:
    try:
        data = json.loads(_PROFILE_FILE.read_text())
        return data.get("profile", "minimal")
    except Exception:
        return "minimal"


def _write_profile(name: str) -> None:
    _PROFILE_FILE.parent.mkdir(parents=True, exist_ok=True)
    _PROFILE_FILE.write_text(json.dumps({"profile": name}, indent=2))


@click.group("profile")
def profile_cmd() -> None:
    """View and switch embedding profiles."""


@profile_cmd.command("show")
def show_profile() -> None:
    """Show the current profile and all available options."""
    active = _read_profile()

    t = Table(show_header=True, header_style="bold grey58", box=None, padding=(0, 2))
    t.add_column("Profile",     style="white",   no_wrap=True)
    t.add_column("Model",       style="dim",      no_wrap=True)
    t.add_column("Dims",        justify="right",  style="dim")
    t.add_column("RAM",         justify="right",  style="dim")
    t.add_column("Description", style="dim")
    t.add_column("",            justify="center", no_wrap=True)

    for name, info in _PROFILES.items():
        marker = "[bold green]● active[/bold green]" if name == active else ""
        style  = "bold" if name == active else "dim"
        t.add_row(
            f"[{style}]{name}[/{style}]",
            info["model"],
            str(info["dims"]),
            info["ram"],
            info["description"],
            marker,
        )

    console.print(Panel(t, title="[bold orange1]Embedding Profiles[/bold orange1]",
                        border_style="orange1"))
    console.print(
        f"[dim]Config: {_PROFILE_FILE}\n"
        "Change with: [bold]linear-canal profile set minimal|standard[/bold][/dim]"
    )


@profile_cmd.command("set")
@click.argument("profile_name", type=click.Choice(["minimal", "standard"]))
def set_profile(profile_name: str) -> None:
    """Switch to a different embedding profile.

    Takes effect on the next `linear-canal setup` or `linear-canal add` run.
    Existing LanceDB vectors for the old profile are NOT deleted automatically
    — run `linear-canal db` and press D to remove them if you want to free space.
    """
    current = _read_profile()
    if current == profile_name:
        console.print(f"[yellow]Already using profile:[/yellow] [bold]{profile_name}[/bold]")
        return

    _write_profile(profile_name)
    info = _PROFILES[profile_name]
    console.print(
        f"[green]✓[/green] Profile set to [bold]{profile_name}[/bold]\n\n"
        f"  Model : {info['model']}\n"
        f"  Dims  : {info['dims']}\n"
        f"  RAM   : {info['ram']}\n\n"
        "[dim]Re-index your projects to use the new profile:\n"
        "  linear-canal setup          (current directory)\n"
        "  linear-canal add <path>     (any project)[/dim]"
    )
