from __future__ import annotations import json import math from dataclasses import asdict from typing import Any from fastapi import APIRouter, Request from fastapi.responses import HTMLResponse, JSONResponse from app.core.request_id import get_or_create_request_id, set_request_id_header, set_request_id_on_state from app.core.time import iso_utc_ms from app.db.session import with_sqlite_busy_retry router = APIRouter() def _clamp_int(value: Any) -> int: try: return int(value or 0) except Exception: return 0 async def _query_gallery_stats(engine) -> dict[str, Any]: async def _op() -> dict[str, Any]: async with engine.connect() as conn: images_total = int((await conn.exec_driver_sql("SELECT COUNT(*) FROM images;")).scalar_one()) images_enabled = int((await conn.exec_driver_sql("SELECT COUNT(*) FROM images WHERE status=1;")).scalar_one()) illust_total = int((await conn.exec_driver_sql("SELECT COUNT(DISTINCT illust_id) FROM images;")).scalar_one()) authors_total = int( ( await conn.exec_driver_sql( "SELECT COUNT(DISTINCT user_id) FROM images WHERE user_id IS NOT NULL;" ) ).scalar_one() ) r18_count = int((await conn.exec_driver_sql("SELECT COUNT(*) FROM images WHERE status=1 AND x_restrict=1;")).scalar_one()) safe_count = int((await conn.exec_driver_sql("SELECT COUNT(*) FROM images WHERE status=1 AND x_restrict=0;")).scalar_one()) r18_unknown = int( (await conn.exec_driver_sql("SELECT COUNT(*) FROM images WHERE status=1 AND x_restrict IS NULL;")).scalar_one() ) ai_count = int((await conn.exec_driver_sql("SELECT COUNT(*) FROM images WHERE status=1 AND ai_type=1;")).scalar_one()) non_ai_count = int((await conn.exec_driver_sql("SELECT COUNT(*) FROM images WHERE status=1 AND ai_type=0;")).scalar_one()) ai_unknown = int( (await conn.exec_driver_sql("SELECT COUNT(*) FROM images WHERE status=1 AND ai_type IS NULL;")).scalar_one() ) return { "gallery": { "images_total": images_total, "images_enabled": images_enabled, "illust_total": illust_total, "authors_total": authors_total, }, "breakdown": { "r18": {"r18": r18_count, "safe": safe_count, "unknown": r18_unknown}, "ai": {"ai": ai_count, "non_ai": non_ai_count, "unknown": ai_unknown}, }, } return await with_sqlite_busy_retry(_op) def _build_status_html(*, base_url: str, status_code: int, payload: dict[str, Any]) -> str: base = (base_url or "").rstrip("/") if not base: base = "" def u(path: str) -> str: path_norm = (path or "").strip() if not path_norm.startswith("/"): path_norm = "/" + path_norm return f"{base}{path_norm}" api_status = str(payload.get("api_status") or "unknown") api_status_code = int(payload.get("api_status_code") or status_code) updated_at = str(payload.get("updated_at") or "") gallery = payload.get("gallery") if isinstance(payload.get("gallery"), dict) else {} images_total = _clamp_int(gallery.get("images_total")) images_enabled = _clamp_int(gallery.get("images_enabled")) illust_total = _clamp_int(gallery.get("illust_total")) authors_total = _clamp_int(gallery.get("authors_total")) random_stats = payload.get("random") if isinstance(payload.get("random"), dict) else {} random_total = _clamp_int(random_stats.get("total_requests")) random_in_flight = _clamp_int(random_stats.get("in_flight")) last_window_requests = _clamp_int(random_stats.get("last_window_requests")) last_window_success_rate = float(random_stats.get("last_window_success_rate") or 0.0) if not math.isfinite(last_window_success_rate): last_window_success_rate = 0.0 last_window_success_rate = max(0.0, min(float(last_window_success_rate), 1.0)) json_url = u("/status.json") docs_url = u("/docs") random_url = u("/random") wtf_url = u("/wtf") return f"""