"""Integration tests for fleet module against live server.

Requires FLEET_INTEGRATION_TEST=1 environment variable.
Uses test token: brinkhaustools-test-token
"""

import os
import time

import pytest

pytestmark = pytest.mark.skipif(
    os.environ.get("FLEET_INTEGRATION_TEST") != "1",
    reason="Set FLEET_INTEGRATION_TEST=1 to run integration tests",
)

_BASE_URL = "https://fleet.brinkhaus-gmbh.de"
_TOKEN = "fmt_dHF4Y6zPweepFf_ws9FkbOU-gGsFtAG4b1qNmhXSNpc"
_CUSTOMER = "brinkhaus"
_MACHINE = "testMachine"
_SOFTWARE = "brinkhaustools-test"


def _make_client():
    from brinkhaustools.common.fleet.client import FleetMonitorClient

    client = FleetMonitorClient(
        base_url=_BASE_URL,
        customer=_CUSTOMER,
        machine=_MACHINE,
        software=_SOFTWARE,
        token=_TOKEN,
    )
    client._start_time = time.monotonic()
    return client


def test_heartbeat_roundtrip():
    client = _make_client()
    client.send_heartbeat()
    assert client.is_connected


def test_diagnostics_roundtrip():
    client = _make_client()
    client.send_diagnostics([(0, "All self tests passed", 0)])
    assert client.is_connected


def test_status_roundtrip():
    client = _make_client()
    client.send_status("running", "Integration test")
    assert client.is_connected


def test_invalid_token_rejected():
    from brinkhaustools.common.fleet.client import FleetMonitorClient

    client = FleetMonitorClient(
        base_url=_BASE_URL,
        customer=_CUSTOMER,
        machine=_MACHINE,
        software=_SOFTWARE,
        token="fmt_invalid_token_that_does_not_exist",
    )
    client.send_status("running", "Should fail")
    assert not client.is_connected
    assert "401" in client._last_connect_error
