import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session

from app.database import SessionLocal
from app.logging_utils import get_logger
from app.models import User
from app.routes import router
from app.routers.admin import router as admin_router
from app.services import google_calendar_service, recurring_refresh_service

app = FastAPI()
logger = get_logger(__name__)


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # for now (later restrict)
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],expose_headers=["Content-Disposition"],

)
#prefix="/api/v1"
app.include_router(router)
app.include_router(admin_router)


@app.on_event("startup")
def bootstrap_calendar_watches():
    recurring_refresh_service.start_background_refresh_worker()

    webhook_url = os.getenv("GOOGLE_CALENDAR_WEBHOOK_URL")
    days_ahead = int(os.getenv("GOOGLE_CALENDAR_SYNC_DAYS", "30"))

    if not webhook_url:
        logger.warning("Google Calendar watch startup was skipped because the webhook URL is missing.")
        return

    db: Session = SessionLocal()
    try:
        users = (
            db.query(User)
            .filter(User.calendar_sync_enabled.is_(True))
            .filter((User.role == "admin") | (User.approval_status == "approved"))
            .filter(User.access_token.isnot(None))
            .all()
        )
        logger.info("Google Calendar watch startup has begun for %s users.", len(users))
        for user in users:
            try:
                result = google_calendar_service.ensure_google_watch(
                    db=db,
                    user=user,
                    webhook_url=webhook_url,
                    days_ahead=days_ahead,
                    auto_schedule_bot=True,
                )
                watch_state = result.get("watch_state")
                if watch_state:
                    logger.info(
                        "Google Calendar watch is ready for user %s. Channel id: %s. Expires at: %s.",
                        user.id,
                        watch_state.channel_id,
                        watch_state.expires_at,
                    )
            except Exception as exc:
                logger.exception("Google Calendar watch startup failed for user %s. Error: %s.", user.id, exc)
    finally:
        db.close()

@app.on_event("shutdown")
def stop_background_workers():
    recurring_refresh_service.stop_background_refresh_worker()
