"""Self-management commands for manta-client."""

from __future__ import annotations

import platform
import shutil
import sys
from pathlib import Path

import typer

from manta_client import __version__
from manta_client.config import config_manager
from manta_client.output import console, is_quiet, print_json, print_key_value, print_success

app = typer.Typer(help="Client self-management")


def _human_size(size_bytes: int) -> str:
    """Format bytes as human-readable size."""
    for unit in ("B", "KB", "MB", "GB"):
        if abs(size_bytes) < 1024:
            return f"{size_bytes:.1f} {unit}"
        size_bytes /= 1024  # type: ignore[assignment]
    return f"{size_bytes:.1f} TB"


def _db_info() -> tuple[str, int]:
    """Return (display string, size in bytes) for local DB."""
    db_path = config_manager.config_dir / "manta.db"
    if not db_path.exists():
        return "Not found", 0
    size = db_path.stat().st_size
    return f"{db_path} ({_human_size(size)})", size


def _sessions_info() -> tuple[str, int, int]:
    """Return (display string, file count, total size) for sessions dir."""
    sessions_dir = config_manager.config_dir / "sessions"
    if not sessions_dir.exists():
        return "Not found", 0, 0
    files = list(sessions_dir.glob("*.jsonl"))
    total = sum(f.stat().st_size for f in files)
    return f"{len(files)} sessions ({_human_size(total)})", len(files), total


@app.command("info")
def info(
    json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
) -> None:
    """Display client environment information."""
    config = config_manager.load_config()
    db_display, db_size = _db_info()
    sessions_display, sessions_count, sessions_size = _sessions_info()

    py = sys.version_info
    data = {
        "client_version": __version__,
        "python_version": f"{py.major}.{py.minor}.{py.micro}",
        "platform": platform.platform(),
        "config_path": str(config_manager.config_path),
        "data_dir": str(config_manager.config_dir),
        "local_db": db_display,
        "sessions": sessions_display,
        "api_url": config.api_url or "Not configured",
        "auth_status": "Authenticated" if config.access_token else "Not authenticated",
        "install_location": str(Path(__file__).resolve().parent.parent),
    }

    if json_output:
        print_json(
            {
                **data,
                "local_db_size_bytes": db_size,
                "sessions_count": sessions_count,
                "sessions_size_bytes": sessions_size,
            }
        )
        return

    print_key_value(data, title="Manta Client Info")


@app.command("update")
def update() -> None:
    """Show upgrade instructions."""
    console.print(f"\n[bold]Current version:[/bold] {__version__}\n")
    console.print("[bold]To upgrade, run:[/bold]\n")
    console.print(
        "  pip install --upgrade manta-client \\\n"
        "    --index-url https://nexus.zilliz.cc/repository/pypi-internal/simple/ \\\n"
        "    --extra-index-url https://pypi.org/simple/\n",
        highlight=False,
    )
    console.print(
        "[bold]After upgrading, sync the Claude Code skill:[/bold]\n"
        "\n"
        "  manta-client skill install-local\n",
        highlight=False,
    )


@app.command("clean")
def clean(
    sessions: bool = typer.Option(False, "--sessions", help="Clean session files"),
    db: bool = typer.Option(False, "--db", help="Clean local database"),
    all_: bool = typer.Option(False, "--all", help="Clean everything"),
) -> None:
    """Clean local cache and data."""
    if all_:
        sessions = db = True

    if not sessions and not db:
        sessions = typer.confirm("Clean session files?", default=False)
        db = typer.confirm("Clean local database?", default=False)

    if not sessions and not db:
        console.print("Nothing to clean.")
        return

    # Show what will be cleaned
    if sessions:
        sessions_dir = config_manager.config_dir / "sessions"
        if sessions_dir.exists():
            files = list(sessions_dir.glob("*.jsonl"))
            total = sum(f.stat().st_size for f in files)
            console.print(f"  Sessions: {len(files)} files ({_human_size(total)})")
        else:
            console.print("  Sessions: directory not found, nothing to clean")
            sessions = False

    if db:
        db_path = config_manager.config_dir / "manta.db"
        if db_path.exists():
            console.print(f"  Database: {_human_size(db_path.stat().st_size)}")
        else:
            console.print("  Database: not found, nothing to clean")
            db = False

    if not sessions and not db:
        return

    if not is_quiet():
        typer.confirm("\nProceed with cleanup?", abort=True)

    if sessions:
        sessions_dir = config_manager.config_dir / "sessions"
        shutil.rmtree(sessions_dir)
        sessions_dir.mkdir(parents=True, exist_ok=True)
        print_success("Session files cleaned.")

    if db:
        db_path = config_manager.config_dir / "manta.db"
        db_path.unlink()
        print_success("Local database cleaned.")
