"""OBS source migration must remove every direct raw-producer URL without touching other origins."""
from __future__ import annotations

import sys
from pathlib import Path
from urllib.parse import parse_qsl, urlsplit

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "live"))
from secure_obs_sources import migrate_scene_document, private_obs_url  # noqa: E402


def test_programme_and_panel_move_to_localhost_without_url_tokens():
    got = private_obs_url(
        "https://broadcast.viewregatta.com/core/web/index.html?feed=live&token=secret&lang=en"
    )
    parsed = urlsplit(got)
    assert parsed.scheme == "http" and parsed.netloc == "localhost:8766"
    assert parse_qsl(parsed.query) == [("feed", "live"), ("lang", "en")]


def test_single_camera_uses_the_second_loopback_origin_and_preserves_duplicate_options():
    got = private_obs_url(
        "https://trap-v3-producer-abc-lz.a.run.app/core/web/boatcam.html?"
        "slot=A&cameraRotation=boat%3D0&cameraRotation=buoy%3D90"
    )
    parsed = urlsplit(got)
    assert parsed.netloc == "127.0.0.1:8766"
    assert parse_qsl(parsed.query) == [
        ("slot", "A"), ("cameraRotation", "boat=0"), ("cameraRotation", "buoy=90")
    ]


def test_unrelated_origins_and_existing_loopback_sources_are_unchanged():
    for url in (
        "https://apps.viewregatta.com/v3/view/race/course",
        "https://other-service-abc.run.app/page",
        "http://127.0.0.1:8766/core/web/boatcam.html?slot=A",
    ):
        assert private_obs_url(url) == url


def test_standings_stays_local_but_uses_its_data_only_service():
    assert private_obs_url("http://localhost:8766/core/web/standings.html") == (
        "http://127.0.0.1:8767/core/web/standings.html"
    )


def test_offline_obs_collection_migration_changes_only_browser_urls():
    document = {
        "sources": [
            {"name": "programme", "settings": {
                "url": "https://broadcast.viewregatta.com/core/web/index.html?feed=live"
            }},
            {"name": "standings", "settings": {
                "url": "http://localhost:8766/core/web/standings.html"
            }},
            {"name": "camera", "settings": {"url": "https://media.example/video.m3u8"}},
        ]
    }
    assert [name for name, _url in migrate_scene_document(document)] == ["programme", "standings"]
    assert document["sources"][0]["settings"]["url"].startswith("http://localhost:8766/")
    assert document["sources"][1]["settings"]["url"].startswith("http://127.0.0.1:8767/")
    assert document["sources"][2]["settings"]["url"] == "https://media.example/video.m3u8"
