"""首页平台级展示数据 endpoint(全平台门面数字,**不鉴权**——登录前首页也要展示)。

路由前缀 `/api/v1/platform`:
  GET /stats   首页三统计(帮助用户 / 完成比价 / 累计节省),按运营后台配的模式算。
  GET /flags   客户端运营 feature flag(比价/领券期广告开关等),客户端拉取后缓存。

展示模式(real/manual/random,每指标独立)与计算逻辑见 app/repositories/ops_stat.py。
"""
from __future__ import annotations

import logging

from fastapi import APIRouter, Query

from app.api.deps import DbSession
from app.repositories import app_config
from app.repositories import ops_marquee as marquee_crud
from app.repositories import ops_stat as crud
from app.schemas.platform import (
    AdConfigPublicOut,
    AppFlagsOut,
    AppVersionOut,
    PlatformStatsOut,
    SavingsFeedItem,
    SavingsFeedOut,
)

logger = logging.getLogger("shagua.platform")

router = APIRouter(prefix="/api/v1/platform", tags=["platform"])


@router.get("/stats", response_model=PlatformStatsOut, summary="首页三统计(全平台门面数字)")
def stats(db: DbSession) -> PlatformStatsOut:
    v = crud.get_display_values(db)
    return PlatformStatsOut(
        help_users=v["help_users"],
        total_compares=v["total_compares"],
        total_saved_cents=v["total_saved"],
    )


@router.get("/savings-feed", response_model=SavingsFeedOut, summary="首页轮播 feed(真实+种子混播)")
def savings_feed(db: DbSession, limit: int = Query(8, ge=1, le=30)) -> SavingsFeedOut:
    items = marquee_crud.get_feed(db, limit=limit)
    return SavingsFeedOut(items=[SavingsFeedItem(**it) for it in items])


@router.get("/flags", response_model=AppFlagsOut, summary="客户端运营 feature flag(不鉴权)")
def flags(db: DbSession) -> AppFlagsOut:
    """客户端拉取运营开关并缓存(app 启动 / 每场比价开始时刷新)。不鉴权:开关非敏感,
    且比价无障碍服务取值时未必有登录态。值来自 app_config(admin 可改),空库回退默认。"""
    return AppFlagsOut(
        comparing_ad_enabled=bool(app_config.get_value(db, "comparing_ad_enabled")),
    )


@router.get("/ad-config", response_model=AdConfigPublicOut, summary="客户端拉广告配置(穿山甲ID+场景开关,不鉴权)")
def ad_config(db: DbSession) -> AdConfigPublicOut:
    """客户端启动/每场广告前拉,缓存后用:app_id + 各位ID + 各场景开关。
    不含验签密钥;空库回退默认(=客户端内置值,维持现状)。"""
    c = app_config.get_ad_config(db)
    return AdConfigPublicOut(
        app_id=c["app_id"],
        reward_code_id=c["reward_code_id"],
        compare_draw_code_id=c["compare_draw_code_id"],
        coupon_draw_code_id=c["coupon_draw_code_id"],
        reward_enabled=c["reward_enabled"],
        compare_ad_enabled=c["compare_ad_enabled"],
        coupon_ad_enabled=c["coupon_ad_enabled"],
        withdrawal_ad_enabled=c["withdrawal_ad_enabled"],
    )


@router.get("/app-version", response_model=AppVersionOut, summary="最新 App 版本(OTA 检查更新,不鉴权)")
def app_version(db: DbSession) -> AppVersionOut:
    """客户端启动 / 手动检查更新时拉取。不鉴权:版本信息非敏感,且检查更新可能在登录前。
    用 latest_version_code 与本机 versionCode 比;未配置(返回默认 0)时客户端视为已是最新。"""
    data = app_config.get_app_version(db)
    if not data:
        return AppVersionOut()
    return AppVersionOut(**data)
