"""Tests for SII scraper integration (gestion4sat + guias cross-module cache).

RUT 77.155.297-8 (SOLUCIONES RGA SPA) is expected to be already cached
in cache_rut_sii collection. Tests verify:
- /api/gestion4sat/scraper/rut/{rut} returns razon_social from cache
- /api/guias/consultar-rut/{rut} returns same data from shared cache
- Cross-module cache sharing (both endpoints hit cache_rut_sii)
"""
import os
import pytest
import requests

BASE_URL = os.environ.get("REACT_APP_BACKEND_URL", "https://doc-manager-111.preview.emergentagent.com").rstrip("/")
RUT_CACHED = "77155297-8"
EXPECTED_RAZON = "SOLUCIONES RGA SPA"


@pytest.fixture(scope="module")
def token_admin4sat():
    r = requests.post(
        f"{BASE_URL}/api/auth/login",
        json={"email": "admin4sat@demo.com", "password": "Test1234!"},
        timeout=15,
    )
    if r.status_code != 200:
        pytest.skip(f"login admin4sat failed: {r.status_code} {r.text}")
    return r.json().get("token") or r.json().get("access_token")


@pytest.fixture(scope="module")
def token_admin_demo():
    r = requests.post(
        f"{BASE_URL}/api/auth/login",
        json={"email": "admin@demo.com", "password": "Test1234!"},
        timeout=15,
    )
    if r.status_code != 200:
        pytest.skip(f"login admin@demo failed: {r.status_code} {r.text}")
    return r.json().get("token") or r.json().get("access_token")


class TestScraperSIIGestion4sat:
    def test_scraper_rut_returns_cached(self, token_admin4sat):
        headers = {"Authorization": f"Bearer {token_admin4sat}"}
        r = requests.get(
            f"{BASE_URL}/api/gestion4sat/scraper/rut/{RUT_CACHED}",
            headers=headers,
            timeout=30,
        )
        assert r.status_code == 200, r.text
        data = r.json()
        assert data.get("razon_social") == EXPECTED_RAZON, f"unexpected razon: {data}"
        # source could be cache OR g4s_empresas (both are instant, no scrape)
        assert data.get("source") in ("cache", "g4s_empresas"), f"unexpected source: {data}"
        assert data.get("rut") in ("77.155.297-8", "77155297-8")

    def test_scraper_rut_requires_auth(self):
        r = requests.get(f"{BASE_URL}/api/gestion4sat/scraper/rut/{RUT_CACHED}", timeout=10)
        assert r.status_code in (401, 403), r.status_code

    def test_scraper_rut_invalid(self, token_admin4sat):
        headers = {"Authorization": f"Bearer {token_admin4sat}"}
        r = requests.get(
            f"{BASE_URL}/api/gestion4sat/scraper/rut/123",
            headers=headers,
            timeout=10,
        )
        assert r.status_code == 400, r.text


class TestScraperSIIGuias:
    def test_consultar_rut_returns_cached(self, token_admin_demo):
        headers = {"Authorization": f"Bearer {token_admin_demo}"}
        r = requests.get(
            f"{BASE_URL}/api/guias/consultar-rut/{RUT_CACHED}",
            headers=headers,
            timeout=30,
        )
        assert r.status_code == 200, r.text
        data = r.json()
        assert data.get("razon_social") == EXPECTED_RAZON, f"unexpected: {data}"
        assert data.get("source") == "cache", f"expected cache hit, got: {data}"


class TestCrossModuleCacheSharing:
    def test_both_endpoints_share_cache(self, token_admin4sat, token_admin_demo):
        """Both endpoints must return the same razon_social from shared cache_rut_sii."""
        h1 = {"Authorization": f"Bearer {token_admin4sat}"}
        h2 = {"Authorization": f"Bearer {token_admin_demo}"}
        r1 = requests.get(f"{BASE_URL}/api/gestion4sat/scraper/rut/{RUT_CACHED}", headers=h1, timeout=15)
        r2 = requests.get(f"{BASE_URL}/api/guias/consultar-rut/{RUT_CACHED}", headers=h2, timeout=15)
        assert r1.status_code == 200 and r2.status_code == 200
        assert r1.json().get("razon_social") == r2.json().get("razon_social") == EXPECTED_RAZON


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
