"""Typer CLI entrypoint."""

from __future__ import annotations

import typer
from rich.console import Console
from rich.table import Table

from dpe.adapters.registry import build_adapters, run_adapter_healthchecks
from dpe.engine.config_loader import load_config
from dpe.engine.logging_config import setup_logging
from dpe.engine.orchestrator import Orchestrator

app = typer.Typer(
    name="dialectic",
    help="Dialectical PRD Engine — deterministic, budget-aware PRD generation.",
    no_args_is_help=True,
)
console = Console()


def _setup_logging(verbose: bool, structured: bool = False) -> None:
    setup_logging(verbose=verbose, structured=structured)


@app.command()
def run(
    idea: str = typer.Option(..., "--idea", "-i", help="Base idea to generate a PRD from."),
    config: str | None = typer.Option(None, "--config", "-c", help="Path to config JSON."),
    simulation: bool = typer.Option(False, "--simulation", "-s", help="Run in simulation mode."),
    smoke: bool = typer.Option(
        False, "--smoke", help="Deterministic smoke test — simulation with fixed run_id/timestamps."
    ),
    output_dir: str = typer.Option("runs", "--output-dir", "-o", help="Output directory."),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging."),
    skip_healthcheck: bool = typer.Option(
        False, "--skip-healthcheck", help="Skip adapter healthchecks (CI/simulation)."
    ),
) -> None:
    """Run the dialectical PRD generation workflow."""
    _setup_logging(verbose)

    overrides: dict[str, object] = {"output_dir": output_dir}
    if simulation:
        overrides["simulation_mode"] = True
    if smoke:
        overrides["smoke_mode"] = True

    try:
        cfg = load_config(config, **overrides)
    except (FileNotFoundError, ValueError) as e:
        console.print(f"[red]Config error:[/red] {e}")
        raise typer.Exit(code=1) from e

    # Adapter healthcheck (T-0101): verify adapters are available before running
    adapters = build_adapters(cfg)
    if not skip_healthcheck and not cfg.simulation_mode:
        failures = run_adapter_healthchecks(adapters)
        if failures:
            console.print("[red]Adapter healthcheck failed:[/red]")
            for f in failures:
                console.print(f"  [red]•[/red] {f}")
            console.print(
                "\n[dim]Use --skip-healthcheck to bypass, "
                "or --simulation for CI/offline mode.[/dim]"
            )
            raise typer.Exit(code=1)

    orchestrator = Orchestrator(config=cfg, adapters=adapters)
    manifest = orchestrator.run(idea)

    # Summary table
    table = Table(title=f"Run {manifest.run_id}")
    table.add_column("Field", style="bold")
    table.add_column("Value")
    table.add_row("Stop Reason", manifest.stop_reason)
    table.add_row("Total Calls", str(manifest.budget_actuals.total_calls_used))
    table.add_row("Premium Calls", str(manifest.budget_actuals.premium_calls_used))
    table.add_row("Critique Rounds", str(manifest.budget_actuals.critique_rounds_used))
    table.add_row("Wall Time", f"{manifest.budget_actuals.wall_time_seconds:.1f}s")
    table.add_row("Artifacts", str(len(manifest.artifacts)))
    table.add_row("Output", str(orchestrator._registry.run_dir))

    if manifest.warnings:
        table.add_row("Warnings", "\n".join(manifest.warnings))

    console.print(table)

    if manifest.stop_reason != "completed":
        raise typer.Exit(code=2)


@app.command()
def validate_config(
    config: str = typer.Option(..., "--config", "-c", help="Path to config file to validate."),
) -> None:
    """Validate a DPE configuration file."""
    try:
        cfg = load_config(config)
        console.print(f"[green]Valid.[/green] Hash: {cfg.config_hash()[:16]}")
    except Exception as e:
        console.print(f"[red]Invalid:[/red] {e}")
        raise typer.Exit(code=1) from e


if __name__ == "__main__":
    app()
