# -*- coding: utf-8 -*-
"""调试 GLUX 邮编弹窗：_dump 弹窗控件状态、错误信息、提交后的 glow 文本"""
import re, time, json
from playwright.sync_api import sync_playwright

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 dump(page, tag):
    print(f"===== {tag} =====")
    for sel in ["#GLUXZipUpdateInput", "#GLUXZipUpdate", "#GLUXZipError", "#GLUXConfirmClose",
                "#glow-ingress-blockLine2", "#nav-global-location-popover-link",
                "#GLUXLaneRefreshButton", ".a-popover-inner"]:
        try:
            el = page.locator(sel).first
            if el.count():
                t = el.inner_text(timeout=2000).strip().replace("\n", " | ")[:200]
                vis = el.is_visible()
                print(f"{sel}: visible={vis} text='{t}'")
        except Exception as e:
            print(f"{sel}: ERR {type(e).__name__}")

def run(url, domain, cur, zip_, locale, tz):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True, args=["--no-sandbox", "--disable-dev-shm-usage"])
        ctx = browser.new_context(user_agent=UA, locale=locale, timezone_id=tz,
                                  viewport={"width": 1366, "height": 768})
        ctx.add_cookies([{"name": "i18n-prefs", "value": cur, "domain": domain, "path": "/"}])
        page = ctx.new_page()
        page.goto(url, wait_until="domcontentloaded", timeout=45000)
        time.sleep(2)
        dump(page, "初始状态")
        print(">>> 点击 glow 入口")
        page.click("#nav-global-location-popover-link", timeout=8000)
        page.wait_for_selector("#GLUXZipUpdateInput", state="visible", timeout=8000)
        time.sleep(1)
        dump(page, "弹窗打开后")
        cur_val = page.locator("#GLUXZipUpdateInput").input_value()
        print(f"邮编输入框当前值: '{cur_val}'")
        page.fill("#GLUXZipUpdateInput", zip_)
        print(f"已填入: '{zip_}'，尝试多种提交方式")
        # 方式1: 点 apply
        try:
            page.click("#GLUXZipUpdate", timeout=3000, force=True)
            print("点了 #GLUXZipUpdate")
        except Exception as e:
            print(f"点 #GLUXZipUpdate 失败: {type(e).__name__}")
        time.sleep(4)
        dump(page, "apply 后 4s")
        # 如有确认按钮点掉
        for csel in ["#GLUXConfirmClose", "input[name='glowDone']", "#GLUXChooseAddress"]:
            try:
                el = page.locator(csel).first
                if el.count() and el.is_visible():
                    el.click(timeout=2000)
                    print(f"点了确认 {csel}")
                    time.sleep(3)
            except Exception:
                pass
        dump(page, "确认后")
        # 看页面是否刷新
        time.sleep(3)
        page.reload(wait_until="domcontentloaded", timeout=30000)
        time.sleep(2)
        dump(page, "reload 后")
        browser.close()

if __name__ == "__main__":
    import sys
    site = sys.argv[1] if len(sys.argv) > 1 else "DE"
    if site == "DE":
        run("https://www.amazon.de/dp/B08GY1VLDK", ".amazon.de", "EUR", "10115", "de-DE", "Europe/Berlin")
    else:
        run("https://www.amazon.co.uk/Auckly-Wireless-Electromagnetic-Automatic-Compatible/dp/B08GY1VLDK", ".amazon.co.uk", "GBP", "SW1A 1AA", "en-GB", "Europe/London")
