import json
import subprocess
import sys
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
TOOL = ROOT / "tools" / "patch_traffic_lanes.py"


def run_patch_sample(tmp_path):
    output = tmp_path / "patched.json"

    result = subprocess.run(
        [
            sys.executable,
            str(TOOL),
            str(ROOT / "samples" / "traffic_resource.json"),
            str(output),
        ],
        check=True,
        text=True,
        capture_output=True,
    )

    assert "lanes changed: 2" in result.stdout

    patched = json.loads(output.read_text(encoding="utf-8"))
    lanes = patched["Data"]["RootChunk"]["data"]["lanes"]

    assert lanes[0]["maxSpeed"] == 25
    assert lanes[1]["maxSpeed"] == 15
    assert lanes[2]["maxSpeed"] == 10


def test_patch_sample(tmp_path):
    run_patch_sample(tmp_path)


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as tmp:
        run_patch_sample(Path(tmp))
