import pytest
from httpx import AsyncClient, ASGITransport
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from database import Base, get_db
from models.quota_policy import QuotaPolicy
from models.token_usage_log import TokenUsageLog
from dependencies import verify_admin_api_key
from main import app


@pytest.fixture
def admin_db():
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine, tables=[QuotaPolicy.__table__, TokenUsageLog.__table__])
    Session = sessionmaker(bind=engine)
    session = Session()
    yield session
    session.close()


@pytest.fixture
async def admin_client(admin_db):
    """Bypasses the API-key check entirely (override) and wires a real
    in-memory SQLite session so CRUD/report logic actually executes."""
    app.dependency_overrides[get_db] = lambda: admin_db
    app.dependency_overrides[verify_admin_api_key] = lambda: None
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as ac:
        yield ac
    app.dependency_overrides.clear()


@pytest.fixture
async def no_override_client(monkeypatch):
    """Client with the real verify_admin_api_key dependency still active —
    used to test the API-key gate itself."""
    monkeypatch.setenv("ADMIN_API_KEY", "test-admin-key-123")
    import dependencies
    dependencies.ADMIN_API_KEY = "test-admin-key-123"
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as ac:
        yield ac


# ── API-key gating ───────────────────────────────────────────────────────────

async def test_missing_api_key_returns_401(no_override_client):
    resp = await no_override_client.get("/admin/quota/policies")
    assert resp.status_code == 401


async def test_wrong_api_key_returns_401(no_override_client):
    resp = await no_override_client.get("/admin/quota/policies", headers={"X-Api-Key": "wrong-key"})
    assert resp.status_code == 401


async def test_correct_api_key_is_allowed(no_override_client):
    resp = await no_override_client.get("/admin/quota/policies", headers={"X-Api-Key": "test-admin-key-123"})
    assert resp.status_code == 200


# ── CRUD round-trip ───────────────────────────────────────────────────────────

async def test_create_and_list_policy(admin_client):
    resp = await admin_client.post("/admin/quota/policies", json={
        "scope_type": "user", "scope_id": 42, "daily_token_limit": 5000,
    })
    assert resp.status_code == 201
    created = resp.json()
    assert created["scope_type"] == "user"
    assert created["scope_id"] == 42
    assert created["daily_token_limit"] == 5000

    resp = await admin_client.get("/admin/quota/policies")
    assert resp.status_code == 200
    policies = resp.json()
    assert len(policies) == 1
    assert policies[0]["scope_id"] == 42


async def test_create_default_scope_requires_no_scope_id(admin_client):
    resp = await admin_client.post("/admin/quota/policies", json={
        "scope_type": "default", "daily_token_limit": 1000,
    })
    assert resp.status_code == 201


async def test_create_non_default_scope_without_scope_id_is_rejected(admin_client):
    resp = await admin_client.post("/admin/quota/policies", json={
        "scope_type": "user", "daily_token_limit": 1000,
    })
    assert resp.status_code == 400


async def test_create_duplicate_active_scope_is_rejected(admin_client):
    body = {"scope_type": "role", "scope_id": 1, "daily_token_limit": 1000}
    resp1 = await admin_client.post("/admin/quota/policies", json=body)
    assert resp1.status_code == 201
    resp2 = await admin_client.post("/admin/quota/policies", json=body)
    assert resp2.status_code == 409


async def test_patch_updates_limits(admin_client):
    create_resp = await admin_client.post("/admin/quota/policies", json={
        "scope_type": "user", "scope_id": 7, "daily_token_limit": 1000,
    })
    policy_id = create_resp.json()["id"]

    patch_resp = await admin_client.patch(f"/admin/quota/policies/{policy_id}", json={
        "daily_token_limit": 2000, "is_active": False,
    })
    assert patch_resp.status_code == 200
    body = patch_resp.json()
    assert body["daily_token_limit"] == 2000
    assert body["is_active"] is False


async def test_patch_nonexistent_policy_returns_404(admin_client):
    resp = await admin_client.patch("/admin/quota/policies/999", json={"daily_token_limit": 1})
    assert resp.status_code == 404


async def test_delete_policy_is_soft_delete(admin_client):
    """DELETE sets is_active=False rather than removing the row — the policy
    stays visible in the unfiltered list (for auditing) but drops out of an
    is_active=true filtered list, and re-DELETing it 404s (already inactive)."""
    create_resp = await admin_client.post("/admin/quota/policies", json={
        "scope_type": "user", "scope_id": 9, "daily_token_limit": 1000,
    })
    policy_id = create_resp.json()["id"]

    delete_resp = await admin_client.delete(f"/admin/quota/policies/{policy_id}")
    assert delete_resp.status_code == 200

    # Row still exists, just deactivated — not hard-deleted.
    list_resp = await admin_client.get("/admin/quota/policies")
    policies = list_resp.json()
    assert len(policies) == 1
    assert policies[0]["id"] == policy_id
    assert policies[0]["is_active"] is False

    # Filtering to active-only excludes it.
    active_resp = await admin_client.get("/admin/quota/policies", params={"is_active": True})
    assert active_resp.json() == []

    # Deleting an already-inactive policy 404s.
    redelete_resp = await admin_client.delete(f"/admin/quota/policies/{policy_id}")
    assert redelete_resp.status_code == 404


async def test_delete_nonexistent_policy_returns_404(admin_client):
    resp = await admin_client.delete("/admin/quota/policies/999")
    assert resp.status_code == 404


# ── usage report ──────────────────────────────────────────────────────────────

async def test_usage_report_filters_by_user_id(admin_client, admin_db):
    admin_db.add(TokenUsageLog(user_id=1, role_id=1, provider="deepseek", source="chat", total_tokens=100))
    admin_db.add(TokenUsageLog(user_id=2, role_id=1, provider="deepseek", source="chat", total_tokens=200))
    admin_db.commit()

    resp = await admin_client.get("/admin/quota/usage-report", params={"user_id": 1})
    assert resp.status_code == 200
    data = resp.json()["data"]
    assert len(data) == 1
    assert data[0]["user_id"] == 1
    assert data[0]["total_tokens"] == 100
