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_normbase_api_key_lifecycle_issue_resolve_revoke():
    agent_id = f"agent-{uuid.uuid4()}"
    try:
        with TestClient(app) as client:
            headers = {"Content-Type": "application/json", **_auth_headers()}
            issue = client.post(
                "/api/v1/keys/issue",
                json={"agent_id": agent_id, "name": "pytest-key"},
                headers=headers,
            )
            assert issue.status_code == 201, issue.text
            body = issue.json()
            api_key = body["api_key"]
            key_id = body["key_id"]
            assert body["agent_id"] == agent_id

            resolve_ok = client.post(
                "/api/v1/keys/resolve",
                json={"api_key": api_key},
                headers=headers,
            )
            assert resolve_ok.status_code == 200, resolve_ok.text
            assert resolve_ok.json()["agent_id"] == agent_id

            revoke = client.post(f"/api/v1/keys/{key_id}/revoke", headers=_auth_headers())
            assert revoke.status_code == 200, revoke.text
            assert revoke.json()["is_active"] is False

            resolve_fail = client.post(
                "/api/v1/keys/resolve",
                json={"api_key": api_key},
                headers=headers,
            )
            assert resolve_fail.status_code == 401
    except Exception as exc:
        pytest.skip(f"Normbase key API lifecycle skipped: {exc}")

