from __future__ import annotations

import datetime as dt
from types import SimpleNamespace

import pytest

from app.core import config
from app.models.pii import PiiRedactionRequest
from app.services import pii


@pytest.mark.asyncio
async def test_redact_text_builds_tokens_and_saves_history(monkeypatch):
    # Ensure deterministic UUID
    monkeypatch.setattr(pii.uuid, "uuid4", lambda: SimpleNamespace(hex="abc123def456"))

    # Avoid real Firestore
    saved_payloads = []

    class _Collection:
        def add(self, payload):
            saved_payloads.append(payload)

    class _Db:
        def collection(self, name):
            assert name == "piiRedactions"
            return _Collection()

    monkeypatch.setattr("app.services.pii.get_firestore_client", lambda: _Db())

    # Skip real credit deduction interactions
    monkeypatch.setattr(
        "app.services.credits.deduct_pii_redaction_credits",
        lambda user_id: {"userId": user_id, "credits": 999},
    )

    finding = SimpleNamespace(
        info_type=SimpleNamespace(name="PERSON"),
        quote="Alice",
        location=SimpleNamespace(content_locations=[]),
    )

    response = SimpleNamespace(result=SimpleNamespace(findings=[finding]))
    monkeypatch.setattr("app.services.pii._inspect_text", lambda parent, text: response)

    request = PiiRedactionRequest(text="Alice lives here")
    result = await pii.redact_text(request, user_id="user-1")

    assert result.anonymized_text == "<PII_PERSON_1> lives here"
    assert result.entities == {"PERSON": ["Alice"]}
    assert result.credits_used == 1

    assert saved_payloads
    history = saved_payloads[0]
    assert history["userId"] == "user-1"
    assert history["entityTypes"] == ["PERSON"]
    assert history["entityCount"] == 1
    assert history["creditsUsed"] == 1
    assert history["redactionId"] == "abc123def456"
