# standard
from typing import Optional

# third party
import typer

# custom
from sunwaee.config import get_default_workspace, get_project_dir, get_workspace_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.projects.model import Project

_log = get_logger("modules.projects")


def create(
    name: str = typer.Argument(..., help="Project name"),
    workspace: Optional[str] = typer.Option(
        None, "--workspace", "-w", help="Workspace name (default: from config)"
    ),
    body: Optional[str] = typer.Option(
        None, "--body", "-b", help="Project description / details (markdown)"
    ),
) -> None:
    """Create a new project."""
    ws = workspace or get_default_workspace()
    project_dir = get_project_dir(ws, name)

    if project_dir.exists():
        error(f"Project already exists: {name!r}", "ALREADY_EXISTS")

    project_dir.mkdir(parents=True, exist_ok=True)
    ws_dir = get_workspace_dir(ws)
    ensure_git_repo(ws_dir)

    proj = Project(name=name, body=body or "")
    write_md(project_dir / "metadata.md", proj.to_frontmatter_meta(), proj.body)

    _log.info("Created project %r (id=%s) at %s", name, proj.id, project_dir)
    append_log(ws, "projects", "create", item_id=proj.id, item_title=name)

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