"""UUT (Unit Under Test) CLI commands."""

from __future__ import annotations

from datetime import datetime
from pathlib import Path

import typer

from .client import QrmClient, QrmClientError
from .commands_shared import (
    CLI_DATE_FORMATS,
    OutputFormat,
    console,
    emit,
    format_api_datetime,
    load_state_or_exit,
    render_uut_status,
    resolve_uut_window,
)

uut_app = typer.Typer(help="Inspect Units Under Test (UUTs).")


@uut_app.command("status")
def uut_status(
    serial_number: str = typer.Argument(..., help="Serial number to query."),
    start: datetime | None = typer.Option(
        None,
        "--start",
        formats=CLI_DATE_FORMATS,
        help=(
            "Filter from this timestamp (UTC). Accepts ISO-8601 (e.g. 2020-01-01T00:00:00Z) "
            "or YYYY-MM-DD HH:MM:SS. Default: 1970-01-01T00:00:00Z."
        ),
    ),
    stop: datetime | None = typer.Option(
        None,
        "--stop",
        formats=CLI_DATE_FORMATS,
        help=(
            "Filter until this timestamp (UTC). Accepts ISO-8601 (e.g. 2026-02-06T23:59:00Z) "
            "or YYYY-MM-DD HH:MM:SS. Default: QRM current time."
        ),
    ),
    max_results: int = typer.Option(
        1000,
        "--max-results",
        "-m",
        min=1,
        max=5000,
        help="Maximum number of rows to return (default 1000).",
    ),
    config_path: Path = typer.Option(
        None,
        "--config-path",
        help="Override the location of the login.json file.",
    ),
    base_url: str = typer.Option(
        None,
        "--base-url",
        help="Override the base URL stored in the config (useful for testing).",
    ),
    insecure: bool = typer.Option(
        False,
        "--insecure",
        help="Disable TLS verification when contacting QRM.",
    ),
    output: OutputFormat = typer.Option(
        OutputFormat.rich,
        "--output",
        "-o",
        case_sensitive=False,
        help="Choose output format: rich (default) or json.",
    ),
) -> None:
    """Fetch UUT execution history using the `/Uut/Status` endpoint."""

    state = load_state_or_exit(config_path)
    resolved_start, resolved_stop = resolve_uut_window(start, stop)

    client = QrmClient(
        base_url=base_url or str(state.base_url),
        verify_tls=not insecure and state.verify_tls,
    )

    try:
        payload = client.uut_status(
            token=state.token,
            serial_number=serial_number,
            start_datetime=format_api_datetime(resolved_start),
            stop_datetime=(
                format_api_datetime(resolved_stop) if resolved_stop is not None else None
            ),
            max_results=max_results,
        )
    except QrmClientError as exc:
        typer.secho(f"UUT status check failed: {exc}", fg=typer.colors.RED)
        raise typer.Exit(code=1) from exc

    if output is OutputFormat.json:
        emit(payload, output)
        return

    console.print(render_uut_status(payload))


__all__ = ["uut_app"]
