# standard
from typing import Optional

# third party
import typer
from rich import box
from rich.panel import Panel

# 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 read_note(
    query: str = typer.Argument(..., help="Note id, slug, or title"),
    workspace: Optional[str] = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Workspace name (default: search all workspaces)",
    ),
) -> None:
    """Read a note."""
    found = _find_in_all(query, workspace)
    if found is None:
        _log.warning("Note not found: %r", query)
        error(f"Note not found: {query!r}", "NOT_FOUND")
    ws, directory, path = found

    note = _load(path)
    _log.debug("Reading note %r (id=%s)", note.title, note.id)
    append_log(ws, "notes", "read", item_id=note.id, item_title=note.title)

    def human_output() -> None:  # pragma: no cover
        from rich.markdown import Markdown

        meta_line = "\n".join(
            [
                f"[dim]id:[/dim] {note.id[:8]}  "
                f"[dim]workspace:[/dim] {ws}  "
                f"[dim]tags:[/dim] {', '.join(note.tags) if note.tags else '—'}  "
                f"[dim]updated:[/dim] {note.updated_at[:10]}",
                f"[dim]path:[/dim] {path}",
            ]
        )
        console.print(
            Panel(
                meta_line,
                title=f"[bold]{note.title}[/bold]",
                box=box.ROUNDED,
                expand=False,
            )
        )
        if note.body:
            console.print(Markdown(note.body))

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