# -*- coding: utf-8 -*-
"""小闭环测试 v2：修复币种（i18n-prefs Cookie）+ 配送地显示。不写飞书。"""
import json, re, time, random
from playwright.sync_api import sync_playwright

SITES = {
    "UK": {
        "url": "https://www.amazon.co.uk/Auckly-Wireless-Electromagnetic-Automatic-Compatible/dp/B08GY1VLDK",
        "postcode": "SW1A 1AA",
        "locale": "en-GB", "tz": "Europe/London",
        "domain": ".amazon.co.uk", "currency": "GBP",
    },
    "DE": {
        "url": "https://www.amazon.de/dp/B08GY1VLDK",
        "postcode": "10115",
        "locale": "de-DE", "tz": "Europe/Berlin",
        "domain": ".amazon.de", "currency": "EUR",
    },
}

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36"

def txt(page, sel):
    try:
        el = page.locator(sel).first
        return el.inner_text(timeout=3000).strip() if el.count() else None
    except Exception:
        return None

def attr(page, sel, name):
    try:
        el = page.locator(sel).first
        return el.get_attribute(name, timeout=3000) if el.count() else None
    except Exception:
        return None

def set_delivery_location(page, postcode):
    try:
        page.click("#nav-global-location-popover-link", timeout=8000)
        page.wait_for_selector("#GLUXZipUpdateInput", state="visible", timeout=8000)
        page.fill("#GLUXZipUpdateInput", postcode)
        page.click("#GLUXZipUpdate", timeout=5000)
        try:
            page.wait_for_selector("#GLUXConfirmClose", state="visible", timeout=4000)
            page.click("#GLUXConfirmClose")
        except Exception:
            pass
        page.wait_for_load_state("domcontentloaded", timeout=15000)
        time.sleep(random.uniform(1.5, 2.5))
        return True
    except Exception:
        return False

def extract_fields(page):
    d = {}
    d["最终URL"] = page.url
    m = re.search(r"/dp/([A-Z0-9]{10})", page.url)
    d["实际ASIN"] = m.group(1) if m else None
    d["标题"] = txt(page, "#productTitle")
    price = txt(page, "#corePriceDisplay_div .a-price .a-offscreen") or txt(page, "#price_inside_buybox") or txt(page, "span.a-price .a-offscreen")
    d["展示价格"] = price
    d["币种"] = ("GBP £" if price and "£" in price else "EUR €" if price and "€" in price else (price or "")[:1])
    # 配送地：glow 区块第二行
    glow = txt(page, "#nav-global-location-popover-link") or ""
    d["配送地显示"] = " ".join(glow.split()) if glow else None
    d["综合评分"] = attr(page, "#acrPopover", "title") or txt(page, "span[data-hook='rating-out-of-text']")
    d["评分人数"] = txt(page, "#acrCustomerReviewText")
    d["可售状态"] = txt(page, "#availability")
    d["销售店铺"] = txt(page, "#sellerProfileTriggerId")
    bullets = txt(page, "#detailBulletsWrapper_feature_div") or txt(page, "#productDetails_detailBullets_sections1")
    if bullets:
        m = re.search(r"Best\s*Sellers?\s*Rank.{0,200}?#(\d[\d,]*)", bullets, re.S)
        d["BSR"] = ("#" + m.group(1)) if m else None
    d["副图数量(粗)"] = page.locator("#altImages img").count()
    body = page.content()[:4000].lower()
    d["疑似反爬"] = ("captcha" in body) or ("robot check" in body)
    return d

def run():
    results = {}
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True, args=["--no-sandbox", "--disable-dev-shm-usage"])
        for site, cfg in SITES.items():
            r = {"配置": {"邮编": cfg["postcode"], "强制币种": cfg["currency"]}}
            ctx = browser.new_context(
                user_agent=UA, locale=cfg["locale"], timezone_id=cfg["tz"],
                viewport={"width": 1366, "height": 768},
            )
            # 关键：先放币种偏好 Cookie，再访问
            ctx.add_cookies([
                {"name": "i18n-prefs", "value": cfg["currency"], "domain": cfg["domain"], "path": "/"},
            ])
            page = ctx.new_page()
            try:
                page.goto(cfg["url"], wait_until="domcontentloaded", timeout=45000)
                time.sleep(random.uniform(2, 3))
                if page.locator("#productTitle").count() == 0:
                    r["状态"] = "页面未加载出商品"
                    r["页头"] = txt(page, "title")
                    results[site] = r; ctx.close(); continue
                r["设邮编成功"] = set_delivery_location(page, cfg["postcode"])
                page.reload(wait_until="domcontentloaded", timeout=45000)
                time.sleep(random.uniform(2, 3.5))
                r.update(extract_fields(page))
                r["状态"] = "OK"
            except Exception as e:
                r["状态"] = f"异常: {e}"
            finally:
                results[site] = r; ctx.close()
            time.sleep(random.uniform(2, 4))
        browser.close()
    print(json.dumps(results, ensure_ascii=False, indent=2))

if __name__ == "__main__":
    run()
