# standard
from pathlib import Path

# third party
from rich import box
from rich.table import Table

# custom
from sunwaee.config import get_default_workspace, get_workspaces_base_dir
from sunwaee.core.audit import append_log
from sunwaee.core.fs import read_md
from sunwaee.core.output import console, success
from sunwaee.modules.workspaces.model import Workspace


def _load_workspace(workspace_dir: Path) -> Workspace:
    meta_path = workspace_dir / "metadata.md"
    if meta_path.exists():
        meta, body = read_md(meta_path)
        return Workspace.from_dict(workspace_dir.name, meta, body)
    return Workspace(name=workspace_dir.name)


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

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

    workspaces = [_load_workspace(d) for d in workspace_dirs]

    data = [
        {**ws.to_dict(), "default": ws.name == default, "path": str(workspace_dirs[i])}
        for i, ws in enumerate(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 ws, d in zip(workspaces, workspace_dirs):
            is_default = ws.name == default
            table.add_row(
                f"[bold]{ws.name}[/bold]" if is_default else ws.name,
                "[green]✓[/green]" if is_default else "",
                str(d),
            )
        console.print(table)

    append_log(default or "personal", "workspaces", "list")
    success(data, human_fn=human_output)
