"""
llmpm clean

Removes the managed virtualenv (~/.llmpm/venv) so it will be recreated
fresh on the next llmpm invocation.

Use --all to also delete downloaded models and the registry.
"""

from __future__ import annotations

import shutil
from pathlib import Path

import click

from llmpm import display
from llmpm._venv import VENV_DIR

# Force rich to load its unicode/cell-width data NOW, before any venv
# directory may be deleted below.  Rich lazy-imports these on first render;
# if the venv is gone by then the import fails with "No module named '...'".
try:
    from rich.cells import get_character_cell_size as _  # noqa: F401
except Exception:  # pragma: no cover
    pass


@click.command("clean")
@click.option(
    "--all", "remove_all", is_flag=True,
    help="Also remove downloaded models and the registry (~/.llmpm/).",
)
@click.option(
    "--yes", "-y", is_flag=True,
    help="Skip confirmation prompt.",
)
def clean(remove_all: bool, yes: bool) -> None:
    """Remove the managed environment (~/.llmpm/venv).

    Downloaded models and the registry are kept unless --all is given.
    """
    display.header("clean")
    display.blank()

    targets: list[tuple[Path, str]] = [(VENV_DIR, "Isolated environment")]
    if remove_all:
        llmpm_home = VENV_DIR.parent  # ~/.llmpm
        targets = [
            (llmpm_home, "All llmpm data (models, registry, environment)"),
        ]

    for target, label in targets:
        if target.exists():
            display.info(f"{label}  [dim]{target}[/]")
        else:
            display.info(
                f"{label}  [dim]{target}[/]"
                "  [dim](not found — nothing to remove)[/]"
            )

    display.blank()

    if not yes:
        confirmed = click.confirm("  Proceed?", default=False)
        display.blank()
        if not confirmed:
            display.info("Cancelled.")
            display.blank()
            raise SystemExit(0)

    for target, label in targets:
        if not target.exists():
            display.warn(f"[dim]{target}[/] does not exist — skipping.")
            display.blank()
            continue
        try:
            shutil.rmtree(target)
            display.ok(f"Removed  [dim]{target}[/]")
        except OSError as exc:
            display.error(f"Could not remove [bold]{target}[/]: {exc}")
            raise SystemExit(1) from None

    display.blank()

    if not remove_all:
        display.info(
            "Downloaded models and registry were kept.\n\n"
            "  To remove everything:  [bold cyan]llmpm clean --all[/]"
        )
        display.blank()
