"""GitCode 身份解析的认证、并发缓存与可恢复失败。"""

import asyncio
from unittest.mock import patch

import httpx
import pytest

from app.services import gitcode_identity as identity


@pytest.fixture(autouse=True)
def reset_identity():
    identity._cached_identity = None
    identity._inflight_lookups.clear()
    yield
    identity._cached_identity = None
    identity._inflight_lookups.clear()


@pytest.fixture
def mock_api(monkeypatch):
    client_class = httpx.AsyncClient

    def install(handler):
        monkeypatch.setattr(identity.httpx, "AsyncClient", lambda **kw: client_class(
            transport=httpx.MockTransport(handler), **kw,
        ))

    return install


@pytest.mark.asyncio
async def test_no_token_skips_network():
    with patch.object(identity.httpx, "AsyncClient") as client:
        assert await identity.resolve_gitcode_user_id() == ""
    client.assert_not_called()


@pytest.mark.asyncio
async def test_each_request_queries_online_and_only_inflight_calls_are_shared(mock_api):
    requests = []

    async def handler(request):
        requests.append(request)
        await asyncio.sleep(0)
        return httpx.Response(200, json={"id": f"real-user-{len(requests)}"})

    mock_api(handler)
    with patch.object(identity.settings, "atomgit_user_token", "primary-token"):
        assert await asyncio.gather(*(identity.resolve_gitcode_user_id() for _ in range(8))) == ["real-user-1"] * 8
        assert await identity.resolve_gitcode_user_id() == "real-user-2"
    assert len(requests) == 2
    assert str(requests[0].url) == "https://api.gitcode.com/api/v5/user"
    assert requests[0].headers["private-token"] == "primary-token"
    assert "primary-token" not in repr(identity._cached_identity)


@pytest.mark.asyncio
async def test_secondary_token_only_used_when_primary_is_not_configured(mock_api):
    tokens = []

    def handler(request):
        tokens.append(request.headers["private-token"])
        return httpx.Response(200, json={"id": "actual-user"})

    mock_api(handler)
    with patch.object(identity.settings, "atomgit_user_token", ""), patch.object(identity.settings, "gitcode_token", "configured-token"):
        assert await identity.resolve_gitcode_user_id() == "actual-user"
    assert tokens == ["configured-token"]


@pytest.mark.asyncio
@pytest.mark.parametrize("status", [401, 403])
async def test_authentication_failure_invalidates_cache_and_never_switches_token(mock_api, status):
    tokens = []
    mode = ["success"]

    def handler(request):
        tokens.append(request.headers["private-token"])
        if mode[0] == "success":
            return httpx.Response(200, json={"id": "verified-user"})
        if mode[0] == "timeout":
            raise httpx.ReadTimeout("temporary", request=request)
        return httpx.Response(status)

    mock_api(handler)
    with patch.object(identity.settings, "atomgit_user_token", "primary-token"), patch.object(
        identity.settings, "gitcode_token", "another-account-token",
    ), patch.object(identity.settings, "realtime_eval_expected_user_id", "configured-id"):
        assert await identity.resolve_gitcode_user_id() == "verified-user"
        mode[0] = "unauthorized"
        assert await identity.resolve_gitcode_user_id() == ""
        assert identity._cached_identity is None
        mode[0] = "timeout"
        assert await identity.resolve_gitcode_user_id() == ""
    assert set(tokens) == {"primary-token"}


@pytest.mark.asyncio
@pytest.mark.parametrize("failure", ["timeout", 429, 500, 503])
async def test_transient_failure_uses_recent_same_token_cache_after_online_retry(mock_api, failure):
    requests = []
    clock = [100.0]
    mode = ["success"]

    def handler(request):
        requests.append(request)
        if mode[0] == "success":
            return httpx.Response(200, json={"id": "verified-user"})
        if failure == "timeout":
            raise httpx.ReadTimeout("temporary", request=request)
        return httpx.Response(failure)

    mock_api(handler)
    with patch.object(identity.settings, "atomgit_user_token", "primary-token"), patch.object(
        identity, "monotonic", side_effect=lambda: clock[0],
    ):
        assert await identity.resolve_gitcode_user_id() == "verified-user"
        expiry = identity._cached_identity[2]
        mode[0] = "failure"
        clock[0] += 10
        assert await identity.resolve_gitcode_user_id() == "verified-user"
        assert len(requests) == 3  # 缓存存在时仍先联网两次。
        assert identity._cached_identity[2] == expiry
        clock[0] += 301
        assert await identity.resolve_gitcode_user_id() == ""
        assert len(requests) == 5


