# standard
from typing import Optional

# third party
import typer

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


def update(
    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)"
    ),
    set_default: bool = typer.Option(False, "--set-default", help="Set as default project"),
) -> None:
    """Update a project."""
    if body is None and not set_default:
        error("Specify at least one of --body or --set-default", "VALIDATION_ERROR")

    ws = workspace or get_default_workspace()
    project_dir = get_project_dir(ws, name)
    if not project_dir.exists():
        error(f"Project not found: {name!r}", "NOT_FOUND")

    meta_path = project_dir / "metadata.md"
    if meta_path.exists():
        meta, existing_body = read_md(meta_path)
        proj = Project.from_dict(name, meta, existing_body)
    else:
        proj = Project(name=name)

    if body is not None:
        proj.body = body
    if set_default:
        set_default_project(ws, name)

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

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