"""FastAPI application for mykb daemon."""

import logging
import time
from contextlib import asynccontextmanager

from fastapi import FastAPI

from mykb.backends import get_backend
from mykb.core.api import MykbAPI
from mykb.core.config import get_config, get_backend_config
from mykb.core.embedder import Embedder
from mykb.core.indexer import EMBEDDING_DIMENSION

logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifespan context manager for loading model and backend."""
    config = get_config()
    start_time = time.time()

    # Load embedding model
    logger.info('Loading embedding model...')
    embedder = Embedder()
    _ = embedder.model  # Trigger lazy load
    app.state.model_name = config.get('embedding', {}).get('model', 'google/embeddinggemma-300m')
    logger.info('Embedding model loaded')

    # Initialize backend
    backend_type, backend_config = get_backend_config()
    logger.info(f'Initializing backend: {backend_type}')
    backend = get_backend(backend_type, **backend_config)
    backend.initialize('mykb', EMBEDDING_DIMENSION)
    app.state.backend_type = backend_type
    logger.info('Backend initialized')

    # Create MykbAPI with pre-initialized embedder and backend
    api = MykbAPI(embedder=embedder, backend=backend)
    app.state.api = api

    # Store startup time for uptime calculation
    app.state.start_time = start_time

    yield

    # Cleanup
    logger.info('Shutting down daemon...')
    if hasattr(app.state, 'api'):
        app.state.api.close()


def create_app() -> FastAPI:
    """Create and configure FastAPI app."""
    app = FastAPI(
        title='mykb daemon',
        description='Embedding and search daemon for mykb',
        version='0.1.0',
        lifespan=lifespan,
    )

    # Import and include routes
    from mykb.daemon.routes import router

    app.include_router(router)

    return app


# Module-level app instance for uvicorn
app = create_app()
