"""微信小程序 Bootstrap API"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_tenant_by_appid
from app.core.models.tenant_channel import TenantChannel
from app.core.models.tenant import Tenant
from app.core.models.theme_settings import ThemeSettings
from app.core.models.payment_gateway import PaymentGateway
from app.core.models.tenant_settings import TenantSettings

router = APIRouter(tags=["小程序Bootstrap"])


class BootstrapIn(BaseModel):
    known_config_version: Optional[str] = None
    scene: Optional[int] = None
    query: Optional[dict] = None


def filter_sections_for_miniapp(sections: list) -> list:
    """Filter theme sections to only those enabled and supporting miniapp channel."""
    return [
        s for s in sections
        if s.get("enabled", True) and "miniapp" in s.get("supported_channels", ["h5", "miniapp"])
    ]


def build_payment_methods(gateways) -> list:
    """Build public-safe payment method list (no secrets)."""
    return [
        {
            "id": gw.id,
            "name": gw.name,
            "type": gw.code,
            "icon_url": gw.icon or None,
        }
        for gw in gateways
    ]


def build_shop_info(tenant, ts) -> dict:
    extra = (ts.extra or {}) if ts else {}
    return {
        "name": (ts.store_name if ts else None) or (tenant.name if tenant else ""),
        "logo": extra.get("store_logo", ""),
        "description": (ts.store_description if ts else None) or extra.get("description", ""),
        "currency": extra.get("currency", "NZD"),
        "locale": extra.get("locale", extra.get("default_language", "en")),
    }


@router.post("/store/mp/bootstrap", summary="小程序启动配置")
async def mp_bootstrap(
    request: Request,
    body: BootstrapIn,
    db: AsyncSession = Depends(get_db),
):
    # 1. 从 X-AppID 请求头解析租户
    appid = request.headers.get("x-appid", "").strip()
    if not appid:
        raise HTTPException(status_code=400, detail="缺少 X-AppID 请求头")

    tid = await get_tenant_by_appid(appid, db)

    # 2. 加载 TenantChannel（取 public_config）
    ch_r = await db.execute(
        select(TenantChannel).where(
            TenantChannel.appid == appid,
            TenantChannel.status == "active",
        )
    )
    ch: TenantChannel = ch_r.scalar_one_or_none()
    if not ch:
        raise HTTPException(status_code=404, detail="AppID 未注册")

    config_version = str(ch.updated_at)

    # 版本一致时返回轻量响应
    if body.known_config_version and body.known_config_version == config_version:
        return {"unchanged": True}

    # 3. 加载租户信息
    tenant_r = await db.execute(select(Tenant).where(Tenant.id == tid))
    tenant: Tenant = tenant_r.scalar_one_or_none()

    # 4. 加载装修配置
    theme_r = await db.execute(
        select(ThemeSettings).where(ThemeSettings.tenant_id == tid)
    )
    theme = theme_r.scalar_one_or_none()
    theme_data = theme.settings if theme and theme.settings else {}

    # 5. 支付方式（只返回展示层，不含密钥）
    gw_r = await db.execute(
        select(PaymentGateway)
        .where(PaymentGateway.tenant_id == tid, PaymentGateway.enabled == 1)
        .order_by(PaymentGateway.sort_order)
    )
    payment_methods = build_payment_methods(gw_r.scalars().all())

    # 6. 租户设置（功能开关等）
    ts_r = await db.execute(
        select(TenantSettings).where(TenantSettings.tenant_id == tid)
    )
    ts = ts_r.scalar_one_or_none()
    extra = (ts.extra or {}) if ts else {}

    # 7. 深链接处理
    redirect = None
    if body.query and "product_id" in body.query:
        redirect = f"/pages/products/{body.query['product_id']}"

    # 8. 过滤小程序 sections，替换 theme_data 中的 sections
    theme_settings = dict(theme_data)
    theme_settings["sections"] = filter_sections_for_miniapp(theme_data.get("sections", []))

    return {
        "tenant_id": tid,
        "config_version": config_version,
        "theme_version": config_version,
        "menu_version": config_version,
        "shop_info": build_shop_info(tenant, ts),
        "theme_settings": theme_settings,
        "payment_methods": payment_methods,
        "features": {
            "ai_chat": extra.get("ai_chat_enabled", False),
            "wishlist": True,
            "articles": True,
            "contact_form": True,
        },
        "public_channel_config": ch.get_public_config(),
        "redirect": redirect,
    }
