"""EuRoCAdapter unit tests — uses a minimal fabricated MH_01-style directory."""

from pathlib import Path

import pytest

from gps_denied.testing.datasets.base import (
    DatasetNotAvailableError,
    PlatformClass,
)
from gps_denied.testing.datasets.euroc import EuRoCAdapter


@pytest.fixture
def fake_euroc_root(tmp_path: Path) -> Path:
    mav0 = tmp_path / "mav0"
    (mav0 / "cam0" / "data").mkdir(parents=True)
    (mav0 / "imu0").mkdir(parents=True)
    (mav0 / "state_groundtruth_estimate0").mkdir(parents=True)

    # Two frames
    for ts in (1403636579763555584, 1403636579813555456):
        img = mav0 / "cam0" / "data" / f"{ts}.png"
        img.write_bytes(b"\x89PNG\r\n\x1a\n")  # stub header
    (mav0 / "cam0" / "data.csv").write_text(
        "#timestamp [ns],filename\n"
        "1403636579763555584,1403636579763555584.png\n"
        "1403636579813555456,1403636579813555456.png\n"
    )

    # IMU: two samples
    (mav0 / "imu0" / "data.csv").write_text(
        "#timestamp [ns],w_RS_S_x [rad s^-1],w_RS_S_y,w_RS_S_z,"
        "a_RS_S_x [m s^-2],a_RS_S_y,a_RS_S_z\n"
        "1403636579763555584,0.01,0.02,0.03,0.1,0.2,-9.7\n"
        "1403636579813555456,0.01,0.02,0.03,0.1,0.2,-9.7\n"
    )

    # GT: two poses
    (mav0 / "state_groundtruth_estimate0" / "data.csv").write_text(
        "#timestamp [ns],p_RS_R_x [m],p_RS_R_y,p_RS_R_z,"
        "q_RS_w [],q_RS_x,q_RS_y,q_RS_z,"
        "v_RS_R_x,v_RS_R_y,v_RS_R_z,b_w_x,b_w_y,b_w_z,b_a_x,b_a_y,b_a_z\n"
        "1403636579763555584,0.0,0.0,0.0,1.0,0.0,0.0,0.0,"
        "0,0,0,0,0,0,0,0,0\n"
        "1403636579813555456,0.05,0.0,0.0,1.0,0.0,0.0,0.0,"
        "0,0,0,0,0,0,0,0,0\n"
    )
    return tmp_path


def test_adapter_raises_when_missing(tmp_path: Path):
    with pytest.raises(DatasetNotAvailableError):
        EuRoCAdapter(tmp_path / "nope")


def test_adapter_capabilities(fake_euroc_root: Path):
    adapter = EuRoCAdapter(fake_euroc_root)
    cap = adapter.capabilities
    assert cap.has_raw_imu is True
    assert cap.has_rtk_gt is False  # EuRoC uses Vicon, not RTK
    assert cap.platform_class == PlatformClass.INDOOR


def test_adapter_iter_frames(fake_euroc_root: Path):
    adapter = EuRoCAdapter(fake_euroc_root)
    frames = list(adapter.iter_frames())
    assert len(frames) == 2
    assert frames[0].timestamp_ns == 1403636579763555584
    assert frames[0].image_path.endswith("1403636579763555584.png")


def test_adapter_iter_imu(fake_euroc_root: Path):
    adapter = EuRoCAdapter(fake_euroc_root)
    imu = list(adapter.iter_imu())
    assert len(imu) == 2
    assert imu[0].gyro == (0.01, 0.02, 0.03)
    assert imu[0].accel == (0.1, 0.2, -9.7)


def test_adapter_iter_ground_truth(fake_euroc_root: Path):
    adapter = EuRoCAdapter(fake_euroc_root)
    gt = list(adapter.iter_ground_truth())
    assert len(gt) == 2
    assert gt[0].qw == 1.0
    # First pose is the fictitious origin
    assert gt[0].lat == pytest.approx(49.0)
    assert gt[0].lon == pytest.approx(32.0)
