import pytest
from fastapi.testclient import TestClient


@pytest.fixture
def client():
    from app.main import app

    return TestClient(app)


def test_health_liveness(client):
    response = client.get("/api/v1/health/")
    assert response.status_code == 200
    assert response.json()["status"] == "ok"


def test_root_healthz(client):
    response = client.get("/healthz")
    assert response.status_code == 200
    assert response.json()["status"] == "ok"


def test_readyz_all_ok(client, monkeypatch):
    async def _true():
        return True

    monkeypatch.setattr("app.api.readiness.is_db_ready", _true)
    monkeypatch.setattr("app.api.readiness.is_embedding_engine_ready", _true)

    response = client.get("/api/v1/health/readyz")
    assert response.status_code == 200
    body = response.json()
    assert body["status"] == "ready"
    assert body["checks"] == {"mongo": True, "embedding_engine": True}


def test_readyz_fails_when_embedding_engine_down(client, monkeypatch):
    async def _true():
        return True

    async def _false():
        return False

    monkeypatch.setattr("app.api.readiness.is_db_ready", _true)
    monkeypatch.setattr("app.api.readiness.is_embedding_engine_ready", _false)

    response = client.get("/readyz")
    assert response.status_code == 503
    assert response.json()["status"] == "not_ready"
    assert response.json()["checks"]["embedding_engine"] is False


def test_version(client):
    response = client.get("/api/v1/version")
    assert response.status_code == 200
    body = response.json()
    assert body["service"] == "Lucos Cloud Client"
    assert "environment" in body
