"""Show workflow command."""

from __future__ import annotations
from collections.abc import Mapping
from typing import Annotated, Any
import typer
from rich.markup import escape
from orcheo_sdk.cli.output import format_datetime, print_json, render_json, render_table
from orcheo_sdk.cli.utils import load_with_cache
from orcheo_sdk.cli.workflow.app import WorkflowIdArgument, _state, workflow_app
from orcheo_sdk.cli.workflow.inputs import _cache_notice
from orcheo_sdk.cli.workflow.mermaid import _mermaid_from_graph
from orcheo_sdk.cli.workflow.reminders import (
    attach_workflow_vault_reminder,
    describe_workflow_vault_reminder,
    fetch_workflow_vault_readiness,
)
from orcheo_sdk.services import show_workflow_data


def _print_workflow_vault_reminder(
    console: Any,
    readiness: dict[str, object] | None,
    *,
    leading_newline: bool = False,
) -> None:
    prefix = "\n" if leading_newline else ""
    reminder = describe_workflow_vault_reminder(readiness)
    if reminder is None:
        return
    console.print(f"{prefix}[dim]Vault reminder: {escape(reminder)}[/dim]")


@workflow_app.command("show")
def show_workflow(
    ctx: typer.Context,
    workflow_id: WorkflowIdArgument,
    version: Annotated[
        int | None,
        typer.Option("--version", "-v", help="Show a specific version number"),
    ] = None,
) -> None:
    """Display details about a workflow, including its latest version and runs."""
    state = _state(ctx)
    workflow, workflow_cached, workflow_stale = load_with_cache(
        state,
        f"workflow:{workflow_id}",
        lambda: state.client.get(f"/api/workflows/{workflow_id}"),
    )
    if workflow_cached:
        _cache_notice(state, f"workflow {workflow_id}", workflow_stale)

    # Only fetch versions list when no specific version is requested
    versions = None
    if version is None:
        versions, _, _ = load_with_cache(
            state,
            f"workflow:{workflow_id}:versions",
            lambda: state.client.get(f"/api/workflows/{workflow_id}/versions"),
        )

    runs, runs_cached, runs_stale = load_with_cache(
        state,
        f"workflow:{workflow_id}:runs",
        lambda: state.client.get(f"/api/workflows/{workflow_id}/runs"),
    )
    if runs_cached:
        _cache_notice(state, f"workflow {workflow_id} runs", runs_stale)

    data = show_workflow_data(
        state.client,
        workflow_id,
        workflow=workflow,
        versions=versions,
        runs=runs,
        target_version=version,
    )
    readiness = fetch_workflow_vault_readiness(state.client, workflow_id)

    if not state.human:
        print_json(attach_workflow_vault_reminder(data, readiness))
        return

    workflow_details = data["workflow"]
    selected_version = data.get("selected_version")
    recent_runs = data.get("recent_runs", [])

    state.console.print("[bold]Publish status[/bold]")
    state.console.print(
        f"Status: {'Public' if workflow_details.get('is_public') else 'Private'}"
    )
    state.console.print(
        f"Require login: {'Yes' if workflow_details.get('require_login') else 'No'}"
    )
    published_at = workflow_details.get("published_at")
    state.console.print(
        f"Published at: {format_datetime(published_at) if published_at else '-'}"
    )
    share_url = workflow_details.get("share_url")
    state.console.print(f"Share URL: {share_url or '-'}\n")

    render_json(state.console, workflow_details, title="Workflow")

    if selected_version:
        graph_raw = selected_version.get("graph", {})
        graph = graph_raw if isinstance(graph_raw, Mapping) else {}
        mermaid = _mermaid_from_graph(graph)
        version_num = selected_version.get("version")
        version_label = f"Version {version_num}" if version else "Latest version"
        state.console.print(f"\n[bold]{version_label}[/bold]")
        render_json(state.console, selected_version)
        state.console.print("\n[bold]Mermaid[/bold]")
        state.console.print(mermaid)

    if recent_runs:
        rows = [
            [
                item.get("id"),
                item.get("status"),
                item.get("triggered_by"),
                item.get("created_at"),
            ]
            for item in recent_runs
        ]
        render_table(
            state.console,
            title="Recent runs",
            columns=["ID", "Status", "Actor", "Created at"],
            rows=rows,
            column_overflow={"ID": "fold"},
        )

    _print_workflow_vault_reminder(
        state.console,
        readiness,
        leading_newline=True,
    )


__all__ = ["show_workflow"]
