"""Brain service — FastAPI entrypoint."""

import logging

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.routes import router
from app.config import DEBUG

logging.basicConfig(
    level=logging.DEBUG if DEBUG else logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)

app = FastAPI(
    title="Second Brain",
    description="Save everything. AI classifies it. Search it later.",
    version="1.0.0",
    docs_url="/api/docs" if DEBUG else None,
    redoc_url=None,
)

# No CORS — internal service only, accessed via gateway
app.include_router(router)


@app.on_event("startup")
async def startup():
    from sqlalchemy import text as sa_text
    from app.database import engine, Base
    from app.models.item import Item, ItemAsset, AppLink  # noqa: import to register models

    # Enable pgvector extension before creating tables
    async with engine.begin() as conn:
        await conn.execute(sa_text("CREATE EXTENSION IF NOT EXISTS vector"))
        await conn.run_sync(Base.metadata.create_all)

    # Ensure Meilisearch index exists
    from app.search.engine import ensure_meili_index
    await ensure_meili_index()

    logging.getLogger(__name__).info("Brain service started")
