import json
import importlib
from datetime import date
from types import SimpleNamespace

import pytest
from fastapi.testclient import TestClient

from keepedu_performance.api import auth, identity
from keepedu_performance.api.app import app

app_module = importlib.import_module("keepedu_performance.api.app")


TOKEN = "b" * 64
SESSION_ID = "a" * 64
GESTOR = "http://localhost/github-app/keepedu/gestor/"
client = TestClient(app)


@pytest.fixture
def payload():
    return {
        "school": "escola-teste",
        "schoolName": "Colégio Teste",
        "institute": "tenant-teste",
        "gestorUsuarioId": 77,
        "email": "coord@example.test",
        "roleTitle": "Coordenador",
        "roleColor": "1a2B3c",
        "user": {"id": "uuid-backoffice", "gestorId": 77, "name": "Coordenadora"},
        "gestorHomeUrl": GESTOR + "home/",
        "logoutUrl": GESTOR + "logout?slo=1",
        "ssoSessionId": SESSION_ID,
        "plataformaDestino": "performance",
        "ssoMarker": {"cookie": "keepsso_local_escola-teste", "value": "c" * 16},
    }


class SsoConnection:
    def __init__(self, payload):
        self.payload = payload
        self.pending_used = False
        self.used = False
        self.closed = False
        self.central_active = True
        self.query = ""

    def cursor(self):
        return self

    def __enter__(self):
        return self

    def __exit__(self, *args):
        pass

    def execute(self, query, values=None):
        self.query = query
        if query.startswith("DELETE FROM sso_tokens"):  # consumir o ticket é apagar a linha
            self.pending_used = True

    def fetchone(self):
        if "FROM sso_sessions" in self.query:
            return {"ativa": 1, "restante": 3600} if self.central_active else None
        return None if self.used else {"auth_data": json.dumps(self.payload)}

    def fetchall(self):
        return [{"url_gestor": GESTOR}]

    def commit(self):
        self.used = self.pending_used

    def rollback(self):
        self.pending_used = False

    def close(self):
        self.closed = True


@pytest.fixture(autouse=True)
def session_settings(monkeypatch):
    monkeypatch.setattr(identity.settings, "session_secret", "s" * 32)
    monkeypatch.setattr(identity.settings, "keepedu_institute", "")
    monkeypatch.setattr(identity, "register_tenant", lambda *args: None)


@pytest.fixture
def connection(monkeypatch, payload):
    connection = SsoConnection(payload)
    monkeypatch.setattr(identity, "_connection", lambda: connection)
    return connection


def bearer(payload):
    session = identity._session(
        payload["user"], payload["school"], payload["institute"], payload
    )
    session["ssoSessionId"] = SESSION_ID
    return {"Authorization": "Bearer " + auth.create_session_token(session)}


def test_exchange_preserves_gestor_identity_urls_and_marker(connection):
    result = identity.exchange_sso(TOKEN)
    session = result["user"]
    assert session["usuarioId"] == "77"
    assert session["role"] == "Coordenador"
    assert session["roleColor"] == "#1a2B3c"
    assert session["anoLetivo"] == date.today().year
    assert session["schoolName"] == "Colégio Teste"
    assert session["gestorHomeUrl"] == GESTOR + "home/"
    assert session["gestorLoginUrl"] == GESTOR + "login"
    assert session["gestorLogoutUrl"] == GESTOR + "logout?slo=1"
    assert session["ssoMarcador"] == {
        "cookie": "keepsso_local_escola-teste",
        "valor": "c" * 16,
    }
    principal = auth.verify_session_token(result["token"], "s" * 32)
    assert principal.subject == "77"
    assert principal.academic_year == date.today().year
    assert connection.used
    assert identity.exchange_sso(TOKEN) is None


def test_signing_failure_does_not_consume_token(connection, monkeypatch):
    monkeypatch.setattr(identity.settings, "session_secret", "")
    with pytest.raises(RuntimeError):
        identity.exchange_sso(TOKEN)
    assert not connection.used
    monkeypatch.setattr(identity.settings, "session_secret", "s" * 32)
    assert identity.exchange_sso(TOKEN) is not None


def test_gestor_urls_can_derive_login_from_logout_when_home_is_missing(payload):
    del payload["gestorHomeUrl"]
    session = identity._session(
        payload["user"], payload["school"], payload["institute"], payload
    )
    assert session["gestorLoginUrl"] == GESTOR + "login"
    assert session["gestorHomeUrl"] == GESTOR + "home/"


