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 Configuration
# We dynamically build allowed origins from environment variables to simplify deployment.
_raw_origins = os.environ.get("ALLOWED_ORIGINS", "")
ALLOWED_ORIGINS = [o.strip() for o in _raw_origins.split(",") if o.strip()]

# Automatically add origins based on network_config.env variables if present
server_ip = os.environ.get("SERVER_IP")
front_port = os.environ.get("FRONTEND_PORT", "8907")
front_ssl_port = os.environ.get("FRONTEND_SSL_PORT", "8909")
back_ssl_port = os.environ.get("BACKEND_SSL_PORT", "8908")

# Always allow localhost
defaults = [
    f"http://localhost:{front_port}",
    f"https://localhost:{front_ssl_port}",
    f"https://localhost:{back_ssl_port}",
]
for d in defaults:
    if d not in ALLOWED_ORIGINS:
        ALLOWED_ORIGINS.append(d)

# Add IP-based origins if SERVER_IP is set
if server_ip and server_ip != "localhost":
    ip_origins = [
        f"http://{server_ip}:{front_port}",
        f"https://{server_ip}:{front_ssl_port}",
        f"https://{server_ip}:{back_ssl_port}",
    ]
    for ip_o in ip_origins:
        if ip_o not in ALLOWED_ORIGINS:
            ALLOWED_ORIGINS.append(ip_o)

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"}
