"""前台商店 API — 无需登录，只返回公开/在售数据。"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.models.product import ProductApiType, ProductStatus
from app.models.product_category import CategoryStatus, ProductCategory
from app.models.product_group import ProductGroup
from app.schemas.common import ApiResponse
from app.schemas.product import ProductPricingResponse, ProductResponse
from app.schemas.product_group import ProductCategoryResponse, ProductGroupResponse
from app.services.product_service import list_products
from app.services import provision_plugin_service

router = APIRouter()


@router.get("/categories", response_model=ApiResponse)
async def store_list_categories(db: AsyncSession = Depends(get_db)):
    result = await db.execute(
        select(ProductCategory)
        .where(ProductCategory.status == CategoryStatus.ACTIVE.value)
        .order_by(ProductCategory.sort_order.asc(), ProductCategory.id.asc())
    )
    cats = result.scalars().all()
    return ApiResponse(data=[ProductCategoryResponse.model_validate(c) for c in cats])


@router.get("/categories/{cat_slug}/groups", response_model=ApiResponse)
async def store_list_groups(cat_slug: str, db: AsyncSession = Depends(get_db)):
    cat_res = await db.execute(
        select(ProductCategory).where(ProductCategory.slug == cat_slug)
    )
    cat = cat_res.scalar_one_or_none()
    if not cat or cat.status != CategoryStatus.ACTIVE.value:
        raise HTTPException(status_code=404, detail="分类不存在")
    grp_res = await db.execute(
        select(ProductGroup)
        .where(ProductGroup.category_id == cat.id)
        .order_by(ProductGroup.sort_order.asc(), ProductGroup.id.asc())
    )
    groups = grp_res.scalars().all()
    return ApiResponse(data=[ProductGroupResponse.model_validate(g) for g in groups])


@router.get("/categories/{cat_slug}/groups/{group_slug}/products", response_model=ApiResponse)
async def store_list_products(
    cat_slug: str, group_slug: str, db: AsyncSession = Depends(get_db)
):
    cat_res = await db.execute(
        select(ProductCategory).where(ProductCategory.slug == cat_slug)
    )
    cat = cat_res.scalar_one_or_none()
    if not cat or cat.status != CategoryStatus.ACTIVE.value:
        raise HTTPException(status_code=404, detail="分类不存在")

    grp_res = await db.execute(
        select(ProductGroup).where(
            ProductGroup.category_id == cat.id,
            ProductGroup.slug == group_slug,
        )
    )
    group = grp_res.scalar_one_or_none()
    if not group:
        raise HTTPException(status_code=404, detail="产品组不存在")

    pairs = await list_products(db, group_id=group.id)

    out = []
    for p, pricings in pairs:
        if p.status != ProductStatus.ACTIVE.value:
            continue
        item = ProductResponse.model_validate(p)
        item.pricings = [ProductPricingResponse.model_validate(pp) for pp in pricings]
        if p.api_type == ProductApiType.PLUGIN.value and p.api_identifier:
            try:
                manifest = provision_plugin_service.get_plugin_manifest(str(p.api_identifier))
                item.provision_plugin = provision_plugin_service.public_manifest(manifest)
                item.product_page = item.provision_plugin.get("product_page")
            except Exception:
                item.provision_plugin = None
        out.append(item)
    return ApiResponse(data=out)
