#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Shopify Universal Commerce Protocol (UCP) MCP API Helper for BOARD-SEARCH.
Fetches active surfboard catalogs via POST https://{domain}/api/ucp/mcp (search_catalog)
with full cursor pagination, completely avoiding HTTP 429 rate-limits on /products.json.
"""

import json
import re
import ssl
import time
import urllib.request
from bs4 import BeautifulSoup

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Content-Type": "application/json",
    "Accept": "application/json",
}


def fetch_ucp_catalog(domain: str, queries=None, max_pages_per_query: int = 12, currency: str = "JPY", country: str = "JP") -> list:
    if queries is None:
        queries = ["surfboard"]
    mcp_url = f"https://{domain}/api/ucp/mcp"
    profile_url = f"https://{domain}/.well-known/ucp"

    seen_keys = set()
    all_items = []

    for q in queries:
        cursor = None
        for page in range(1, max_pages_per_query + 1):
            pg = {"limit": 250}
            if cursor:
                pg["cursor"] = cursor
            payload = {
                "jsonrpc": "2.0",
                "id": page,
                "method": "tools/call",
                "params": {
                    "name": "search_catalog",
                    "arguments": {
                        "meta": {"ucp-agent": {"profile": profile_url}},
                        "catalog": {
                            "query": q,
                            "filters": {"available": True},
                            "context": {"address_country": country, "language": "ja" if country == "JP" else "en", "currency": currency},
                            "pagination": pg,
                        },
                    },
                },
            }
            inner = None
            for attempt in range(3):
                try:
                    req = urllib.request.Request(
                        mcp_url,
                        data=json.dumps(payload).encode("utf-8"),
                        headers=HEADERS,
                    )
                    resp = urllib.request.urlopen(req, timeout=20, context=ctx)
                    data = json.loads(resp.read().decode("utf-8", "ignore"))
                    content_list = (data.get("result") or {}).get("content") or []
                    if content_list:
                        inner = json.loads(content_list[0].get("text") or "{}")
                    break
                except Exception as e:
                    if "429" in str(e):
                        time.sleep(2.0 * (attempt + 1))
                    elif attempt < 2:
                        time.sleep(1.0)
                    else:
                        break
            if not inner:
                break
            prods = inner.get("products") or []
            if not prods:
                break
            added_in_page = 0
            for p in prods:
                if not isinstance(p, dict):
                    continue
                handle = str(p.get("handle") or "").strip()
                p_url = str(p.get("url") or (f"https://{domain}/products/{handle}" if handle else "")).strip()
                p_title = str(p.get("title") or "").strip()
                if not p_title:
                    continue

                p_desc_obj = p.get("description") or {}
                p_desc_html = p_desc_obj.get("html") if isinstance(p_desc_obj, dict) else str(p_desc_obj)
                p_desc_txt = re.sub(r"<[^>]+>", " ", str(p_desc_html or ""))
                p_desc_txt = re.sub(r"\s+", " ", p_desc_txt).strip()
                p_media = [m.get("url") for m in (p.get("media") or []) if isinstance(m, dict) and m.get("url")]

                variants = p.get("variants") or []
                for v in variants:
                    if not isinstance(v, dict):
                        continue
                    avail = (v.get("availability") or {}).get("available", True)
                    if not avail:
                        continue
                    vid = str(v.get("id") or "").split("/")[-1]
                    sku = str(v.get("sku") or vid).strip()
                    v_title = str(v.get("title") or "").strip()
                    if v_title and v_title.lower() != "default title":
                        full_title = f"{p_title} ({v_title})"
                        item_url = f"{p_url}?variant={vid}" if vid else p_url
                    else:
                        full_title = p_title
                        item_url = p_url

                    if not item_url or item_url in seen_keys:
                        continue
                    seen_keys.add(item_url)

                    pr_obj = v.get("price") or {}
                    raw_amount = float(pr_obj.get("amount") or 0)
                    pr_curr = str(pr_obj.get("currency") or currency).upper()
                    if pr_curr in ("USD", "EUR", "AUD", "GBP"):
                        price_val = round(raw_amount / 100.0, 2) if raw_amount >= 10000 else raw_amount
                    else:
                        price_val = round(raw_amount / 100.0, 0) if raw_amount >= 3000000 else raw_amount

                    v_desc_obj = v.get("description") or {}
                    v_desc_html = v_desc_obj.get("html") if isinstance(v_desc_obj, dict) else str(v_desc_obj)
                    if v_desc_html:
                        desc_txt = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", str(v_desc_html))).strip()
                    else:
                        desc_txt = p_desc_txt

                    v_media = [m.get("url") for m in (v.get("media") or []) if isinstance(m, dict) and m.get("url")]
                    imgs = list(dict.fromkeys(v_media + p_media))
                    if not imgs:
                        continue

                    cond_type = "used" if re.search(r"\bUSED\b|中古|ユーズド|CONSIGNMENT|SECOND\s*HAND", f"{full_title} {desc_txt[:150]}", re.I) else "new"

                    all_items.append({
                        "source_url": item_url,
                        "source_id": sku or vid or handle,
                        "title": full_title,
                        "title_en": full_title if country != "JP" else "",
                        "original_currency": pr_curr,
                        "original_price": price_val,
                        "base_price": price_val if pr_curr == "JPY" else 0,
                        "condition_type": cond_type,
                        "description": desc_txt[:2500],
                        "main_image_url": imgs[0],
                        "image_urls": imgs[:8],
                    })
                    added_in_page += 1

            pg_info = inner.get("pagination") or {}
            next_cur = pg_info.get("next_cursor") or pg_info.get("cursor")
            has_next = pg_info.get("has_next_page", bool(next_cur and next_cur != cursor))
            if not has_next or not next_cur or next_cur == cursor or added_in_page == 0:
                break
            cursor = next_cur

    return all_items
