"""
Iteration 19 regression tests
Modules/features: worldcup public/admin API contract + release-bundle static integration files
"""

from pathlib import Path
import os
import uuid

import pytest
import requests


BASE_URL = (os.environ.get("REACT_APP_BACKEND_URL") or "").rstrip("/")
if not BASE_URL:
    pytest.skip("REACT_APP_BACKEND_URL is required", allow_module_level=True)


ROOT = Path("/app")


def _admin_login_token() -> str:
    response = requests.post(
        f"{BASE_URL}/api/auth/login",
        json={"username": "admin", "password": "admin123"},
        timeout=25,
    )
    if response.status_code != 200:
        pytest.skip(f"Admin login failed ({response.status_code}): {response.text}")
    data = response.json()
    token = data.get("access_token")
    assert isinstance(token, str) and len(token) > 10
    return token


def _get_worldcup_matches() -> list:
    response = requests.get(f"{BASE_URL}/api/worldcup/fixtures", timeout=25)
    assert response.status_code == 200, response.text
    data = response.json()
    assert data.get("configured") is True
    assert isinstance(data.get("matches"), list)
    return data["matches"]


def test_worldcup_public_fixture_endpoints_shape_and_alias():
    response_main = requests.get(f"{BASE_URL}/api/worldcup/fixtures", timeout=25)
    response_alias = requests.get(f"{BASE_URL}/api/sports/fixtures.php", timeout=25)

    assert response_main.status_code == 200, response_main.text
    assert response_alias.status_code == 200, response_alias.text

    main_data = response_main.json()
    alias_data = response_alias.json()

    assert main_data.get("configured") is True
    assert main_data.get("source") == "admin"
    assert isinstance(main_data.get("matches"), list)
    assert isinstance(main_data.get("standings"), list)

    assert alias_data.get("configured") is True
    assert alias_data.get("source") == "admin"
    assert isinstance(alias_data.get("matches"), list)
    assert isinstance(alias_data.get("standings"), list)


def test_admin_worldcup_post_requires_auth():
    response = requests.post(
        f"{BASE_URL}/api/admin/worldcup/fixtures",
        json={"matches": []},
        timeout=25,
    )
    assert response.status_code in (401, 403), response.text


def test_admin_worldcup_save_and_restore_snapshot():
    token = _admin_login_token()
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}

    before_matches = _get_worldcup_matches()
    test_match_id = f"TEST_ITER19_WC_{uuid.uuid4().hex[:8]}"

    test_matches = list(before_matches) + [
        {
            "id": test_match_id,
            "kickoffIso": "2026-07-15T18:00:00+00:00",
            "status": "UPCOMING",
            "group": "TEST_GROUP",
            "venue": "TEST_VENUE",
            "home": {"name": "TEST_HOME", "code": "th"},
            "away": {"name": "TEST_AWAY", "code": "ta"},
            "homeScore": None,
            "awayScore": None,
            "homePenalty": None,
            "awayPenalty": None,
            "broadcaster": "TEST_CHANNEL",
            "liveLabel": "",
        }
    ]

    save_response = requests.post(
        f"{BASE_URL}/api/admin/worldcup/fixtures",
        headers=headers,
        json={"matches": test_matches},
        timeout=30,
    )
    assert save_response.status_code == 200, save_response.text
    save_data = save_response.json()
    assert save_data.get("ok") is True
    assert isinstance(save_data.get("saved"), int)

    try:
        after_matches = _get_worldcup_matches()
        inserted = [m for m in after_matches if m.get("id") == test_match_id]
        assert len(inserted) == 1
        assert inserted[0]["home"]["name"] == "TEST_HOME"
        assert inserted[0]["away"]["name"] == "TEST_AWAY"
        assert inserted[0]["broadcaster"] == "TEST_CHANNEL"
    finally:
        restore_response = requests.post(
            f"{BASE_URL}/api/admin/worldcup/fixtures",
            headers=headers,
            json={"matches": before_matches},
            timeout=30,
        )
        assert restore_response.status_code == 200, restore_response.text


def test_google_services_json_contains_requested_ids():
    p = ROOT / "frontend/android/app/google-services.json"
    assert p.exists()
    txt = p.read_text(encoding="utf-8")
    assert '"project_id": "nadiplayer"' in txt
    assert '"mobilesdk_app_id": "1:939354065189:android:ae03f9a1067c310f43f2cc"' in txt


def test_php_firebase_service_account_exists_and_project_id_matches():
    p = ROOT / "release-bundle/nadiplayer/api/secrets/firebase-service-account.json"
    assert p.exists()
    txt = p.read_text(encoding="utf-8")
    assert '"type": "service_account"' in txt
    assert '"project_id": "nadiplayer"' in txt
    assert '"client_email": "firebase-adminsdk-fbsvc@nadiplayer.iam.gserviceaccount.com"' in txt


def test_php_api_index_dispatcher_has_worldcup_routes():
    p = ROOT / "release-bundle/nadiplayer/api/index.php"
    txt = p.read_text(encoding="utf-8")
    assert "require_once __DIR__ . '/routes/worldcup.php';" in txt
    assert "if ($method === 'GET'  && ($path === '/worldcup/fixtures' || $path === '/sports/fixtures.php'))" in txt
    assert "if ($method === 'POST' && $path === '/admin/worldcup/fixtures')" in txt


def test_admin_panel_includes_worldcup_sidebar_route_and_router_case():
    layout = (ROOT / "release-bundle/nadiplayer/admin_panel/views/layout.php").read_text(encoding="utf-8")
    assert "href=\"?page=worldcup\"" in layout
    assert "World Cup" in layout
    assert "case 'worldcup':  require __DIR__ . '/worldcup.php';  break;" in layout


def test_admin_worldcup_view_has_add_edit_bulk_import_and_table_actions():
    worldcup_view = (ROOT / "release-bundle/nadiplayer/admin_panel/views/worldcup.php").read_text(encoding="utf-8")

    assert 'name="action" value="save_worldcup_match"' in worldcup_view
    assert 'data-testid="worldcup-save-match-btn"' in worldcup_view
    assert 'data-testid="worldcup-cancel-edit-link"' in worldcup_view

    assert 'name="action" value="import_worldcup_json"' in worldcup_view
    assert 'data-testid="worldcup-json-input"' in worldcup_view
    assert 'data-testid="worldcup-import-json-btn"' in worldcup_view

    assert 'data-testid="worldcup-matches-table"' in worldcup_view
    assert 'data-testid="worldcup-edit-link-' in worldcup_view
    assert 'name="action" value="delete_worldcup_match"' in worldcup_view
    assert 'data-testid="worldcup-delete-btn-' in worldcup_view
