import shutil

import typer
from rich import box
from rich.table import Table

from sunwaee.config import (
    get_default_workspace,
    get_workspaces_base_dir,
    set_default_workspace,
)
from sunwaee.core.logger import get_logger
from sunwaee.core.output import console, error, success

app = typer.Typer(name="workspace", help="Manage workspaces.")
_log = get_logger("modules.workspaces")


@app.command("create")
def create(
    name: str = typer.Argument(..., help="Workspace name"),
) -> None:
    """Create a new workspace."""
    base = get_workspaces_base_dir()
    workspace_dir = base / name
    if workspace_dir.exists():
        error(f"Workspace already exists: {name!r}", "ALREADY_EXISTS")

    workspace_dir.mkdir(parents=True, exist_ok=True)
    _log.info("Created workspace %r at %s", name, workspace_dir)

    success(
        {"name": name, "path": str(workspace_dir)},
        human_fn=lambda: console.print(
            f"[green]Created[/green] workspace '[bold]{name}[/bold]' → {workspace_dir}"
        ),
    )


@app.command("list")
def list_workspaces() -> None:
    """List all workspaces."""
    base = get_workspaces_base_dir()
    default = get_default_workspace()

    if not base.exists():
        success([], human_fn=lambda: console.print("[dim]No workspaces found.[/dim]"))
        return

    workspaces = sorted(
        [d for d in base.iterdir() if d.is_dir() and not d.name.startswith(".")],
        key=lambda d: d.name,
    )

    data = [
        {"name": w.name, "default": w.name == default, "path": str(w)}
        for w in workspaces
    ]

    def human_output() -> None:  # pragma: no cover
        if not workspaces:
            console.print("[dim]No workspaces found.[/dim]")
            return
        table = Table(box=box.SIMPLE, show_header=True, header_style="bold")
        table.add_column("Name")
        table.add_column("Default", width=10)
        table.add_column("Path", style="dim")
        for w in workspaces:
            is_default = w.name == default
            table.add_row(
                f"[bold]{w.name}[/bold]" if is_default else w.name,
                "[green]✓[/green]" if is_default else "",
                str(w),
            )
        console.print(table)

    success(data, human_fn=human_output)


@app.command("set-default")
def set_default(
    name: str = typer.Argument(..., help="Workspace name to set as default"),
) -> None:
    """Set the default workspace."""
    base = get_workspaces_base_dir()
    if not (base / name).exists():
        error(f"Workspace not found: {name!r}", "NOT_FOUND")

    set_default_workspace(name)

    success(
        {"name": name},
        human_fn=lambda: console.print(
            f"[green]Default workspace set to '[bold]{name}[/bold]'"
        ),
    )


@app.command("delete")
def delete(
    name: str = typer.Argument(..., help="Workspace name"),
    confirm: bool = typer.Option(False, "--confirm", help="Confirm deletion"),
) -> None:
    """Delete a workspace and all its data."""
    if not confirm:
        error("Pass --confirm to delete a workspace", "CONFIRMATION_REQUIRED")

    base = get_workspaces_base_dir()
    workspace_dir = base / name
    if not workspace_dir.exists():
        error(f"Workspace not found: {name!r}", "NOT_FOUND")

    shutil.rmtree(workspace_dir)
    _log.info("Deleted workspace %r from %s", name, workspace_dir)

    success(
        {"name": name},
        human_fn=lambda: console.print(
            f"[red]Deleted[/red] workspace '[bold]{name}[/bold]' and all its data"
        ),
    )