@pytest.mark.asyncio
async def test_changed_credentials_cannot_reuse_cache_or_recover_original_request_as_another_user(mock_api):
    tokens = []
    mode = ["success"]

    def handler(request):
        tokens.append(request.headers["private-token"])
        if mode[0] == "failure":
            raise httpx.ReadTimeout("temporary", request=request)
        return httpx.Response(200, json={"id": "user-1" if tokens[-1] == "token-1" else "user-2"})

    mock_api(handler)
    with patch.object(identity.settings, "atomgit_user_token", "token-1"):
        original_key = identity.gitcode_identity_key()
        assert await identity.resolve_gitcode_user_id() == "user-1"
        with patch.object(identity.settings, "atomgit_user_token", "token-2"):
            assert await identity.resolve_gitcode_user_id(expected_credential_key=original_key) == ""
            assert len(tokens) == 1
            mode[0] = "failure"
            assert await identity.resolve_gitcode_user_id() == ""
            mode[0] = "success"
            assert await identity.resolve_gitcode_user_id() == "user-2"
    assert "token-" not in repr(identity._cached_identity)


@pytest.mark.asyncio
async def test_failed_request_does_not_negative_cache_the_next_request(mock_api):
    count = [0]

    def handler(request):
        count[0] += 1
        if count[0] <= 2:
            raise httpx.ReadTimeout("temporary", request=request)
        return httpx.Response(200, json={"id": "recovered-user"})

    mock_api(handler)
    with patch.object(identity.settings, "atomgit_user_token", "primary-token"):
        assert await identity.resolve_gitcode_user_id() == ""
        assert await identity.resolve_gitcode_user_id() == "recovered-user"
    assert count[0] == 3


@pytest.mark.asyncio
async def test_cancelling_one_waiter_does_not_cancel_shared_identity_lookup(mock_api):
    started = asyncio.Event()
    release = asyncio.Event()
    requests = []

    async def handler(request):
        requests.append(request)
        started.set()
        await release.wait()
        return httpx.Response(200, json={"id": "actual-user"})

    mock_api(handler)
    with patch.object(identity.settings, "atomgit_user_token", "primary-token"):
        cancelled = asyncio.create_task(identity.resolve_gitcode_user_id())
        await started.wait()
        other = asyncio.create_task(identity.resolve_gitcode_user_id())
        await asyncio.sleep(0)
        cancelled.cancel()
        with pytest.raises(asyncio.CancelledError):
            await cancelled
        release.set()
        assert await other == "actual-user"
    assert len(requests) == 1


@pytest.mark.asyncio
@pytest.mark.parametrize("failure", ["not-json", "missing-id", "blank-id", "numeric-id", "oversized-id", 404])
async def test_invalid_response_never_uses_cache_or_configuration_as_an_id(mock_api, failure):
    def handler(request):
        if failure == "not-json":
            return httpx.Response(200, text="not JSON")
        if failure == 404:
            return httpx.Response(404)
        return httpx.Response(200, json={"id": {
            "missing-id": None, "blank-id": " ", "numeric-id": 42, "oversized-id": "x" * 129,
        }[failure], "login": "display-only"})

    mock_api(handler)
    with patch.object(identity.settings, "atomgit_user_token", "primary-token"), patch.object(
        identity.settings, "realtime_eval_expected_user_id", "configured-id",
    ), patch.object(identity.lts_logger, "log") as log:
        identity._cached_identity = (identity.gitcode_identity_key(), "cached-user", float("inf"))
        assert await identity.resolve_gitcode_user_id() == ""
        assert "primary-token" not in repr(log.call_args_list)