from __future__ import annotations

import importlib.util
import json
import sys
from pathlib import Path
from types import ModuleType

import numpy as np
import pytest


def _worker_module() -> ModuleType:
    worker_root = Path(__file__).parents[1] / "experiments" / "perception" / "worker"
    path = worker_root / "run_e4_full_session_segmentation.py"
    spec = importlib.util.spec_from_file_location("e4_full_session_worker", path)
    assert spec is not None and spec.loader is not None
    sys.path.insert(0, str(worker_root))
    try:
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
    finally:
        sys.path.remove(str(worker_root))
    return module


def _profile() -> dict[str, object]:
    path = (
        Path(__file__).parents[1]
        / "experiments"
        / "perception"
        / "worker"
        / "e3_k1_camera1_profile.json"
    )
    value = json.loads(path.read_text(encoding="utf-8"))
    assert isinstance(value, dict)
    return value


def test_e4_accepts_the_sealed_camera1_valid_fov() -> None:
    worker = _worker_module()
    root = (
        Path(__file__).parents[1]
        / ".runtime"
        / "compute-experiments"
        / "e1"
        / "valid-fov"
        / "valid-fov-mask-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"
    )
    if not root.is_dir():
        pytest.skip("real sealed LAB E1 valid-FOV artifact is unavailable")

    mask, identity = worker._load_valid_fov(
        root,
        {"input": {"source_id": "sensor.camera.right"}},
        _profile(),
    )

    assert mask.shape == (600, 800)
    assert mask.dtype == np.bool_
    assert int(mask.sum()) == 270_606
    assert identity["valid_pixel_count"] == 270_606


def test_e4_rejects_valid_fov_from_another_camera() -> None:
    worker = _worker_module()
    root = (
        Path(__file__).parents[1]
        / ".runtime"
        / "compute-experiments"
        / "e1"
        / "valid-fov"
        / "valid-fov-mask-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"
    )
    if not root.is_dir():
        pytest.skip("real sealed LAB E1 valid-FOV artifact is unavailable")

    with pytest.raises(RuntimeError, match="valid-FOV binding"):
        worker._load_valid_fov(
            root,
            {"input": {"source_id": "sensor.camera.left"}},
            _profile(),
        )


def test_e4_overlay_preserves_pixels_outside_semantic_mask() -> None:
    worker = _worker_module()
    image = np.full((2, 3, 3), 100, dtype=np.uint8)
    semantic = np.asarray([[0, 4, 0], [7, 0, 1]], dtype=np.uint8)

    overlay = worker._overlay(image, semantic)

    assert np.array_equal(overlay[semantic == 0], image[semantic == 0])
    assert np.all(np.any(overlay[semantic > 0] != image[semantic > 0], axis=1))


def test_e4_class_fractions_use_only_valid_fov_pixels() -> None:
    worker = _worker_module()
    semantic = np.asarray([[0, 4, 4], [7, 0, 1]], dtype=np.uint8)
    valid = np.asarray([[False, True, True], [True, False, True]])
    names = {index: f"class-{index}" for index in range(16)}

    classes = worker._class_document(semantic, valid, names)

    assert {item["id"]: item["pixels"] for item in classes} == {1: 1, 4: 2, 7: 1}
    assert sum(float(item["fraction_of_valid_fov"]) for item in classes) == 1.0
