import pytest
from qrm.commands_shared import (
    resolve_config_path,
    emit,
    OutputFormat,
    resolve_uut_window,
    resolve_box_window,
    resolve_window,
    format_api_datetime,
    render_uut_status,
    render_box_list,
    render_box_detail,
    render_uut_table,
    render_results_status,
    render_serial_status,
    resolve_serial,
    format_timestamp,
)
from pathlib import Path
from datetime import datetime, timezone


def test_resolve_config_path_default():
    assert resolve_config_path(None).name == "login.json"


def test_format_api_datetime():
    dt = datetime(2024, 3, 26, 12, 0, 0, tzinfo=timezone.utc)
    assert format_api_datetime(dt) == "2024-03-26 12:00:00"
    assert format_api_datetime(None) is None


def test_emit_json(capsys):
    emit({"foo": "bar"}, OutputFormat.json)
    out = capsys.readouterr().out
    assert '"foo": "bar"' in out


def test_emit_rich_table(monkeypatch):
    called = {}

    def fake_print(obj):
        called["printed"] = True

    monkeypatch.setattr("qrm.commands_shared.console.print", fake_print)
    emit({"foo": "bar"}, OutputFormat.rich)
    assert called["printed"]


def test_resolve_uut_window():
    start, stop = resolve_uut_window(None, None)
    assert isinstance(start, datetime) and isinstance(stop, datetime)


def test_resolve_box_window():
    start, stop = resolve_box_window(None, None)
    assert isinstance(start, datetime) and (stop is None or isinstance(stop, datetime))


def test_resolve_window():
    now = datetime.now(timezone.utc)
    start, stop = resolve_window(None, now, default_start=now)
    assert stop == now
    with pytest.raises(Exception):
        resolve_window(now, now.replace(year=now.year - 1), default_start=now)


def test_render_uut_status():
    table = render_uut_status([])
    assert hasattr(table, "add_row")
    table = render_uut_status(
        {
            "ResultSetName": "foo",
            "SerialNumber": "bar",
            "Outcome": "Passed",
            "StartDateTime": "2024-01-01T00:00:00",
            "StopDateTime": "2024-01-01T01:00:00",
            "StationName": "A",
            "OperatorName": "B",
        }
    )
    assert hasattr(table, "add_row")


def test_render_box_list():
    table = render_box_list([])
    assert hasattr(table, "add_row")
    table = render_box_list(
        {
            "BoxIdentifier": "box1",
            "Shipped": True,
            "NumberOfUnits": 5,
            "StartedDateTime": "2024-01-01T00:00:00",
            "FinishedDateTime": "2024-01-01T01:00:00",
            "Location": "loc",
        }
    )
    assert hasattr(table, "add_row")


def test_render_box_detail():
    table = render_box_detail(
        {
            "boxIdentifier": "box1",
            "shipped": True,
            "numberOfUnits": 5,
            "startedDateTime": "2024-01-01T00:00:00",
            "finishedDateTime": "2024-01-01T01:00:00",
        }
    )
    assert hasattr(table, "add_row")


def test_render_uut_table():
    table = render_uut_table(
        [{"serialNumber": "sn", "uutTypeName": "type", "identifierTag": "tag"}]
    )
    assert hasattr(table, "add_row")


def test_render_results_status():
    table = render_results_status(
        [
            {
                "ResultSetName": "foo",
                "SerialNumber": "bar",
                "Outcome": "Passed",
                "StartDateTime": "2024-01-01T00:00:00",
                "StopDateTime": "2024-01-01T01:00:00",
                "StationName": "A",
                "OperatorName": "B",
                "TestProgramName": "prog",
                "TestTypeName": "type",
                "SequenceName": "seq",
                "TestSocketIndex": 1,
                "LogFileURL": "url",
                "InsertDateTime": "2024-01-01T02:00:00",
                "Yield": 1,
                "UUTTypeName": "uut",
            }
        ]
    )
    assert hasattr(table, "add_row")


def test_render_serial_status():
    table = render_serial_status(
        [
            {
                "ResultSetName": "foo",
                "SerialNumber": "bar",
                "Outcome": "Passed",
                "StartDateTime": "2024-01-01T00:00:00",
                "StopDateTime": "2024-01-01T01:00:00",
                "StationName": "A",
                "OperatorName": "B",
                "TestProgramName": "prog",
                "TestTypeName": "type",
                "SequenceName": "seq",
                "TestSocketIndex": 1,
                "LogFileURL": "url",
                "InsertDateTime": "2024-01-01T02:00:00",
                "Yield": 1,
                "UUTTypeName": "uut",
            }
        ]
    )
    assert hasattr(table, "add_row")


def test_resolve_serial():
    assert resolve_serial({"serialNumber": "sn"}) == "sn"
    assert resolve_serial({}) == "-"


def test_format_timestamp():
    assert format_timestamp("2024-01-01T00:00:00") == "2024-01-01 00:00:00"
    assert format_timestamp(datetime(2024, 1, 1, 0, 0, 0)) == "2024-01-01 00:00:00"
    assert format_timestamp(None) == "-"
