"""
Tests for FEATURE 2026-01:
  - /api/public/app-info now returns terms_policy_text + tv_banner
  - PUT /api/admin/settings accepts tv_banner_enabled/type/html/image_url/click_url
    and terms_policy_text and round-trips via /api/public/app-info.
"""

import os
import pytest
import requests

BASE_URL = os.environ.get("REACT_APP_BACKEND_URL").rstrip("/")
ADMIN = {"username": "admin", "password": "admin123"}


@pytest.fixture(scope="module")
def admin_token():
    r = requests.post(f"{BASE_URL}/api/auth/login", json=ADMIN, timeout=15)
    assert r.status_code == 200, f"admin login failed: {r.status_code} {r.text}"
    tok = r.json().get("token") or r.json().get("access_token")
    assert tok, f"no token in login response: {r.json()}"
    return tok


@pytest.fixture(scope="module")
def admin_client(admin_token):
    s = requests.Session()
    s.headers.update({
        "Content-Type": "application/json",
        "Authorization": f"Bearer {admin_token}",
    })
    return s


# ───────── Public app-info shape ─────────
class TestPublicAppInfo:
    def test_app_info_returns_terms_and_tv_banner_keys(self):
        r = requests.get(f"{BASE_URL}/api/public/app-info", timeout=15)
        assert r.status_code == 200
        data = r.json()
        # terms_policy_text must exist as string
        assert "terms_policy_text" in data
        assert isinstance(data["terms_policy_text"], str)
        # tv_banner object must exist with all 5 keys
        assert "tv_banner" in data
        tb = data["tv_banner"]
        for key in ("enabled", "type", "html", "image_url", "click_url"):
            assert key in tb, f"missing tv_banner.{key}"
        assert isinstance(tb["enabled"], bool)
        assert tb["type"] in ("image", "html")
        assert isinstance(tb["html"], str)
        assert isinstance(tb["image_url"], str)
        assert isinstance(tb["click_url"], str)


# ───────── Persistence round-trip ─────────
class TestSettingsRoundTrip:
    def test_save_tv_banner_image_mode_and_verify_public(self, admin_client):
        payload = {
            "tv_banner_enabled": True,
            "tv_banner_type": "image",
            "tv_banner_image_url": "https://example.com/TEST_banner.png",
            "tv_banner_click_url": "https://example.com/TEST_click",
            "tv_banner_html": "<a href='TEST'>x</a>",
            "terms_policy_text": "# TEST Title\n\n- one\n- two\n- **bold**",
        }
        r = admin_client.put(f"{BASE_URL}/api/admin/settings", json=payload, timeout=15)
        assert r.status_code == 200, f"PUT settings failed: {r.status_code} {r.text}"

        # GET public app-info verifies persistence
        r2 = requests.get(f"{BASE_URL}/api/public/app-info", timeout=15)
        assert r2.status_code == 200
        data = r2.json()
        tb = data["tv_banner"]
        assert tb["enabled"] is True
        assert tb["type"] == "image"
        assert tb["image_url"] == "https://example.com/TEST_banner.png"
        assert tb["click_url"] == "https://example.com/TEST_click"
        assert tb["html"] == "<a href='TEST'>x</a>"
        assert data["terms_policy_text"] == "# TEST Title\n\n- one\n- two\n- **bold**"

    def test_switch_banner_type_to_html(self, admin_client):
        payload = {"tv_banner_type": "html"}
        r = admin_client.put(f"{BASE_URL}/api/admin/settings", json=payload, timeout=15)
        assert r.status_code == 200

        data = requests.get(f"{BASE_URL}/api/public/app-info", timeout=15).json()
        assert data["tv_banner"]["type"] == "html"
        # both payloads preserved — image_url not erased
        assert data["tv_banner"]["image_url"] == "https://example.com/TEST_banner.png"

    def test_disable_tv_banner(self, admin_client):
        r = admin_client.put(
            f"{BASE_URL}/api/admin/settings",
            json={"tv_banner_enabled": False},
            timeout=15,
        )
        assert r.status_code == 200
        data = requests.get(f"{BASE_URL}/api/public/app-info", timeout=15).json()
        assert data["tv_banner"]["enabled"] is False

    def test_admin_settings_requires_auth(self):
        r = requests.put(
            f"{BASE_URL}/api/admin/settings",
            json={"tv_banner_enabled": True},
            timeout=15,
        )
        assert r.status_code in (401, 403)


# ───────── Cleanup ─────────
@pytest.fixture(scope="module", autouse=True)
def cleanup(admin_client):
    yield
    try:
        admin_client.put(
            f"{BASE_URL}/api/admin/settings",
            json={
                "tv_banner_enabled": False,
                "tv_banner_type": "image",
                "tv_banner_html": "",
                "tv_banner_image_url": "",
                "tv_banner_click_url": "",
                "terms_policy_text": "",
            },
            timeout=15,
        )
    except Exception:
        pass
