from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException

from app.extractor import extract
from app.schemas import ParseRequest, ParseResponse

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

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


@router.post("/parse", response_model=ParseResponse)
def parse(req: ParseRequest) -> ParseResponse:
    logger.info(
        "parse request package=%s tree=%s clusters=%d",
        req.package_name,
        bool(req.tree),
        len(req.clusters),
    )
    result = extract(req.package_name, req.tree, req.clusters)

    if not result.get("success"):
        logger.info("parse failed: reason=%s raw=%s", result.get("reason"), result.get("raw"))
        raise HTTPException(
            status_code=422,
            detail=result.get("reason", "extract_failed"),
        )

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