# standard
import json
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 sunwaee.modules.logs.model import LogEntry
from .list import _collect, _resolve_workspaces

_log = get_logger("modules.logs")


def _find_entry(
    id_prefix: str, workspaces: list[str]
) -> Optional[tuple[str, LogEntry]]:
    """Return the first log entry whose id starts with the given prefix."""
    for ws in workspaces:
        for entry in _collect([ws], date=None, month=None, all_time=True):
            if entry.id.startswith(id_prefix):
                return ws, entry
    return None


def read_log(
    id: str = typer.Argument(..., help="Full or partial log entry id"),
    workspace: Optional[str] = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Workspace name (default: search all workspaces)",
    ),
) -> None:
    """Read a single log entry in full detail."""
    workspaces = _resolve_workspaces(workspace)
    found = _find_entry(id, workspaces)

    if found is None:
        _log.warning("Log entry not found: %r", id)
        error(f"Log entry not found: {id!r}", "NOT_FOUND")

    ws, entry = found
    _log.debug("Reading log entry ts=%r ws=%r", entry.timestamp, ws)
    append_log(ws, "logs", "read", item_id=entry.id)

    def human_output() -> None:  # pragma: no cover
        ok_str = "[green]✓ ok[/green]" if entry.ok else "[red]✗ failed[/red]"
        item = entry.item_title or entry.item_id or "—"
        meta_line = "\n".join(
            [
                f"[dim]id:[/dim]        {entry.id}",
                f"[dim]timestamp:[/dim] {entry.timestamp}  "
                f"[dim]workspace:[/dim] {ws}  "
                f"[dim]status:[/dim] {ok_str}",
                f"[dim]caller:[/dim]    {entry.caller}  "
                f"[dim]module:[/dim] {entry.module}  "
                f"[dim]operation:[/dim] {entry.operation}",
                f"[dim]item:[/dim]      {item}",
            ]
        )
        if entry.item_id:
            meta_line += f"\n[dim]item_id:[/dim]   {entry.item_id}"
        if entry.args:
            meta_line += f"\n[dim]args:[/dim]      {json.dumps(entry.args, indent=2)}"

        title = f"[bold]{entry.module}[/bold] · {entry.operation}"
        console.print(
            Panel(
                meta_line,
                title=title,
                box=box.ROUNDED,
                expand=False,
            )
        )

    success(entry.to_dict(), human_fn=human_output)
