from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, HTTPException, Header
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.db import engine, Base
from app import models  # noqa: F401
from app.api.routes import router

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Development convenience only; production should apply versioned migrations.
    if settings.app_env == "development":
        async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)
    yield
    await engine.dispose()

app = FastAPI(title=settings.app_name, version="1.0.0-phase1", lifespan=lifespan, docs_url="/docs" if settings.app_env != "production" else None)
app.add_middleware(CORSMiddleware, allow_origins=[x.strip() for x in settings.cors_origins.split(",") if x.strip()], allow_credentials=True, allow_methods=["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"], allow_headers=["Authorization", "Content-Type", "X-Telegram-Bot-Api-Secret-Token", "X-Bootstrap-Token"])
app.include_router(router)

@app.get("/health/live")
async def live(): return {"status": "ok", "service": "omega-api"}

@app.get("/health/ready")
async def ready():
    from sqlalchemy import text
    from app.db import SessionLocal
    try:
        async with SessionLocal() as db: await db.execute(text("SELECT 1"))
        return {"status": "ready", "database": "ok"}
    except Exception: raise HTTPException(503, "Database unavailable")

@app.post("/api/v1/telegram/webhook")
async def telegram_webhook(request: Request, x_telegram_bot_api_secret_token: str | None = Header(default=None)):
    if not settings.telegram_webhook_secret or x_telegram_bot_api_secret_token != settings.telegram_webhook_secret:
        raise HTTPException(403, "Invalid webhook secret")
    update = await request.json()
    # Bot service consumes updates in polling mode; webhook delivery is accepted only after secret validation.
    # Deploy the bot as a dedicated webhook consumer before enabling public production traffic.
    return {"accepted": True, "update_id": update.get("update_id")}