@pytest.mark.parametrize(
    "invalid",
    [
        [],
        {"school": "escola-teste", "user": {"id": 1}},
        {"institute": "tenant-teste", "user": {"id": 1}},
    ],
)
def test_incomplete_payload_does_not_issue_session_or_consume_token(
    connection, invalid
):
    connection.payload = invalid
    assert identity.exchange_sso(TOKEN) is None
    assert not connection.used


def test_exchange_resolves_legacy_institute_mapping(connection, monkeypatch):
    del connection.payload["institute"]
    monkeypatch.setattr(
        identity.settings, "keepedu_institute", '{"escola-teste":"tenant-teste"}'
    )
    assert identity.exchange_sso(TOKEN)["user"]["institute"] == "tenant-teste"


def test_exchange_uses_server_year_even_if_environment_has_an_old_year(
    connection, monkeypatch
):
    monkeypatch.setattr(identity.settings, "keepedu_anoletivo", 2020)

    result = identity.exchange_sso(TOKEN)

    assert result["user"]["anoLetivo"] == date.today().year


def test_revoked_session_rejects_authenticated_api_request(payload, monkeypatch):
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: None)
    response = client.get("/api/v1/auth/me", headers=bearer(payload))
    assert response.status_code == 401


def test_active_session_can_read_profile(payload, monkeypatch):
    payload["images"] = {
        "icons": {"negative": "https://cdn.example.test/logo-sm.png"}
    }
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: payload)
    response = client.get("/api/v1/auth/me", headers=bearer(payload))
    assert response.status_code == 200
    assert response.json()["role"] == "Coordenador"
    assert response.json()["images"] == payload["images"]


def test_active_session_can_read_its_institute_report_logo(payload, monkeypatch):
    payload["images"] = {
        "logos": {"boletim": "https://cdn.example.test/boletim.png"}
    }
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: payload)
    monkeypatch.setattr(
        app_module.requests,
        "get",
        lambda *args, **kwargs: SimpleNamespace(
            status_code=200,
            headers={"Content-Type": "image/png"},
            content=b"png-bytes",
        ),
    )

    response = client.get("/api/v1/auth/images/boletim", headers=bearer(payload))

    assert response.status_code == 200
    assert response.content == b"png-bytes"
    assert response.headers["content-type"] == "image/png"
    assert response.headers["cache-control"] == "private, no-store"


def test_report_logo_is_optional(payload, monkeypatch):
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: payload)

    response = client.get("/api/v1/auth/images/boletim", headers=bearer(payload))

    assert response.status_code == 404


def test_central_outage_is_not_reported_as_expired(payload, monkeypatch):
    def unavailable(*args, **kwargs):
        raise RuntimeError("offline")

    monkeypatch.setattr(identity, "central_session", unavailable)
    assert client.get("/api/v1/auth/me", headers=bearer(payload)).status_code == 503
    assert (
        client.get("/api/v1/auth/central-session", headers=bearer(payload)).status_code
        == 503
    )


def test_central_poll_reports_revocation_without_requiring_active_session(
    payload, monkeypatch
):
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: None)
    response = client.get("/api/v1/auth/central-session", headers=bearer(payload))
    assert response.status_code == 200
    assert response.json() == {"active": False, "platforms": []}


def test_logout_is_idempotent_and_bound_to_authenticated_session(payload, monkeypatch):
    removed = []
    monkeypatch.setattr(identity, "remove_central_session", removed.append)
    response = client.post(
        "/api/v1/auth/logout",
        headers=bearer(payload),
        json={"sessionToken": "another-session"},
    )
    assert response.status_code == 200
    assert removed == [SESSION_ID]
    assert (
        client.post("/api/v1/auth/logout", headers=bearer(payload)).status_code == 200
    )


def test_chained_logout_only_returns_to_registered_gestor_login(connection):
    assert identity.gestor_return_url(GESTOR + "login") == GESTOR + "login"
    assert identity.gestor_return_url("https://untrusted.example/login") == ""
    assert (
        identity.gestor_return_url(GESTOR + "login?return=https://untrusted.example")
        == ""
    )
    assert identity.gestor_return_url("javascript:alert(1)") == ""


