# standard
from typing import Annotated, Literal

# third party
# 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.git import ensure_git_repo
from sunwaee.core.tools import err, ok, tool
from sunwaee.modules.workspaces.model import Workspace


def _load(name: str) -> Workspace | None:
    meta_path = get_workspaces_base_dir() / name / "metadata.md"
    if not meta_path.exists():
        return None
    meta, body = read_md(meta_path)
    return Workspace.from_dict(name, meta, body)


@tool(
    "Manage workspaces. Actions: "
    "'create' (requires name, optional body), "
    "'list' returns all workspaces with full metadata, "
    "'read' (requires name) returns a single workspace in full detail, "
    "'update' (requires name; optional body, set_default)."
)
def workspaces(
    action: Annotated[Literal["create", "list", "read", "update"], "Action to perform"],
    name: Annotated[str | None, "Workspace name — required for create/update"] = None,
    body: Annotated[str | None, "Workspace description / details (markdown)"] = None,
    set_default: Annotated[bool, "Set as the default workspace (update only)"] = False,
) -> str:
    base = get_workspaces_base_dir()

    if action == "list":
        if not base.exists():
            return ok([])
        default = get_default_workspace()
        result = []
        for d in sorted(base.iterdir()):
            if not d.is_dir() or d.name.startswith("."):
                continue
            ws = _load(d.name) or Workspace(name=d.name)
            entry = ws.to_dict()
            entry["default"] = ws.name == default
            entry["path"] = str(d)
            result.append(entry)
        return ok(result)

    if not name:
        return err(f"'name' is required for action={action!r}")

    if action == "create":
        workspace_dir = base / name
        if workspace_dir.exists():
            return err(f"Workspace already exists: {name!r}")
        workspace_dir.mkdir(parents=True, exist_ok=True)
        ensure_git_repo(workspace_dir)
        ws = Workspace(name=name, body=body or "")
        write_md(workspace_dir / "metadata.md", ws.to_frontmatter_meta(), ws.body)
        append_log(name, "workspaces", "create", item_id=ws.id, item_title=name)
        data = ws.to_dict()
        data["path"] = str(workspace_dir)
        return ok(data)

    if action == "read":
        workspace_dir = base / name
        if not workspace_dir.exists():
            return err(f"Workspace not found: {name!r}")
        ws = _load(name) or Workspace(name=name)
        append_log(name, "workspaces", "read", item_id=ws.id, item_title=name)
        data = ws.to_dict()
        data["default"] = get_default_workspace() == name
        data["path"] = str(workspace_dir)
        return ok(data)

    if action == "update":
        workspace_dir = base / name
        if not workspace_dir.exists():
            return err(f"Workspace not found: {name!r}")
        if body is None and not set_default:
            return err("Specify at least one of body or set_default=true")
        ws = _load(name) or Workspace(name=name)
        if body is not None:
            ws.body = body
        if set_default:
            set_default_workspace(name)
        ws.touch()
        write_md(workspace_dir / "metadata.md", 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)
        return ok(data)

    return err(f"Unknown action: {action!r}")  # pragma: no cover


TOOLS = [workspaces._tool]
