#!/usr/bin/env python3
"""Scrape Briggs & Riley UK (briggs-riley.co.uk, Shopify) for cabin-sized bags.

Fetches /products.json (all products), filters to luggage/bags/backpacks that are
carry-on / underseat / cabin-sized, then fetches each product page with Playwright
(the store fronts products.json with bot protection that plain HTTP fails) and
parses the spec block:

    EXTERIOR DIMENSIONS (includes wheels & handles) 55.9 x 35.6 x 22.9 - 29.2 cm / ...
    WEIGHT 4.4 kg / 9.7 lbs

Output: data/bags.json  (also data/bags_raw.json with the raw Shopify payloads)
"""
import asyncio
import json
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlparse

from playwright.async_api import async_playwright

ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "data"
BASE = "https://briggs-riley.co.uk"
US_BASE = "https://www.briggs-riley.com"
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")

# product_type values that can plausibly be cabin luggage (never accessories/sets)
CANDIDATE_TYPES = {"Luggage", "Bags", "Backpacks", "Backpacks & Bags", "Duffle Bag"}
SKIP_TITLE = re.compile(r"\b(set|gift card)\b", re.I)
CABIN_MARKETING = re.compile(r"carry[- ]?on|cabin|underseat|weekender|overnight", re.I)
MAX_CABIN_HEIGHT_CM = 56.0  # tallest carry-on height any listed airline allows


def html_to_text(html: str) -> str:
    text = re.sub(r"(?is)<script[\s\S]*?</script>", " ", html)
    text = re.sub(r"(?is)<style[\s\S]*?</style>", " ", text)
    text = re.sub(r"(?s)<[^>]+>", " ", text)
    text = text.replace("&amp;", "&").replace("&nbsp;", " ")
    text = re.sub(r"[ \t]+", " ", text)
    return text


DIM_RE = re.compile(
    r"EXTERIOR DIMENSIONS[^\d]{0,120}?"  # case-insensitive flag below
    r"(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)"
    r"(?:\s*[-–]\s*(\d+(?:\.\d+)?))?\s*cm"
    r"(?:[^0-9]{0,60}?(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*in)?"
    r"(?:[^0-9]{0,40}?\(?\s*(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*in\s*(?:expanded|Expanded)\)?)?",
    re.I,
)
# inches-first variant: "EXTERIOR DIMENSIONS ... 21 x 14 x 9 in / 53.5 x 35.5 x 23 cm"
DIM_RE_IN_FIRST = re.compile(
    r"EXTERIOR DIMENSIONS[^\d]{0,120}?"
    r"(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*in"
    r"\s*/\s*(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*cm",
    re.I,
)
EXPANDED_CM_RE = re.compile(r"(\d+(?:\.\d+)?)\s*cm\s*\(?\s*expanded", re.I)
EXPANDED_IN_RE = re.compile(r"\(\s*(\d+(?:\.\d+)?)\s*in\s*expanded\s*\)", re.I)
WEIGHT_RE = re.compile(r"WEIGHT\s*(\d+(?:\.\d+)?)\s*kg", re.I)
WEIGHT_RE_LBS_FIRST = re.compile(r"WEIGHT\s*(\d+(?:\.\d+)?)\s*lbs?\s*/\s*(\d+(?:\.\d+)?)\s*kg", re.I)
CAPACITY_RE = re.compile(r"CAPACITY\s*(\d+(?:\.\d+)?)\s*(?:-|–)\s*(\d+(?:\.\d+)?)\s*(?:lit(?:re|er)s?)", re.I)