def test_database_failure_at_exchange_returns_service_error(monkeypatch):
    def unavailable(*args):
        raise RuntimeError("offline")

    monkeypatch.setattr(identity, "exchange_sso", unavailable)
    assert (
        client.post("/api/v1/auth/sso/exchange", json={"token": TOKEN}).status_code
        == 503
    )


@pytest.mark.parametrize("path", ["/sso", "/logout"])
def test_legacy_platform_entry_redirects_to_frontend_without_consuming_token(
    path, monkeypatch
):
    monkeypatch.setattr(identity.settings, "app_public_url", "http://localhost:3000/")

    def no_exchange(*args):
        pytest.fail("The entry redirect must not consume an SSO token")

    monkeypatch.setattr(identity, "exchange_sso", no_exchange)
    query = (
        f"token={TOKEN}&next=%2F&return=http%3A%2F%2Flocalhost%2Fgestor%2Flogin&slo=1"
    )
    response = client.get(path + "?" + query, follow_redirects=False)
    assert response.status_code == 307
    assert response.headers["location"] == "http://localhost:3000" + path + "?" + query
    assert response.headers["cache-control"] == "no-store"
    assert response.headers["referrer-policy"] == "no-referrer"


@pytest.mark.parametrize(
    "url",
    [
        "",
        "javascript:alert(1)",
        "http://testserver",
        "http://testserver/",
        "https://frontend.test/?redirect=1",
    ],
)
def test_legacy_entry_rejects_missing_invalid_or_recursive_frontend_url(
    url, monkeypatch
):
    monkeypatch.setattr(identity.settings, "app_public_url", url)
    response = client.get("/sso?token=" + TOKEN, follow_redirects=False)
    assert response.status_code == 503


# ── Credencial do navegador: token em sessionStorage, enviado em Authorization: Bearer (nenhum cookie) ────────────────────

FRONT = "http://front.test"
MARKER = {"cookie": "keepsso_local_escola-teste", "valor": "c" * 16}


@pytest.fixture
def front(monkeypatch):
    monkeypatch.setattr(auth.settings, "app_public_url", FRONT)
    monkeypatch.setattr(auth.settings, "api_cors_origins", [])


def _bearer(token):
    return {"Authorization": "Bearer " + token}


def test_sso_exchange_returns_the_session_token_and_sets_no_cookie(connection, front):
    response = client.post("/api/v1/auth/sso/exchange", json={"token": TOKEN})

    assert response.status_code == 200
    assert set(response.json()) == {"token"}
    assert "set-cookie" not in response.headers
    session = auth.verify_session_token(response.json()["token"], "s" * 32)
    assert session.sso_session_id == SESSION_ID and session.subject == "77"


def test_login_returns_the_session_token_and_sets_no_cookie(payload, monkeypatch, front):
    monkeypatch.setattr(auth.settings, "local_login", True)
    session = {**identity._session(payload["user"], payload["school"], payload["institute"], payload), "loc": 1}
    monkeypatch.setattr(
        identity,
        "login",
        lambda *args: {"token": auth.create_session_token(session), "user": session},
    )

    response = client.post("/api/v1/auth/login", json={"email": "coord@example.test", "password": "x"})

    assert response.status_code == 200 and set(response.json()) == {"token"}
    assert "set-cookie" not in response.headers
    assert auth.verify_session_token(response.json()["token"], "s" * 32).local_session is True


def test_bearer_authenticates_and_profile_never_exposes_the_central_id(payload, monkeypatch, front):
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: payload)

    me = client.get("/api/v1/auth/me", headers=_bearer(_signed(payload)))

    assert me.status_code == 200
    body = me.json()
    assert body["ssoVinculada"] is True and body["school"] == "escola-teste"
    assert body["gestorLoginUrl"] == GESTOR + "login"
    assert body["gestorLogoutUrl"] == GESTOR + "logout?slo=1"
    assert SESSION_ID not in me.text and "ssoSessionId" not in me.text
    assert me.headers["cache-control"] == "no-store"


def test_a_session_token_sent_as_a_cookie_does_not_authenticate(payload, monkeypatch, front):
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: payload)

    response = client.get("/api/v1/auth/me", cookies={"painel_session": _signed(payload)})

    assert response.status_code == 401


def test_profile_carries_the_marker_so_the_panel_decides_whether_the_browser_shares_it(payload, monkeypatch, front):
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: payload)

    body = client.get("/api/v1/auth/me", headers=_bearer(_signed(payload))).json()

    assert body["ssoMarcador"] == MARKER


