import json
from pathlib import Path

import pytest

from m3m_twin.configuration import load_mission_parameters, load_study_configuration
from m3m_twin.mission import plan_virtual_mission
from m3m_twin.simulator import simulate_capture_qc


ROOT = Path(__file__).resolve().parents[1]


def test_repository_configuration_files_drive_default_parameters():
    field, parameters, paths = load_study_configuration(ROOT)
    assert field.field_id == "VIRTUAL-SX-12HA"
    assert field.area_m2 == 120_000
    assert parameters.altitude_agl_m == 60.0
    assert parameters.sun_altitude_deg == 42.0
    assert paths["mission"].name == "mission.example.json"
    assert paths["field"].name == "virtual-field.json"


def test_custom_mission_configuration_propagates_sun_altitude(tmp_path):
    value = json.loads((ROOT / "config" / "mission.example.json").read_text(encoding="utf-8"))
    value["sunAltitudeDeg"] = 51.5
    target = tmp_path / "mission.json"
    target.write_text(json.dumps(value), encoding="utf-8")
    parameters = load_mission_parameters(target)
    mission = plan_virtual_mission(parameters=parameters)
    records, _ = simulate_capture_qc(
        mission["captureEvents"],
        sun_altitude_deg=parameters.sun_altitude_deg,
    )
    assert all(row["sunAltitudeDeg"] == 51.5 for row in records)


def test_operational_mission_configuration_is_rejected(tmp_path):
    value = json.loads((ROOT / "config" / "mission.example.json").read_text(encoding="utf-8"))
    value["flightExecutionAuthorized"] = True
    target = tmp_path / "unsafe-mission.json"
    target.write_text(json.dumps(value), encoding="utf-8")
    with pytest.raises(ValueError, match="non-operational"):
        load_mission_parameters(target)
