# standard
from typing import Optional

# third party
import typer

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


def update(
    name: str = typer.Argument(..., help="Workspace name"),
    body: Optional[str] = typer.Option(
        None, "--body", "-b", help="Workspace description / details (markdown)"
    ),
    set_default: bool = typer.Option(False, "--set-default", help="Set as default workspace"),
) -> None:
    """Update a workspace."""
    if body is None and not set_default:
        error("Specify at least one of --body or --set-default", "VALIDATION_ERROR")

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

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

    if body is not None:
        ws.body = body
    if set_default:
        set_default_workspace(name)

    ws.touch()
    write_md(meta_path, ws.to_frontmatter_meta(), ws.body)
    append_log(name, "workspaces", "update", item_id=ws.id, item_title=name)

    data = ws.to_dict()
    data["default"] = get_default_workspace() == name
    data["path"] = str(workspace_dir)
    success(
        data,
        human_fn=lambda: console.print(
            f"[green]Updated[/green] workspace '[bold]{name}[/bold]'"
        ),
    )