def test_revoked_central_session_rejects_the_token_on_the_next_request(payload, monkeypatch, front):
    monkeypatch.setattr(identity, "central_session", lambda *args, **kwargs: None)

    response = client.get("/api/v1/auth/me", headers=_bearer(_signed(payload)))

    assert response.status_code == 401


def test_logout_ends_the_central_session_and_returns_gestor_links(payload, monkeypatch, front):
    removed = []
    monkeypatch.setattr(identity, "remove_central_session", removed.append)

    response = client.post("/api/v1/auth/logout", headers=_bearer(_signed(payload)))

    assert response.status_code == 200 and removed == [SESSION_ID]
    assert response.json()["gestorLoginUrl"] == GESTOR + "login"
    assert "set-cookie" not in response.headers


def test_logout_without_a_valid_session_is_idempotent_and_touches_nothing(monkeypatch, front):
    monkeypatch.setattr(identity, "remove_central_session", lambda *args: pytest.fail("sem sessao nao apaga a central"))

    invalid = client.post("/api/v1/auth/logout", headers=_bearer("invalido.assinatura"))
    missing = client.post("/api/v1/auth/logout")

    assert invalid.status_code == 200 and invalid.json() == {"authenticated": False}
    assert missing.status_code == 200 and missing.json() == {"authenticated": False}


def test_cors_allows_the_panel_origin_with_authorization_and_never_with_credentials(monkeypatch):
    from keepedu_performance.api import app as app_module

    cors = [item for item in app_module.app.user_middleware if item.cls.__name__ == "CORSMiddleware"]
    if not cors:
        pytest.skip("CORS desligado neste ambiente (sem APP_PUBLIC_URL)")
    options = cors[0].kwargs
    assert options["allow_credentials"] is False
    assert "Authorization" in options["allow_headers"] and "*" not in options["allow_origins"]


# ── B2/B3/B4: destino do ticket, vínculo obrigatório e /sso/status ─────────────────────────────────────────────────────

def test_ticket_for_another_platform_is_refused_and_not_burned(connection, payload):
    payload["plataformaDestino"] = "genesis"

    assert identity.exchange_sso(TOKEN) is None
    assert connection.used is False

    payload["plataformaDestino"] = "performance"  # o mesmo ticket segue valendo para a plataforma certa
    assert identity.exchange_sso(TOKEN) is not None


@pytest.mark.parametrize("session_id", [None, "", "curto", "Z" * 64])
def test_ticket_without_a_valid_central_link_is_refused_and_not_burned(connection, payload, session_id):
    payload.pop("ssoSessionId")
    if session_id is not None:
        payload["ssoSessionId"] = session_id

    assert identity.exchange_sso(TOKEN) is None
    assert connection.used is False


def test_ticket_for_an_ended_central_session_is_refused_and_not_burned(connection):
    connection.central_active = False

    assert identity.exchange_sso(TOKEN) is None
    assert connection.used is False


def _signed(payload, linked=True, **extra):
    """Sessão assinada como a API emite; `linked=False` tira o ssoSessionId e `extra` acrescenta campos (ex.: loc=1)."""
    session = identity._session(payload["user"], payload["school"], payload["institute"], payload)
    if linked:
        session["ssoSessionId"] = SESSION_ID
    return auth.create_session_token({**session, **extra})


def test_session_without_central_link_is_refused_even_with_local_login_on(payload, monkeypatch, front):
    monkeypatch.setattr(auth.settings, "local_login", True)
    monkeypatch.setattr(identity, "central_session", lambda *a, **k: pytest.fail("sem vinculo nao consulta a central"))
    token = _signed(payload, linked=False)  # sem `ssoSessionId` e sem a marca de sessão local

    response = client.get("/api/v1/auth/me", headers=_bearer(token))

    assert response.status_code == 401


def test_local_session_only_works_while_local_login_is_on(payload, monkeypatch, front):
    headers = _bearer(_signed(payload, linked=False, loc=1))

    monkeypatch.setattr(auth.settings, "local_login", False)
    assert client.get("/api/v1/auth/me", headers=headers).status_code == 401
    monkeypatch.setattr(auth.settings, "local_login", True)
    me = client.get("/api/v1/auth/me", headers=headers)
    assert me.status_code == 200 and me.json()["ssoVinculada"] is False


