import os
import datetime
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from starlette.middleware.sessions import SessionMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
import anyio.lowlevel

# Limit the global thread pool to a small number (e.g., 5 or 10)
# This prevents the app from hitting the cPanel NPROC limit.
from anyio import CapacityLimiter
# Your local imports
from database import engine, Base
from config import settings
from routers import public, admin, api

# 1. Define Absolute Path Base Directory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 2. Initialize App
app = FastAPI(title="Local News", docs_url=None, redoc_url=None)

# 3. Middlewares
app.add_middleware(SessionMiddleware, secret_key=settings.SECRET_KEY, max_age=86400)

@app.middleware("http")
async def security_headers(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    response.headers["X-XSS-Protection"] = "1; mode=block"
    response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
    content_type = response.headers.get("Content-Type", "")
    if "text" in content_type or "javascript" in content_type:
        if "charset" not in content_type:
            response.headers["Content-Type"] = f"{content_type}; charset=utf-8"
            
    return response

# 4. Mount Static Files (FIXED: Using Absolute Path)
static_dir = os.path.join(BASE_DIR, "static")
app.mount("/static", StaticFiles(directory=static_dir), name="static")

# 5. Routers
app.include_router(api.router)
app.include_router(admin.router)
app.include_router(public.router)

# 6. Startup Event (FIXED: DB Initialization moved here to prevent timeouts)
@app.on_event("startup")
async def startup_event():
    # This runs only after Passenger has successfully started the worker
    Base.metadata.create_all(bind=engine)
    anyio.lowlevel.current_task().context.get(CapacityLimiter).total_tokens = 10
    # Note: APScheduler has been permanently removed for shared hosting compatibility.
    # Use a cPanel Cron Job pointing to a separate script for your scheduled posts.

# 7. Templates and Error Handlers (FIXED: Using Absolute Path)
templates_dir = os.path.join(BASE_DIR, "templates")
templates = Jinja2Templates(directory=templates_dir)

@app.exception_handler(404)
async def not_found(request: Request, exc):
    return templates.TemplateResponse("errors/404.html", {"request": request, "lang": "en"}, status_code=404)

@app.exception_handler(403)
async def forbidden(request: Request, exc):
    return templates.TemplateResponse("errors/403.html", {"request": request, "lang": "en"}, status_code=403)

# 8. Local Testing Block (Ignored by Passenger)
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", reload=False)