# standard
from typing import Optional

# third party
import typer

# custom
from sunwaee.config import get_workspaces_base_dir
from sunwaee.core.audit import append_log
from sunwaee.core.fs import write_md
from sunwaee.core.git import ensure_git_repo
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 create(
    name: str = typer.Argument(..., help="Workspace name"),
    body: Optional[str] = typer.Option(
        None, "--body", "-b", help="Workspace description / details (markdown)"
    ),
) -> 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)
    ensure_git_repo(workspace_dir)

    ws = Workspace(name=name, body=body or "")
    write_md(workspace_dir / "metadata.md", ws.to_frontmatter_meta(), ws.body)

    _log.info("Created workspace %r (id=%s) at %s", name, ws.id, workspace_dir)
    append_log(name, "workspaces", "create", item_id=ws.id, item_title=name)

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