from pathlib import Path
import sys


PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from runtime_env import apply_config_env_overrides, apply_intercept_env_overrides


def test_apply_config_env_overrides_parses_source_device_and_flags(monkeypatch):
    namespace = {
        "SOURCE": "video.mp4",
        "MODEL_PATH": "best.pt",
        "SHOW_OUTPUT": True,
        "SAVE_INFER_VIDEO": True,
        "OUT_VIDEO_PATH": "out.mp4",
    }

    monkeypatch.setenv("FPV_SOURCE", "0")
    monkeypatch.setenv("FPV_MODEL_PATH", "/models/best.pt")
    monkeypatch.setenv("FPV_SHOW_OUTPUT", "false")
    monkeypatch.setenv("FPV_SAVE_INFER_VIDEO", "0")
    monkeypatch.setenv("FPV_OUT_VIDEO_PATH", "/outputs/run.mp4")

    apply_config_env_overrides(namespace)

    assert namespace["SOURCE"] == 0
    assert namespace["MODEL_PATH"] == "/models/best.pt"
    assert namespace["SHOW_OUTPUT"] is False
    assert namespace["SAVE_INFER_VIDEO"] is False
    assert namespace["OUT_VIDEO_PATH"] == "/outputs/run.mp4"


def test_apply_intercept_env_overrides_switches_to_proto_udp(monkeypatch):
    namespace = {
        "AUTOPILOT_ENABLE": True,
        "AUTOPILOT_BACKEND": "json",
        "PROTO_UDP_ENABLE": False,
        "PROTO_UDP_HOST": "127.0.0.1",
        "PROTO_UDP_PORT": 5005,
    }

    monkeypatch.setenv("FPV_AUTOPILOT_ENABLE", "true")
    monkeypatch.setenv("FPV_AUTOPILOT_BACKEND", "proto_udp")
    monkeypatch.setenv("FPV_PROTO_UDP_ENABLE", "1")
    monkeypatch.setenv("FPV_PROTO_UDP_HOST", "192.168.0.55")
    monkeypatch.setenv("FPV_PROTO_UDP_PORT", "6001")

    apply_intercept_env_overrides(namespace)

    assert namespace["AUTOPILOT_ENABLE"] is True
    assert namespace["AUTOPILOT_BACKEND"] == "proto_udp"
    assert namespace["PROTO_UDP_ENABLE"] is True
    assert namespace["PROTO_UDP_HOST"] == "192.168.0.55"
    assert namespace["PROTO_UDP_PORT"] == 6001