def parse_spec(text: str):
    """Return dict with exterior dims cm (unexpanded, expanded_depth optional), weight kg, source strings."""
    out = {}
    m = DIM_RE.search(text)
    mi = DIM_RE_IN_FIRST.search(text)
    if m and (not mi or m.start() <= mi.start()):
        h, w, d = (float(g) for g in m.group(1, 2, 3))
        out.update(height=h, width=w, depth=d, dims_source=m.group(0).strip()[:200])
        if m.group(4):
            out["expanded_depth"] = float(m.group(4))
            out["expanded_source"] = m.group(0).strip()[:200]
    elif mi:
        h, w, d = (float(g) for g in mi.group(4, 5, 6))
        out.update(height=h, width=w, depth=d,
                   dims_source="cm part of 'in / cm' pair: " + mi.group(0).strip()[:200])
    else:
        # some pages only give inches
        in_only = re.search(
            r"EXTERIOR DIMENSIONS[^\d]{0,120}?"
            r"(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*(?:x|×|X)\s*(\d+(?:\.\d+)?)\s*in", text, re.I)
        if in_only:
            h, w, d = (round(float(g) * 2.54, 1) for g in in_only.groups())
            out.update(height=h, width=w, depth=d, dims_source="inches converted to cm: " + in_only.group(0).strip())
        else:
            return None
    # expanded depth given as "(11 in Expanded)" -> convert
    if "expanded_depth" not in out:
        ei = EXPANDED_IN_RE.search(text)
        if ei:
            out["expanded_depth"] = round(float(ei.group(1)) * 2.54, 1)
            out["expanded_source"] = ei.group(0)
        ec = EXPANDED_CM_RE.search(text)
        if ec:
            out["expanded_depth"] = float(ec.group(1))
            out["expanded_source"] = ec.group(0)
    wm = WEIGHT_RE.search(text)
    if wm:
        out["weight_kg"] = float(wm.group(1))
        out["weight_source"] = wm.group(0).strip()
    else:
        wl = WEIGHT_RE_LBS_FIRST.search(text)
        if wl:
            out["weight_kg"] = float(wl.group(2))
            out["weight_source"] = wl.group(0).strip()
    cm = CAPACITY_RE.search(text)
    if cm:
        out["capacity_litres"] = [float(cm.group(1)), float(cm.group(2))]
    return out


async def fetch_json(page, url):
    resp = await page.goto(url, timeout=60000, wait_until="domcontentloaded")
    if resp.status != 200:
        raise RuntimeError(f"{url} -> HTTP {resp.status}")
    return json.loads(await resp.text())


