"""Iteration 2 backend tests:
   - GET /api/public/geo now returns lat/lon
   - GET /api/public/weather?lat&lon returns temp_c/weather_code/source
   - Regression on ad-config + auth/login
"""
import os
import requests
import pytest

BASE_URL = (os.environ.get("REACT_APP_BACKEND_URL") or "").rstrip("/")
if not BASE_URL:
    with open("/app/frontend/.env") as f:
        for line in f:
            if line.startswith("REACT_APP_BACKEND_URL="):
                BASE_URL = line.split("=", 1)[1].strip().rstrip("/")
                break


@pytest.fixture(scope="module")
def session():
    s = requests.Session()
    s.headers.update({"Content-Type": "application/json"})
    return s


# Geo: now must include numeric lat/lon
class TestGeoLatLon:
    def test_geo_lat_lon_present(self, session):
        r = session.get(f"{BASE_URL}/api/public/geo", timeout=15)
        assert r.status_code == 200, r.text
        d = r.json()
        for k in ("city", "country", "country_code", "lat", "lon", "source"):
            assert k in d, f"missing {k} in {d}"
        if d["source"] != "none":
            assert isinstance(d["lat"], (int, float)), f"lat not numeric: {d}"
            assert isinstance(d["lon"], (int, float)), f"lon not numeric: {d}"


# Weather endpoint
class TestPublicWeather:
    def test_weather_known_coords(self, session):
        r = session.get(
            f"{BASE_URL}/api/public/weather",
            params={"lat": 41.26, "lon": -95.86},
            timeout=15,
        )
        assert r.status_code == 200, r.text
        d = r.json()
        assert "temp_c" in d and "weather_code" in d and "source" in d
        assert d["source"] in ("open-meteo", "none")
        if d["source"] == "open-meteo":
            assert isinstance(d["temp_c"], (int, float)), f"temp_c not numeric: {d}"
            assert isinstance(d["weather_code"], (int, float)), f"weather_code not numeric: {d}"

    def test_weather_missing_params_400(self, session):
        r = session.get(f"{BASE_URL}/api/public/weather", timeout=10)
        # FastAPI returns 422 for missing required query params
        assert r.status_code in (400, 422), r.text


# Regression
class TestRegression:
    def test_ad_config(self, session):
        r = session.get(f"{BASE_URL}/api/public/ad-config", timeout=10)
        assert r.status_code == 200
        d = r.json()
        for k in ("enabled", "testing", "banner_id", "interstitial_id", "interstitial_every"):
            assert k in d

    def test_login_admin(self, session):
        r = session.post(
            f"{BASE_URL}/api/auth/login",
            json={"username": "admin", "password": "admin123"},
            timeout=10,
        )
        assert r.status_code == 200, r.text
        d = r.json()
        tk = next((k for k in ("access_token", "token", "jwt") if k in d), None)
        assert tk and isinstance(d[tk], str) and len(d[tk]) > 10
