# 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, error, success
from ._helpers import _enrich, _find_in_all, _load, _save

_log = get_logger("modules.notes")


def update(
    query: str = typer.Argument(..., help="Note id, slug, or title"),
    title: Optional[str] = typer.Option(None, "--title", "-t", help="New title"),
    tags: Optional[str] = typer.Option(
        None, "--tags", help="New tags (comma-separated)"
    ),
    body: Optional[str] = typer.Option(None, "--body", "-b", help="New body"),
    workspace: Optional[str] = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Workspace name (default: search all workspaces)",
    ),
) -> None:
    """Update a note. Without flags (human caller), opens $EDITOR for the body."""
    found = _find_in_all(query, workspace)
    if found is None:
        error(f"Note not found: {query!r}", "NOT_FOUND")
    ws, directory, path = found

    note = _load(path)
    changed = False

    if title is not None:
        note.title = title
        changed = True
    if tags is not None:
        note.tags = [t.strip() for t in tags.split(",")]
        changed = True
    if body is not None:
        note.body = body
        changed = True

    if not changed and not is_machine_caller():  # pragma: no cover
        note.body = open_editor(note.body)
        changed = True

    if changed:
        note.touch()
        _save(note, directory, path)
        _log.info("Updated note %r (id=%s) at %s", note.title, note.id, path)
        append_log(ws, "notes", "update", item_id=note.id, item_title=note.title)

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

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