def test_direct_login_is_disabled_unless_the_dev_flag_is_on(monkeypatch, front):
    monkeypatch.setattr(identity, "login", lambda *args: pytest.fail("login direto desligado"))
    monkeypatch.setattr(auth.settings, "local_login", False)

    response = client.post("/api/v1/auth/login", json={"email": "a@b", "password": "x"})

    assert response.status_code == 403
    assert "set-cookie" not in response.headers


def test_identity_login_itself_refuses_when_the_flag_is_off(monkeypatch):
    monkeypatch.setattr(auth.settings, "local_login", False)

    with pytest.raises(PermissionError):
        identity.login("a@b", "x")


def test_central_poll_does_not_keep_an_unlinked_session_alive(payload, monkeypatch, front):
    monkeypatch.setattr(auth.settings, "local_login", False)

    response = client.get("/api/v1/auth/central-session", headers=_bearer(_signed(payload, linked=False)))

    assert response.status_code == 200 and response.json() == {"active": False, "platforms": []}


def test_service_token_keeps_working_without_a_central_link(monkeypatch):
    monkeypatch.setattr(
        auth.settings, "api_service_tokens", {"svc": {"subject": "bff", "institute": "tenant-a", "scopes": ["read"]}}
    )
    monkeypatch.setattr(identity, "central_session", lambda *a, **k: pytest.fail("token de servico nao tem sessao central"))

    response = client.get("/api/v1/auth/me", headers={"Authorization": "Bearer svc"})

    assert response.status_code == 200


def test_status_reports_the_link_without_ever_exposing_the_session_id(payload, monkeypatch, front):
    import hashlib

    monkeypatch.setattr(identity, "central_session_state", lambda identifier: ("ativa", 17934))
    marker = hashlib.sha256(SESSION_ID.encode()).hexdigest()[:16]

    response = client.get("/api/v1/sso/status", headers=_bearer(_signed(payload)))

    assert response.status_code == 200 and response.headers["cache-control"] == "no-store"
    assert response.json() == {
        "plataforma": "performance",
        "vinculada": True,
        "sessaoCentral": "ativa",
        "marcador": marker,
        # A API nao recebe cookies (a credencial vai em Bearer): quem confere o cookie keepsso_* e o painel.
        "marcadorNoNavegador": None,
        "expiraEm": 17934,
        "checadaHa": 0,
    }
    assert SESSION_ID not in response.text


@pytest.mark.parametrize("state", ["ausente", "indisponivel"])
def test_status_still_answers_when_the_central_row_is_gone_or_unreachable(payload, monkeypatch, front, state):
    monkeypatch.setattr(identity, "central_session_state", lambda identifier: (state, None))

    body = client.get("/api/v1/sso/status", headers=_bearer(_signed(payload))).json()

    assert body["sessaoCentral"] == state and body["expiraEm"] is None and body["vinculada"] is True


def test_status_requires_a_platform_session_and_reports_no_link_for_local_sessions(payload, front):
    assert client.get("/api/v1/sso/status").status_code == 401

    body = client.get("/api/v1/sso/status", headers=_bearer(_signed(payload, linked=False, loc=1))).json()

    assert body["vinculada"] is False and body["sessaoCentral"] == "sem-vinculo" and body["marcador"] is None


@pytest.mark.parametrize(
    "row, expected",
    [({"restante": 3600}, ("ativa", 3600)), ({"restante": 0}, ("ausente", None)), (None, ("ausente", None))],
)
def test_central_state_reads_the_row_without_renewing_it(monkeypatch, row, expected):
    queries = []

    class Reader:
        def cursor(self):
            return self

        def __enter__(self):
            return self

        def __exit__(self, *args):
            pass

        def execute(self, query, values=None):
            queries.append(query)

        def fetchone(self):
            return row

        def close(self):
            pass

    monkeypatch.setattr(identity, "_connection", lambda: Reader())

    assert identity.central_session_state(SESSION_ID) == expected
    assert queries and all(query.startswith("SELECT") for query in queries)


def test_central_state_reports_unavailable_when_the_database_is_down(monkeypatch):
    def down():
        raise RuntimeError("sem banco")

    monkeypatch.setattr(identity, "_connection", down)

    assert identity.central_session_state(SESSION_ID) == ("indisponivel", None)
