"""``albus viz`` — render a pathway as a Mermaid flowchart."""

from __future__ import annotations

from typing import Annotated

import typer

from albusos.cli import app
from albusos.cli._helpers import err, load_workspace_or_exit, out, run_async


@app.command("viz")
def viz_cmd(
    pathway_id: Annotated[str, typer.Argument(help="Pathway ID to visualize.")],
    root: Annotated[str, typer.Option("--root", "-r", help="Workspace root.")] = ".",
    trace_id: Annotated[
        str | None,
        typer.Option("--trace", "-t", help="Overlay an execution trace by ID."),
    ] = None,
    direction: Annotated[
        str, typer.Option("--direction", "-d", help="Graph direction: TD or LR.")
    ] = "TD",
    output: Annotated[
        str | None,
        typer.Option("--output", "-o", help="Write to file instead of stdout."),
    ] = None,
) -> None:
    """Render a pathway as a Mermaid flowchart (pipe to mmdc for SVG/PNG)."""
    load_workspace_or_exit(root)

    from core.workspace import get_workspace_pathway_registry

    registry = get_workspace_pathway_registry()
    pathway = registry.load(pathway_id) if registry else None
    if pathway is None:
        err.print(f"[red]Error:[/red] Pathway [bold]{pathway_id}[/bold] not found.")
        raise typer.Exit(1)

    if trace_id is not None:
        from core.observability.trace import ExecutionTrace
        from core.pathways.visualize import pathway_to_mermaid_with_trace
        from core.state import FileStateStore

        store = FileStateStore()
        trace = run_async(store.load_trace(trace_id))
        if trace is None or not isinstance(trace, ExecutionTrace):
            err.print(f"[red]Error:[/red] Trace [bold]{trace_id}[/bold] not found.")
            raise typer.Exit(1)
        mermaid = pathway_to_mermaid_with_trace(pathway, trace, direction=direction)
    else:
        from core.pathways.visualize import pathway_to_mermaid

        mermaid = pathway_to_mermaid(pathway, direction=direction)

    if output:
        from pathlib import Path

        Path(output).write_text(mermaid)
        err.print(f"Written to [bold]{output}[/bold]")
    else:
        out.print(mermaid)
