"""AI Trading Signal Lab — FastAPI application.

PAPER TRADING ONLY. This API never places live orders.
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

import os

from .config import settings
from .database import Base, engine
from .routers import analytics, auth, dashboard, news, paper_trades, reports, risk, scanner
from .routers import scheduler as scheduler_router
from .routers import signals
from .security import (
    AuthGateMiddleware,
    RateLimitMiddleware,
    SecurityHeadersMiddleware,
    enforce_production_safety,
)
from .services.scheduler import auto_scan_enabled, scheduler

enforce_production_safety()

Base.metadata.create_all(bind=engine)

from .migrations import run_migrations  # noqa: E402

run_migrations(engine)

_IS_PROD = os.getenv("ENV", "development").lower() == "production"

app = FastAPI(
    title="AI Trading Signal Lab API",
    version="0.4.0",
    description="AI-powered trading research platform. Paper trading only — no live orders.",
    docs_url=None if _IS_PROD else "/docs",
    redoc_url=None if _IS_PROD else "/redoc",
    openapi_url=None if _IS_PROD else "/openapi.json",
)

app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(RateLimitMiddleware)
app.add_middleware(AuthGateMiddleware)

app.add_middleware(
    CORSMiddleware,
    allow_origins=[settings.FRONTEND_ORIGIN, "http://localhost:3000", "http://127.0.0.1:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(auth.router)
app.include_router(dashboard.router)
app.include_router(scanner.router)
app.include_router(signals.router)
app.include_router(paper_trades.router)
app.include_router(risk.router)
app.include_router(reports.router)
app.include_router(scheduler_router.router)
app.include_router(analytics.router)
app.include_router(news.router)


@app.on_event("startup")
def _start_auto_scan() -> None:
    if auto_scan_enabled():
        scheduler.start()


@app.get("/health")
def health():
    return {"status": "ok", "mode": "paper-trading-only"}
