from fastapi.testclient import TestClient

import pataniscai.api as api_module
from pataniscai.config import Settings


class FakeOllama:
    model = "modelo-teste"

    def health(self) -> dict:
        return {
            "version": "teste", "model_available": True, "models_count": 1,
            "gpu": {"model_loaded": True, "vram_bytes": 1024},
        }


class FakeEngine:
    client = FakeOllama()

    def extract(self, documents):
        document = documents[0]
        return {
            "success": True,
            "engine_version": "pataniscAI-3.0.0-dev",
            "model": self.client.model,
            "duration_ms": 1,
            "documents": [{"id": document.document_id, "name": document.name, "type": document.document_type,
                           "ocr_ok": True, "chars": 5, "duration_ms": 1, "model_duration_ms": 1,
                           "eval_count": 1, "error_code": ""}],
            "transcriptions": [{"document_id": document.document_id, "name": document.name,
                                "type_hint": document.document_type, "text": "TESTE"}],
            "results": {}, "avisos": [], "incertos": [],
        }


def _client(monkeypatch) -> TestClient:
    config = Settings(
        token="segredo", allowed_ips=frozenset({"testclient"}), ollama_url="http://ollama",
        model="modelo-teste", request_timeout=5, max_files=2, max_file_bytes=1024,
    )
    monkeypatch.setattr(api_module, "settings", lambda: config)
    monkeypatch.setattr(api_module, "engine", lambda: FakeEngine())
    return TestClient(api_module.app)


def test_health_reports_model_ready(monkeypatch) -> None:
    response = _client(monkeypatch).get("/health")
    assert response.status_code == 200
    assert response.json()["ready"] is True
    assert response.json()["gpu"]["model_loaded"] is True


def test_extract_requires_token(monkeypatch) -> None:
    response = _client(monkeypatch).post("/v1/extract")
    assert response.status_code == 401


def test_extract_rejects_empty_manifest(monkeypatch) -> None:
    response = _client(monkeypatch).post(
        "/v1/extract",
        headers={"X-PataniscAI-Token": "segredo"},
        data={"manifest": '{"documents":[]}'},
    )
    assert response.status_code == 422


def test_extract_accepts_dynamic_upload_key(monkeypatch) -> None:
    manifest = '{"documents":[{"id":"d1","name":"pagina.png","type":"cc_verso","upload_key":"file_0"}]}'
    response = _client(monkeypatch).post(
        "/v1/extract",
        headers={"X-PataniscAI-Token": "segredo"},
        data={"manifest": manifest},
        files={"file_0": ("pagina.png", b"imagem", "image/png")},
    )
    assert response.status_code == 200
    assert response.json()["transcriptions"][0]["text"] == "TESTE"
