"""POST /api/v1/parse-text —— iOS 端的"已知商品/价格,只需归簇 + 估常见价"接口。

application/json:
  {"title": "...", "price": 99.0, "source_app": "淘宝",
   "clusters": [{"id":"<uuid>","title":"..."}, ...]}

使用场景:
  - iOS 主 App 内"手动新建记录":用户手填了 title/price/source_app
  - Share Extension 收到的是纯文本(分享链接的标题文案)而非图片

占坑期实现接 mock_extractor;后续接真模型时改这里调真实 extractor_text。
"""
from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException

from app.mock_extractor import mock_extract_text
from app.schemas import ParseStrResponse, ParseTextRequest

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

router = APIRouter(prefix="/api/v1")


@router.post("/parse-text", response_model=ParseStrResponse)
async def parse_text(req: ParseTextRequest) -> ParseStrResponse:
    if not req.title.strip():
        raise HTTPException(status_code=422, detail="empty_title")
    if req.price <= 0:
        raise HTTPException(status_code=422, detail="invalid_price")

    logger.info(
        "parse_text request title=%r price=%.2f source=%s clusters=%d",
        req.title,
        req.price,
        req.source_app,
        len(req.clusters),
    )

    result = await mock_extract_text(req.title, req.price, req.source_app, req.clusters)
    if not result.get("success"):
        raise HTTPException(status_code=422, detail=result.get("reason", "extract_failed"))

    return ParseStrResponse(
        title=result["title"],
        price=result["price"],
        source_app=result["source_app"],
        cluster_id=result.get("cluster_id"),
        typical_price=result["typical_price"],
    )