async def main():
    DATA.mkdir(exist_ok=True)
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        ctx = await browser.new_context(user_agent=UA, locale="en-GB")
        page = await ctx.new_page()

        # 1. all products
        products = []
        n = 1
        while True:
            d = await fetch_json(page, f"{BASE}/products.json?limit=250&page={n}")
            ps = d.get("products", [])
            products.extend(ps)
            if len(ps) < 250:
                break
            n += 1
        (DATA / "bags_raw.json").write_text(json.dumps(products, indent=1), encoding="utf-8")
        print(f"fetched {len(products)} products from {BASE}")

        # 2. candidates
        candidates = []
        for pr in products:
            if pr.get("product_type") not in CANDIDATE_TYPES:
                continue
            if SKIP_TITLE.search(pr.get("title", "")):
                continue
            candidates.append(pr)
        print(f"{len(candidates)} candidate products (luggage/bags/backpacks, not sets)")

        # 3. fetch each product page, parse spec
        bags = []
        seen = set()
        for pr in candidates:
            handle = pr["handle"]
            url = f"{BASE}/products/{handle}"
            try:
                resp = await page.goto(url, timeout=60000, wait_until="domcontentloaded")
                await page.wait_for_timeout(1500)
                if resp.status != 200:
                    print(f"  SKIP {handle}: HTTP {resp.status}")
                    continue
                html = await page.content()
            except Exception as e:
                print(f"  ERROR {handle}: {e!r:.120}")
                continue
            await page.wait_for_timeout(700)
            text = html_to_text(html)
            spec = parse_spec(text)
            if not spec:
                print(f"  NO SPEC {handle}: {pr['title'][:60]}")
                continue
            dims = sorted([spec["height"], spec["width"], spec["depth"]], reverse=True)
            cabin_marketed = bool(CABIN_MARKETING.search(pr["title"]))
            small_enough = dims[0] <= MAX_CABIN_HEIGHT_CM
            if not (cabin_marketed or small_enough):
                print(f"  EXCLUDE (checked/large) {pr['title'][:60]} dims={dims}")
                continue
            sku = ""
            if pr.get("variants"):
                sku = pr["variants"][0].get("sku", "")
            key = re.sub(r"[-_]?\d+$", "", sku) or re.sub(r"\s+", " ", pr["title"]).strip().lower()
            if key in seen:
                print(f"  DUPE {pr['title'][:60]} ({handle})")
                continue
            seen.add(key)
            img = ""
            if pr.get("images"):
                img = pr["images"][0]["src"]
            bag = {
                "name": pr["title"],
                "handle": handle,
                "sku": sku,
                "product_type": pr.get("product_type", ""),
                "url": url,
                "image_url": img,
                "height_cm": spec["height"],
                "width_cm": spec["width"],
                "depth_cm": spec["depth"],
                "expanded_depth_cm": spec.get("expanded_depth"),
                "weight_kg": spec.get("weight_kg"),
                "capacity_litres": spec.get("capacity_litres"),
                "dims_source": spec.get("dims_source"),
                "expanded_source": spec.get("expanded_source"),
                "weight_source": spec.get("weight_source"),
                "dims_include_wheels_handles": True,
                "cabin_marketed": cabin_marketed,
                "source": BASE,
                "fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
            }
            bags.append(bag)
            print(f"  OK {bag['name'][:58]:58s} {bag['height_cm']}x{bag['width_cm']}x{bag['depth_cm']}"
                  f" exp={bag['expanded_depth_cm']} w={bag['weight_kg']}")

        # 4. cross-check two bags against the US site (briggs-riley.com uses
        #    "Dimensions (Exterior): H x W x D in / H x W x D cm")
        US_DIM = re.compile(r"Dimensions \(Exterior\):\s*[\d.]+\s*(?:x|×)\s*[\d.]+\s*(?:x|×)\s*[\d.]+\s*in\s*/\s*"
                            r"(\d+(?:\.\d+)?)\s*(?:x|×)\s*(\d+(?:\.\d+)?)\s*(?:x|×)\s*(\d+(?:\.\d+)?)\s*cm", re.I)
        US_W = re.compile(r"Weight:\s*(?:[\d.]+\s*lbs?\s*/\s*)?(\d+(?:\.\d+)?)\s*kg", re.I)
        checked = 0
        us_products = {}
        try:
            d = await fetch_json(page, f"{US_BASE}/products.json?limit=250")
            for pr in d.get("products", []):
                us_products[pr["title"].lower()] = pr["handle"]
        except Exception as e:
            print(f"  US products.json failed: {e!r:.100}")
        for bag in bags:
            if checked >= 2:
                break
            us_handle = us_products.get(bag["name"].lower())
            if not us_handle:
                continue
            us_url = f"{US_BASE}/products/{us_handle}"
            try:
                resp = await page.goto(us_url, timeout=60000, wait_until="domcontentloaded")
                await page.wait_for_timeout(2000)
                if resp.status == 200:
                    utext = html_to_text(await page.content())
                    dm = US_DIM.search(utext)
                    wm = US_W.search(utext)
                    if dm:
                        dims = [float(dm.group(1)), float(dm.group(2)), float(dm.group(3))]
                        bag["us_cross_check"] = {
                            "url": us_url,
                            "dims_cm": dims,
                            "weight_kg": float(wm.group(1)) if wm else None,
                            "matches_uk": dims == [bag["height_cm"], bag["width_cm"], bag["depth_cm"]],
                        }
                        checked += 1
                        print(f"  US cross-check {bag['name'][:50]}: {dims} vs UK "
                              f"{[bag['height_cm'], bag['width_cm'], bag['depth_cm']]}")
            except Exception as e:
                print(f"  US cross-check failed for {bag['handle']}: {e!r:.100}")

        out = {
            "source": BASE,
            "cross_check_source": US_BASE,
            "fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
            "bag_count": len(bags),
            "bags": sorted(bags, key=lambda b: (b["height_cm"], b["width_cm"], b["depth_cm"]), reverse=True),
        }
        (DATA / "bags.json").write_text(json.dumps(out, indent=1, ensure_ascii=False), encoding="utf-8")
        print(f"\nwrote {len(bags)} bags to data/bags.json ({checked} US cross-checks)")
        await browser.close()


if __name__ == "__main__":
    asyncio.run(main())
