# standard
from typing import Optional

# third party
import typer

# custom
from sunwaee.core.audit import append_log
from sunwaee.core.logger import get_logger
from sunwaee.core.output import console, error, success
from ._helpers import _enrich, _find_in_all, _load

_log = get_logger("modules.notes")


def delete(
    query: str = typer.Argument(..., help="Note id, slug, or title"),
    confirm: bool = typer.Option(False, "--confirm", help="Confirm deletion"),
    workspace: Optional[str] = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Workspace name (default: search all workspaces)",
    ),
) -> None:
    """Delete a note."""
    if not confirm:
        error("Pass --confirm to delete a note", "CONFIRMATION_REQUIRED")

    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)
    deleted_path = path
    append_log(ws, "notes", "delete", item_id=note.id, item_title=note.title)
    path.unlink()
    _log.info("Deleted note %r (id=%s) from %s", note.title, note.id, deleted_path)

    def _deleted() -> None:  # pragma: no cover
        console.print(f"[red]Deleted[/red] '[bold]{note.title}[/bold]'")
        console.print(f"[dim]{deleted_path}[/dim]")

    success(
        {
            "id": note.id,
            "title": note.title,
            "workspace": ws,
            "path": str(deleted_path),
        },
        human_fn=_deleted,
    )
