"""Tests for the kernel API server wrapper."""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

from kernel_service.registry import ModelCapabilities
from kernel_service.server.app import create_app


class DummyModel:
    def __init__(self):
        self.requests = []

    def analyze(self, claim, tenant_id):
        self.requests.append((claim, tenant_id))
        return {
            "verdict": "denied",
            "explanation": {"summary": "dummy"},
            "financialImpact": {"projectedRecovery": 100.0, "currency": "USD"},
            "reportId": "rpt-123",
        }


class DummyRegistry:
    def __init__(self):
        self.model = DummyModel()
        self.capabilities = {
            "cxr-k1": ModelCapabilities(fusion_planes=7, uses_monte_carlo=False),
        }

    def list_models(self):
        return self.capabilities

    def get_capabilities(self, model_id):
        if model_id not in self.capabilities:
            raise ValueError(f"Model '{model_id}' not registered")
        return self.capabilities[model_id]

    def get_model(self, model_id=None):
        return self.model


@pytest.fixture()
def api_client(monkeypatch):
    # Ensure config validation passes during tests
    monkeypatch.setenv("CXR_DB_CONNECTION_STRING", "Driver={ODBC Driver};Server=fake;Database=fake;UID=user;PWD=pass;")
    registry = DummyRegistry()
    app = create_app(registry=registry)
    client = TestClient(app)
    return client, registry


def test_list_models(api_client):
    client, _ = api_client
    response = client.get("/models")
    assert response.status_code == 200
    payload = response.json()
    assert payload["defaultModelId"] == "cxr-k1"
    assert payload["models"][0]["modelId"] == "cxr-k1"


def test_analyze_endpoint(api_client):
    client, registry = api_client
    resp = client.post(
        "/analyze",
        json={
            "claim": {"claimId": "CLM-1"},
            "tenantId": "tenant-a",
        },
    )
    assert resp.status_code == 200
    data = resp.json()
    assert data["modelId"] == "cxr-k1"
    assert registry.model.requests[0][1] == "tenant-a"


def test_get_model_not_found(api_client):
    client, _ = api_client
    resp = client.get("/models/unknown")
    assert resp.status_code == 404
