import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter
from slowapi.util import get_remote_address
from . import models
from .database import engine
from .routers import items, operations, users, categories, admin_db
from .logger import log
from .scheduler import scheduler, sync_scheduler_config

# Create the database tables
from .database import DATA_DIR, db_path
log.info(f"Using DATA_DIR: {DATA_DIR}")
log.info(f"Database path: {db_path}")
models.Base.metadata.create_all(bind=engine)
log.info("Database tables verified.")

app = FastAPI(title="TFM aInventory API", version="1.1.0")
log.info("TFM aInventory API process started.")

# [SECURITY FIX M-01] CORS: allow_origins=["*"] + allow_credentials=True is invalid per spec.
# Allowed origins are configured via ALLOWED_ORIGINS environment variable (comma-separated).
# Secure fallback: localhost only for development.
_raw_origins = os.environ.get(
    "ALLOWED_ORIGINS",
    "http://localhost:8907,https://localhost:8909"
)
ALLOWED_ORIGINS = [o.strip() for o in _raw_origins.split(",") if o.strip()]
log.info(f"CORS allowed origins: {ALLOWED_ORIGINS}")

# Add CORS middleware FIRST (before rate limiter)
app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# [H-02] Rate limiting on API
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter

app.include_router(items.router)
app.include_router(operations.router)
app.include_router(users.router)
app.include_router(categories.router)
app.include_router(admin_db.router)

@app.on_event("startup")
def startup_event():
    log.info("[STARTUP] Starting background scheduler...")
    scheduler.start()
    sync_scheduler_config()

@app.get("/")
def read_root():
    return {"message": "Inventory API is running"}
