"""Tests for the 'uut status' command."""

from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path

from typer.testing import CliRunner

from qrm import cli
from qrm import uut_commands
from qrm.client import LoginState
from qrm.commands_shared import resolve_uut_window

runner = CliRunner()


def test_uut_status_command_calls_client(monkeypatch, tmp_path: Path) -> None:
    """The uut status subcommand should call the API and render a table."""

    state = LoginState(  # type: ignore[call-arg]
        token="TOKEN123",
        username="alice",
        base_url="https://qrm.local/api",
        verify_tls=True,
    )
    config_path = tmp_path / "login.json"
    config_path.write_text(state.model_dump_json())

    captured = {}

    class FakeClient:
        def __init__(self, base_url: str, verify_tls: bool) -> None:  # noqa: D401
            captured["base_url"] = base_url
            captured["verify_tls"] = verify_tls

        def uut_status(
            self,
            *,
            token: str,
            serial_number: str,
            start_datetime: str | None,
            stop_datetime: str | None,
            max_results: int | None,
        ):
            captured["token"] = token
            captured["serial_number"] = serial_number
            captured["start"] = start_datetime
            captured["stop"] = stop_datetime
            captured["max_results"] = max_results
            return [
                {
                    "ResultSetName": "Run #1",
                    "Outcome": "Passed",
                    "StartDateTime": "2026-02-06T07:08:59.863Z",
                    "StopDateTime": "2026-02-06T07:10:57.220Z",
                    "Info": {
                        "UutSerialNumber": "326115020010F2F1",
                        "StationName": "RYW1104",
                        "Operator": "Operator",
                    },
                }
            ]

    monkeypatch.setattr(uut_commands, "QrmClient", FakeClient)

    result = runner.invoke(
        cli.app,
        [
            "uut",
            "status",
            "326115020010F2F1",
            "--start",
            "2026-02-01 00:00:00",
            "--stop",
            "2026-02-06 23:59:00",
            "--max-results",
            "50",
            "--config-path",
            str(config_path),
        ],
    )

    assert result.exit_code == 0
    assert "Run #1" in result.stdout
    assert "RYW1104" in result.stdout
    assert captured == {
        "base_url": "https://qrm.local/api",
        "verify_tls": True,
        "token": "TOKEN123",
        "serial_number": "326115020010F2F1",
        "start": "2026-02-01 00:00:00",
        "stop": "2026-02-06 23:59:00",
        "max_results": 50,
    }


def test_uut_status_command_supports_json_output(monkeypatch, tmp_path: Path) -> None:
    """JSON output should bypass table rendering."""

    state = LoginState(  # type: ignore[call-arg]
        token="TOKEN123",
        username="alice",
        base_url="https://qrm.local/api",
        verify_tls=True,
    )
    config_path = tmp_path / "login.json"
    config_path.write_text(state.model_dump_json())

    class FakeClient:
        def __init__(self, *_: str, **__: str) -> None:  # noqa: D401, ANN001, ANN002, ANN003
            pass

        def uut_status(self, **kwargs):  # noqa: ANN003
            return [{"serialNumber": kwargs["serial_number"], "Outcome": "Passed"}]

    monkeypatch.setattr(uut_commands, "QrmClient", FakeClient)

    result = runner.invoke(
        cli.app,
        [
            "uut",
            "status",
            "326115020010F2F1",
            "--config-path",
            str(config_path),
            "--output",
            "json",
        ],
    )

    assert result.exit_code == 0
    assert json.loads(result.stdout) == [{"serialNumber": "326115020010F2F1", "Outcome": "Passed"}]


def test_uut_status_defaults_time_window(monkeypatch, tmp_path: Path) -> None:
    """Start defaults to epoch; stop defaults to current time when not provided."""

    state = LoginState(  # type: ignore[call-arg]
        token="TOKEN123",
        username="alice",
        base_url="https://qrm.local/api",
        verify_tls=True,
    )
    config_path = tmp_path / "login.json"
    config_path.write_text(state.model_dump_json())

    captured = {}

    class FakeClient:
        def __init__(self, *_: str, **__: str) -> None:  # noqa: D401, ANN001, ANN002, ANN003
            pass

        def uut_status(self, **kwargs):  # noqa: ANN003
            captured["start"] = kwargs["start_datetime"]
            captured["stop"] = kwargs["stop_datetime"]
            return []

    monkeypatch.setattr(uut_commands, "QrmClient", FakeClient)

    result = runner.invoke(
        cli.app,
        [
            "uut",
            "status",
            "ABC123",
            "--config-path",
            str(config_path),
        ],
    )

    assert result.exit_code == 0
    assert captured["start"] == "1970-01-01 00:00:00"
    assert captured["stop"] is not None and captured["stop"] > "2020-01-01 00:00:00"


def test_resolve_uut_window_defaults_epoch() -> None:
    """When only stop is provided, start should fall back to the epoch."""

    stop = datetime(2026, 2, 6, 0, 0, tzinfo=timezone.utc)

    start, resolved_stop = resolve_uut_window(None, stop)

    assert start == datetime(1970, 1, 1, 0, 0, tzinfo=timezone.utc)
    assert resolved_stop == stop


def test_uut_status_handles_empty_payload(monkeypatch, tmp_path: Path) -> None:
    """An empty list should render the placeholder row."""

    state = LoginState(  # type: ignore[call-arg]
        token="TOKEN123",
        username="alice",
        base_url="https://qrm.local/api",
        verify_tls=True,
    )
    config_path = tmp_path / "login.json"
    config_path.write_text(state.model_dump_json())

    class FakeClient:
        def __init__(self, *_: str, **__: str) -> None:  # noqa: D401, ANN001, ANN002, ANN003
            pass

        def uut_status(self, **__: str):  # noqa: ANN003
            return []

    monkeypatch.setattr(uut_commands, "QrmClient", FakeClient)

    result = runner.invoke(
        cli.app,
        [
            "uut",
            "status",
            "326115020010F2F1",
            "--config-path",
            str(config_path),
        ],
    )

    assert result.exit_code == 0
    assert "No results" in result.stdout


def test_uut_status_handles_irregular_rows(monkeypatch, tmp_path: Path) -> None:
    """Mixed payload elements should still render without crashing."""

    state = LoginState(  # type: ignore[call-arg]
        token="TOKEN123",
        username="alice",
        base_url="https://qrm.local/api",
        verify_tls=True,
    )
    config_path = tmp_path / "login.json"
    config_path.write_text(state.model_dump_json())

    class FakeClient:
        def __init__(self, *_: str, **__: str) -> None:  # noqa: D401, ANN001, ANN002, ANN003
            pass

        def uut_status(self, **__: str):  # noqa: ANN003
            return [
                {
                    "Id": 99,
                    "serialNumber": "ABC123",
                    "Outcome": "Failed",
                    "StartDateTime": datetime(2026, 2, 1, 12, 0, 0, tzinfo=timezone.utc),
                    "StopDateTime": 12345,
                    "Info": "oops",
                },
                "raw-string",
            ]

    monkeypatch.setattr(uut_commands, "QrmClient", FakeClient)

    result = runner.invoke(
        cli.app,
        [
            "uut",
            "status",
            "ABC123",
            "--config-path",
            str(config_path),
        ],
    )

    assert result.exit_code == 0
    assert "Failed" in result.stdout
    assert "raw-string" in result.stdout
    assert "12345" in result.stdout
