"""API test: /api/keys and /api/stats with auth, over a mongomock-backed store.

No network: the Mongo store is swapped for an in-memory one. Run from the project root:
    venv/Scripts/python.exe tests/api_keys.py
"""
import os
import sys

import mongomock
from fastapi.testclient import TestClient

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)

os.environ["API_TOKEN"] = "test-token"
os.environ["MONGODB_URI"] = "mongodb://unused"  # never dialed; store is overridden below

from keystore import MongoKeyStore
import api.db as db

_coll = mongomock.MongoClient()["ai_key_hunt"]["keys"]
_store = MongoKeyStore(_collection=_coll)
db.get_store = lambda: _store   # all routers import get_store from api.db

from api.main import app  # import after the override

client = TestClient(app)
AUTH = {"Authorization": "Bearer test-token"}


def test_api():
    _store.upsert_many([
        {"key": "gsk_a", "provider_id": "groq", "masked": "gsk_a", "status": "working",
         "category": "working", "sources": ["alice/repo/.env"], "variables": ["GROQ_API_KEY"]},
        {"key": "AIza_c", "provider_id": "gemini", "masked": "AIza_c", "status": "dead",
         "category": "not_working", "sources": ["carol/x/.env"], "variables": ["GEMINI_API_KEY"]},
    ], run="r1")

    assert client.get("/api/health").json() == {"ok": True}

    # auth required
    assert client.get("/api/stats").status_code == 401
    assert client.get("/api/stats", headers={"Authorization": "Bearer wrong"}).status_code == 401

    s = client.get("/api/stats", headers=AUTH).json()
    assert s["total"] == 2 and s["by_category"] == {"working": 1, "not_working": 1}, s

    page = client.get("/api/keys", params={"category": "working"}, headers=AUTH).json()
    assert page["total"] == 1 and page["rows"][0]["key"] == "gsk_a", page

    page = client.get("/api/keys", params={"limit": 1, "page": 1}, headers=AUTH).json()
    assert page["total"] == 2 and len(page["rows"]) == 1, page

    one = client.get("/api/keys/gsk_a", headers=AUTH).json()
    assert one["provider_id"] == "groq", one
    assert client.get("/api/keys/missing", headers=AUTH).status_code == 404
    print("OK: /api/health, /api/stats, /api/keys (auth enforced)")


if __name__ == "__main__":
    test_api()
    print("api_keys passed")
