# app/web/main.py
from __future__ import annotations
from fastapi import FastAPI
import logging
from starlette.middleware.sessions import SessionMiddleware
import os
from fastapi.staticfiles import StaticFiles
from importlib import import_module
from pkgutil import walk_packages
from pathlib import Path

app = FastAPI(title="GovBot Web")

# --- Static mount (절대경로) ---
# __file__ = /var/www/html/bot/app/web/main.py
# parents[2] = /var/www/html/bot
BASE_DIR = Path(__file__).resolve().parents[2]
STATIC_DIR = BASE_DIR / "static"
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")

# --- Session (for Auth) ---
SESSION_SECRET = os.getenv("SESSION_SECRET", "change-me")
app.add_middleware(SessionMiddleware, secret_key=SESSION_SECRET)

# Warn if default session secret is used (unsafe for production)
if SESSION_SECRET == "change-me":
    logging.getLogger("govbot.web").warning("SESSION_SECRET is using default; set a strong value in production.")

def include_all_page_routers():
    base_pkg = "app.web.pages"
    base_dir = Path(__file__).parent / "pages"
    for mod in walk_packages([str(base_dir)], prefix=base_pkg + "."):
        if mod.ispkg:
            continue
        module = import_module(mod.name)
        r = getattr(module, "router", None)
        if r is not None:
            app.include_router(r)

include_all_page_routers()

# --- Optional scheduler (ENABLE_SCHEDULER=1) ---
if os.getenv("ENABLE_SCHEDULER", "0") == "1":
    try:
        from .scheduler import start_scheduler, upsert_daily_cron
        from app.services.announce_service import send_daily_digest
        start_scheduler()
        # Daily digest at configured hour (local tz)
        try:
            hour = int(os.getenv("DIGEST_HOUR", "8"))
        except Exception:
            hour = 8
        upsert_daily_cron("daily_digest", send_daily_digest, hour=hour, minute=0, enabled=True)
    except Exception as e:
        import logging
        logging.getLogger("govbot.web").warning("Scheduler init skipped: %s", e)
