"""An HTTP application backed by an existing ContextBase space."""

import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import asdict
from typing import Any

from fastapi import FastAPI
from pydantic import BaseModel, Field

from contextbase import AsyncContextBase


@asynccontextmanager
async def lifespan(application: FastAPI) -> AsyncIterator[None]:
    """Share the asynchronous connection and close it on shutdown."""
    async with AsyncContextBase() as client:
        application.state.client = client
        application.state.space_id = os.environ['CONTEXTBASE_SPACE_ID']
        yield


app = FastAPI(lifespan=lifespan)


class Question(BaseModel):
    """A nonempty question for the configured knowledge base."""

    question: str = Field(min_length=1)


@app.post('/ask')
async def ask(question: Question) -> dict[str, Any]:
    """Return the generated answer and the passages supporting it."""
    client: AsyncContextBase = app.state.client
    space = await client.spaces.get(app.state.space_id)
    return asdict(await space.query(question.question))
