"""
Grundlegende Unit- und Fehler-Tests für scripts.

End-to-end-Tests gegen echte Bilder sind in tests/test_e2e.py
(erfordert fixtures/Scene*-Ordner, nicht im Repo).
"""
import os
from pathlib import Path

import pytest

from scripts import PipelineResult, __version__, estimate_from_dir

FIXTURES = Path(__file__).parent / "fixtures"


def test_version_format():
    parts = __version__.split(".")
    assert len(parts) == 3
    assert all(p.isdigit() for p in parts)


def test_pipeline_result_dataclass():
    r = PipelineResult(
        joints={"x": 50.0, "y": -2.0, "z": 94.0, "a": 20.0, "b": 59.0, "c": 9.0, "e": 3.0},
        confidence={"x": "high", "y": "high", "z": "high", "a": "high", "b": "low", "c": "low", "e": "low"},
        n_markers=42,
        residual_rms=1.45,
        processing_ms=1200.0,
    )
    assert r.joints["x"] == 50.0
    assert r.confidence["b"] == "low"
    assert r.n_markers == 42
    assert r.errors == []


def test_estimate_raises_on_empty_dir(tmp_path):
    with pytest.raises(FileNotFoundError, match="render_"):
        estimate_from_dir(tmp_path, robot_json=FIXTURES / "robot_minimal.json")


def test_estimate_raises_without_robot_json(tmp_path):
    env_backup = os.environ.pop("ROBOT_JSON", None)
    try:
        with pytest.raises(ValueError, match="robot_json"):
            estimate_from_dir(tmp_path, robot_json=None)
    finally:
        if env_backup is not None:
            os.environ["ROBOT_JSON"] = env_backup


def test_robot_minimal_json_is_valid():
    import json
    data = json.loads((FIXTURES / "robot_minimal.json").read_text())
    assert "pose_estimation" in data
    assert "links" in data
    assert data["pose_estimation"]["method"] == "hybrid"
