import os
import uuid

import pytest
from fastapi.testclient import TestClient

from normbase.main import app


def _auth_headers() -> dict:
    token = os.getenv("AIF_INTERNAL_SERVICE_TOKEN", "").strip()
    if not token:
        return {}
    return {"Authorization": f"Bearer {token}"}


def test_usage_token_closes_and_blocks_replay():
    strict = os.getenv("NORMBASE_USAGE_TOKEN_STRICT_REPLAY", "1").strip().lower()
    if strict in {"0", "false", "no", "off"}:
        pytest.skip("Strict replay protection disabled by environment.")

    role = f"role-{uuid.uuid4()}"
    agent_id = f"agent-{uuid.uuid4()}"
    key_id = f"kid-{uuid.uuid4()}"
    try:
        with TestClient(app) as client:
            headers = {
                "Content-Type": "application/json",
                "X-Agent-Id": agent_id,
                "X-Key-Id": key_id,
                **_auth_headers(),
            }

            created = client.post(
                "/api/v1/norms",
                json={
                    "name": f"replay-test-{uuid.uuid4()}",
                    "norm_type": "obligation",
                    "status": "active",
                    "scope_roles": [role],
                    "action": {"required": ["mask_pii"]},
                    "condition": {"trigger": "requires_report"},
                    "consequence": {},
                },
                headers=headers,
            )
            assert created.status_code == 201, created.text
            norm_id = created.json()["id"]

            retrieved = client.post(
                "/api/v1/retrieve",
                json={"context": {"requires_report": True}, "agent_role": role, "top_k": 5},
                headers=headers,
            )
            assert retrieved.status_code == 200, retrieved.text
            usage_token = retrieved.json()["usage_token"]

            first = client.post(
                "/api/v1/norms/log-outcome",
                json={
                    "usage_token": usage_token,
                    "norm_id": norm_id,
                    "outcome": "complied",
                    "details": {"source": "pytest"},
                },
                headers=headers,
            )
            assert first.status_code == 200, first.text

            replay = client.post(
                "/api/v1/norms/log-outcome",
                json={
                    "usage_token": usage_token,
                    "norm_id": norm_id,
                    "outcome": "complied",
                    "details": {"source": "pytest-replay"},
                },
                headers=headers,
            )
            assert replay.status_code == 409, replay.text
            assert "closed" in replay.text.lower() or "already reported" in replay.text.lower()
    except Exception as exc:
        pytest.skip(f"Normbase usage token replay test skipped: {exc}")
