"""``albus validate`` — pre-run pathway validation."""

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


@app.command("validate")
def validate_cmd(
    pathway_id: Annotated[
        str | None,
        typer.Argument(help="Pathway ID to validate. Omit to validate all."),
    ] = None,
    root: Annotated[str, typer.Option("--root", "-r", help="Workspace root.")] = ".",
) -> None:
    """Validate pathways — check for cycles, missing tools, bad expressions."""
    ws = load_workspace_or_exit(root)

    from core.pathways.context import Context
    from core.pathways.validation import validate_pathway
    from core.tools import get_tool_registry
    from core.workspace import get_workspace_pathway_registry

    registry = get_workspace_pathway_registry()
    tool_handlers = get_tool_registry().as_handler_dict()
    ctx = Context(tools=tool_handlers)

    ids_to_check = [pathway_id] if pathway_id is not None else list(ws.pathways)

    if not ids_to_check:
        err.print("[yellow]No pathways found in workspace.[/yellow]")
        raise typer.Exit(0)

    total_errors = 0
    total_warnings = 0

    for pid in sorted(ids_to_check):
        pathway = registry.load(pid) if registry else None
        if pathway is None:
            err.print(f"[red]  MISSING[/red]  {pid}")
            total_errors += 1
            continue

        result = validate_pathway(pathway, ctx)

        if result.valid and not result.warnings:
            err.print(f"[green]  OK[/green]      {pid}")
        elif result.valid:
            err.print(f"[yellow]  WARN[/yellow]    {pid}")
        else:
            err.print(f"[red]  FAIL[/red]    {pid}")

        for issue in result.errors:
            node_ctx = f" (node: {issue.node_id})" if issue.node_id else ""
            err.print(f"           [red]error:[/red] {issue.message}{node_ctx}")
            total_errors += 1

        for issue in result.warnings:
            node_ctx = f" (node: {issue.node_id})" if issue.node_id else ""
            err.print(f"           [yellow]warn:[/yellow]  {issue.message}{node_ctx}")
            total_warnings += 1

    # Summary
    err.print()
    err.print(
        f"  {len(ids_to_check)} pathway(s) checked — "
        f"[red]{total_errors} error(s)[/red], "
        f"[yellow]{total_warnings} warning(s)[/yellow]"
    )

    if total_errors:
        raise typer.Exit(1)
