from fastapi import FastAPI, BackgroundTasks, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
import os
import json
import asyncio
import sys

if sys.platform == 'win32':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

from backend.scheduler import start_scheduler
from backend.core.scanner import (
    load_json, scan_schema_for_db, scan_images_for_db_table, load_config, get_scan_status,
    SCHEMA_RESULTS_PATH, IMAGE_RESULTS_PATH
)

app = FastAPI(title="DB Health & Image Sync Monitor")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.on_event("startup")
async def startup_event():
    start_scheduler()

@app.get("/api/status")
async def get_status():
    return get_scan_status()

@app.get("/api/schema/latest")
async def get_schema_latest():
    return load_json(SCHEMA_RESULTS_PATH)

@app.get("/api/image/latest")
async def get_image_latest():
    return load_json(IMAGE_RESULTS_PATH)

@app.post("/api/scan/schema/{db_name}")
async def trigger_schema_scan(db_name: str):
    config = load_config()
    result = await scan_schema_for_db(db_name, config)
    return result

@app.post("/api/scan/image/{db_name}/{table_name}")
async def trigger_image_scan(db_name: str, table_name: str):
    config = load_config()
    result = await scan_images_for_db_table(db_name, table_name, config)
    return result

frontend_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'frontend')
app.mount("/static", StaticFiles(directory=frontend_dir), name="static")

@app.get("/")
async def serve_index():
    return FileResponse(
        os.path.join(frontend_dir, 'index.html'),
        headers={"Cache-Control": "no-cache, no-store, must-revalidate"}
    )
