# standard
# third party
import typer
from rich import box
from rich.panel import Panel

# 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.logger import get_logger
from sunwaee.core.output import console, error, success
from sunwaee.modules.workspaces.model import Workspace

_log = get_logger("modules.workspaces")


def read(
    name: str = typer.Argument(..., help="Workspace name"),
) -> None:
    """Read a workspace."""
    base = get_workspaces_base_dir()
    workspace_dir = base / name
    if not workspace_dir.exists():
        _log.warning("Workspace not found: %r", name)
        error(f"Workspace not found: {name!r}", "NOT_FOUND")

    meta_path = workspace_dir / "metadata.md"
    if meta_path.exists():
        meta, body = read_md(meta_path)
        ws = Workspace.from_dict(name, meta, body)
    else:
        ws = Workspace(name=name)

    _log.debug("Reading workspace %r (id=%s)", ws.name, ws.id)
    append_log(name, "workspaces", "read", item_id=ws.id, item_title=name)

    def human_output() -> None:  # pragma: no cover
        from rich.markdown import Markdown

        is_default = get_default_workspace() == name
        meta_line = "\n".join([
            f"[dim]id:[/dim] {ws.id[:8]}  "
            f"[dim]default:[/dim] {'yes' if is_default else 'no'}  "
            f"[dim]created:[/dim] {ws.created_at[:10]}  "
            f"[dim]updated:[/dim] {ws.updated_at[:10]}",
            f"[dim]path:[/dim] {workspace_dir}",
        ])
        console.print(
            Panel(
                meta_line,
                title=f"[bold]{ws.name}[/bold]",
                box=box.ROUNDED,
                expand=False,
            )
        )
        if ws.body:
            console.print(Markdown(ws.body))

    data = ws.to_dict()
    data["default"] = get_default_workspace() == name
    data["path"] = str(workspace_dir)
    success(data, human_fn=human_output)
