import pytest
from typer.testing import CliRunner
from qrm.query_commands import query_app
from qrm.client import QrmClientError, LoginState
from qrm.commands_shared import OutputFormat

runner = CliRunner()

_FAKE_STATE = LoginState(
    token="TOKEN123",
    username="alice",
    base_url="https://qrm.local/api",
    verify_tls=True,
)


def test_results_rich(monkeypatch):
    class DummyClient:
        def __init__(self, *a, **k):
            pass

        def export_sql(self, **kwargs):
            return [
                {
                    "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",
                }
            ]

    monkeypatch.setattr("qrm.query_commands.QrmClient", DummyClient)
    monkeypatch.setattr("qrm.query_commands.load_state_or_exit", lambda *a, **k: _FAKE_STATE)
    result = runner.invoke(query_app, ["results", "--output", "rich"])
    assert result.exit_code == 0
    # Check for table grid and data, not full header string
    assert "┏" in result.output or "━" in result.output  # Table border
    assert "foo" in result.output or "━" in result.output  # Data value


def test_serial_rich(monkeypatch):
    class DummyClient:
        def __init__(self, *a, **k):
            pass

        def export_sql(self, **kwargs):
            return [
                {
                    "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",
                }
            ]

    monkeypatch.setattr("qrm.query_commands.QrmClient", DummyClient)
    monkeypatch.setattr("qrm.query_commands.load_state_or_exit", lambda *a, **k: _FAKE_STATE)
    result = runner.invoke(query_app, ["serial", "sn", "--output", "rich"])
    assert result.exit_code == 0
    # Check for table grid and data, not full header string
    assert "┏" in result.output or "━" in result.output  # Table border
    assert "foo" in result.output or "━" in result.output or "bar" in result.output  # Data value


def test_serial_qrmclienterror(monkeypatch):
    class DummyClient:
        def __init__(self, *a, **k):
            pass

        def export_sql(self, **kwargs):
            raise QrmClientError("fail")

    monkeypatch.setattr("qrm.query_commands.QrmClient", DummyClient)
    monkeypatch.setattr("qrm.query_commands.load_state_or_exit", lambda *a, **k: _FAKE_STATE)
    result = runner.invoke(query_app, ["serial", "sn"])
    assert result.exit_code != 0
    assert "query failed" in result.output
