
from __future__ import annotations
from typing import Dict, Tuple, Union
from shared.utils import soup_of
from ..http_client import fetch
from ..html_utils import absolutize_fragment
from bp.browse.services.slugs import product_slug_from_href
from .registry import REGISTRY, merge_missing
from . import extractors as _auto_register  # noqa: F401  (import-time side effects)

async def scrape_product_detail(product_url: str, include_html: bool = False) -> Union[dict, Tuple[dict, str]]:
    """
    Returns a dict with fields (subset):
      title, images, image, description_short, description_html, sections,
      slug, suma_href, stickers, labels, info_table fields, oe_list_price, prices,
      breadcrumbs-derived category_* fields.
    If include_html=True, returns (data, html).
    """
    html = await fetch(product_url)
    

    data: Dict[str, Union[str, float, int, list, dict, None]] = {
        "suma_href": product_url,
        "slug": product_slug_from_href(product_url),
    }

    # Run all extractors
    for fn in REGISTRY:
        try:
            soup = soup_of(html)
            piece = fn(soup, product_url) or {}
        except Exception:
            # Tolerate site drift
            continue
        merge_missing(data, piece)
    # If we found short description but not description_html, echo it
    if not data.get("description_html") and data.get("description_short"):
        data["description_html"] = absolutize_fragment(f"<p>{data['description_short']}</p>")

    # Ensure "image" mirrors first of images if not set
    if not data.get("image"):
        imgs = data.get("images") or []
        if isinstance(imgs, list) and imgs:
            data["image"] = imgs[0]

    if include_html:
        return data, html
    return data
