# standard
from typing import Optional

# third party
import typer

# custom
from sunwaee.config import is_machine_caller
from sunwaee.core.audit import append_log
from sunwaee.core.editor import open_editor
from sunwaee.core.logger import get_logger
from sunwaee.core.output import console, success
from sunwaee.modules.notes.model import Note
from ._helpers import _enrich, _resolve_dir, _save

_log = get_logger("modules.notes")


def create(
    title: str = typer.Option(..., "--title", "-t", help="Note title"),
    tags: Optional[str] = typer.Option(None, "--tags", help="Comma-separated tags"),
    body: Optional[str] = typer.Option(
        None, "--body", "-b", help="Note body (markdown)"
    ),
    workspace: Optional[str] = typer.Option(
        None, "--workspace", "-w", help="Workspace name (default: from config)"
    ),
) -> None:
    """Create a new note."""
    ws, directory = _resolve_dir(workspace)
    tag_list = [t.strip() for t in tags.split(",")] if tags else []

    if body is None and not is_machine_caller():  # pragma: no cover
        body = open_editor()

    note = Note(title=title, tags=tag_list, body=body or "")
    path = _save(note, directory)
    _log.info("Created note %r (id=%s) at %s", title, note.id, path)
    append_log(ws, "notes", "create", item_id=note.id, item_title=note.title)

    def _created() -> None:  # pragma: no cover
        console.print(f"[green]Created[/green] note '[bold]{note.title}[/bold]'")
        console.print(f"[dim]{path}[/dim]")

    success(_enrich(note, ws, path), human_fn=_created)
