"""V3Q.AI — FastAPI entry point."""

from __future__ import annotations

import asyncio
import sys
from contextlib import asynccontextmanager
from pathlib import Path

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

from config import get_settings
from database.connection_manager import ConnectionManager
from logging_config import setup_logging
from preflight import run_and_report


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Startup / shutdown lifecycle."""
    settings = get_settings()

    # Setup structured logging (JSON-lines for Claude Code analysis)
    setup_logging(debug=settings.debug)

    import logging
    logger = logging.getLogger(__name__)
    logger.info("=" * 60)
    logger.info(f"  V3Q.AI v{settings.version} starting")
    logger.info(f"  Host: {settings.host}:{settings.port}  Debug: {settings.debug}")
    logger.info(f"  PostgreSQL: {settings.db.user}@{settings.db.host}:{settings.db.port}/{settings.db.database}")
    logger.info(f"  Pool: size={settings.db.pool_size}, overflow={settings.db.max_overflow}")
    logger.info(f"  Ollama: {settings.ollama.base_url} model={settings.ollama.model}")
    logger.info(f"  Claude: model={settings.claude.model} max_tokens={settings.claude.max_tokens}")
    logger.info(f"  Sync: batch_size={settings.sync.batch_size:,}")
    logger.info(f"  Notifications: enabled={settings.notifications.enabled}")
    logger.info("=" * 60)

    # Ensure results directory exists
    Path(settings.results_csv_path).mkdir(parents=True, exist_ok=True)

    # Initialize database connection pool
    cm = ConnectionManager(settings.db)
    await cm.initialize()
    app.state.db = cm
    app.state.settings = settings

    # Initialize Ollama client (local LLM)
    from local_llm.ollama_client import OllamaClient
    app.state.ollama = OllamaClient(settings.ollama)

    # Start sync scheduler (reads sync_schedule from table_registry)
    from database.local_pg import LocalPG
    from knowledge.table_registry import TableRegistry
    from knowledge.column_registry import ColumnRegistry
    from sync.scheduler import SyncScheduler

    local_pg = LocalPG(cm)
    tr = TableRegistry(cm)
    cr = ColumnRegistry(cm)
    scheduler = SyncScheduler(cm, local_pg, tr, cr)
    try:
        await scheduler.start()
        app.state.scheduler = scheduler
    except Exception as e:
        import logging
        logging.getLogger(__name__).warning(f"Scheduler start failed (non-critical): {e}")

    # Cleanup stale sync jobs from any previous crash/restart
    try:
        from sync.sync_jobs import SyncJobManager
        job_mgr = SyncJobManager(cm)
        await job_mgr.cleanup_stale_jobs()
        app.state.sync_job_manager = job_mgr
    except Exception as e:
        import logging
        logging.getLogger(__name__).warning(f"Sync job cleanup failed (non-critical): {e}")

    yield

    # Shutdown
    if hasattr(app.state, 'scheduler'):
        app.state.scheduler.stop()
    await cm.close()


app = FastAPI(
    title="V3Q.AI",
    version="1.0.0",
    description="Secure hybrid LLM text-to-SQL system",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173", "http://localhost:3000", "http://localhost:5174", "http://localhost:5175"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- Import and register routes ---
from routes.chat import router as chat_router
from routes.config import router as config_router
from routes.results import router as results_router
from routes.sync import router as sync_router
from routes.setup import router as setup_router
from routes.ws import router as ws_router
from routes.tracking import router as tracking_router
from routes.notifications import router as notifications_router

app.include_router(chat_router, prefix="/api")
app.include_router(config_router, prefix="/api")
app.include_router(results_router, prefix="/api")
app.include_router(sync_router, prefix="/api")
app.include_router(setup_router, prefix="/api")
app.include_router(ws_router, prefix="/api")
app.include_router(tracking_router, prefix="/api")
app.include_router(notifications_router, prefix="/api")


@app.get("/health")
async def health():
    return {"status": "ok", "version": "1.0.0", "service": "V3Q.AI"}


if __name__ == "__main__":
    import uvicorn

    # Run preflight checks before starting
    ok = asyncio.run(run_and_report())
    if not ok:
        sys.exit(1)

    settings = get_settings()
    uvicorn.run(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        timeout_keep_alive=300,
    )
