"""Application entrypoint."""

from contextlib import asynccontextmanager
import logging
from pathlib import Path

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

from app.api.router import api_router
from app.core.config import settings
from app.core.db import SessionLocal, init_db
from app.middleware.security import SecurityConfig, SecurityMiddleware
from app.services import runtime_config

logging.basicConfig(level=getattr(logging, settings.log_level, logging.INFO))
LOGGER = logging.getLogger("sentineledge")
BASE_DIR = Path(__file__).resolve().parents[1]
STATIC_DIR = BASE_DIR / "static"


@asynccontextmanager
async def lifespan(_app: FastAPI):
    """Initialize resources at startup."""
    init_db()
    config_warnings = runtime_config.initialize_runtime_config(session_factory=SessionLocal)
    orb_video = STATIC_DIR / "orbe.mp4"
    favicon = STATIC_DIR / "favicon.png"
    LOGGER.info("Static assets ready (orbe.mp4=%s favicon.png=%s)", orb_video.exists(), favicon.exists())
    if config_warnings:
        if settings.privacy_mode:
            LOGGER.warning("Runtime config warnings present (count=%s)", len(config_warnings))
        else:
            for warning in config_warnings:
                LOGGER.warning("Runtime config warning: %s", warning)
    if settings.is_production:
        LOGGER.info("%s running in PRODUCTION mode (Auth enabled)", settings.app_name)
    else:
        LOGGER.info("%s running in DEV mode", settings.app_name)
    yield


app = FastAPI(title=f"{settings.app_name} API", lifespan=lifespan)
cors_allow_headers = ["Authorization", "Content-Type", "X-API-Key"] if settings.is_production else ["*"]
cors_origin_regex = None if settings.is_production else r"^https?://(localhost|127\.0\.0\.1)(:\d+)?$"
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_allowed_origins,
    allow_origin_regex=cors_origin_regex,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allow_headers=cors_allow_headers,
)
app.add_middleware(
    SecurityMiddleware,
    config=SecurityConfig(
        mode=settings.app_mode,
        api_key=settings.sentineledge_api_key,
        auth_enabled=settings.is_production,
        assistant_rate_limit_per_minute=20,
    ),
)
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
app.include_router(api_router)
