"""Deployment invariants for the stateful live broadcast producer."""

import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[4]


def test_deploy_all_restates_the_service_singleton_without_pinning_revisions():
    script = (ROOT / "deploy-all.ps1").read_text(encoding="utf-8")

    producer_guard = script[script.index("if ($s.name -eq 'trap-v3-producer') {") :]
    assert "'--min', '1', '--max', '1'" in producer_guard
    assert "'--min-instances', 'default'" in producer_guard
    assert "'--max-instances', 'default'" in producer_guard
    assert "'--scaling', 'auto'" in producer_guard


def test_deploy_all_keeps_the_raw_producer_private_and_checks_clients_with_iam():
    script = (ROOT / "deploy-all.ps1").read_text(encoding="utf-8")

    producer_deploy = script[script.index("if ($s.name -eq 'trap-v3-producer') {") :]
    assert "'--no-allow-unauthenticated'" in producer_deploy
    assert "'--invoker-iam-check'" in producer_deploy
    assert "gcloud auth print-identity-token" in script
    assert 'Authorization = "Bearer $($identityToken.Trim())"' in script
    assert "private client state could not be verified" in script
    assert "producer service could not be described" in script
    assert "catch {\n      Write-Host \"  trap-v3-producer SKIPPED" in script


def test_operator_runbook_never_reopens_or_bypasses_the_private_producer():
    runbook = (ROOT / "v3/broadcast/deploy/PRODUCER_CLOUDRUN.md").read_text(encoding="utf-8")

    assert not re.search(r"(?<!no-)--allow-unauthenticated", runbook)
    assert "--no-allow-unauthenticated" in runbook
    assert "--invoker-iam-check" in runbook
    assert "http://127.0.0.1:8766/core/web/index.html?feed=live" in runbook
    assert "Do not point OBS at `broadcast.viewregatta.com` or a `run.app` URL" in runbook


def test_render_host_installer_uses_limited_restartable_login_tasks():
    installer = (ROOT / "v3/broadcast/deploy/install_private_feed_relay.ps1").read_text(
        encoding="utf-8"
    )

    assert "New-ScheduledTaskPrincipal" in installer
    assert "-LogonType Interactive" in installer
    assert "-RunLevel Limited" in installer
    assert "-RestartCount 3" in installer
    assert '"ViewRegatta Private Feed Relay"' in installer
    assert '"ViewRegatta Standings Card"' in installer


def test_producer_image_honours_the_bounded_rest_read_plane_without_exposing_token():
    dockerfile = (ROOT / "v3/broadcast/deploy/producer.Dockerfile").read_text(encoding="utf-8")

    command = dockerfile[dockerfile.index('CMD ["sh"') :]
    assert 'VR_PRODUCER_READ_BASE:+--read-base' in command
    assert "VR_PRODUCER_READ_TOKEN" not in command
