# -*- coding: utf-8 -*-
"""按站点管理独立持久浏览器（launch_persistent_context）。
- 每站点一个 user_data_dir：收货邮编/币种偏好/会话跨轮次保留，设一次长期有效
- ensure_location(): 验证 glow 邮编，失效才重设。
  实测结论（diag3）：Enter/按钮提交后 glow 不自动刷新，必须 reload 页面才显示新位置。
"""
import re, time
import os
from playwright.sync_api import sync_playwright, BrowserContext
from sites import SITE_CONFIGS, UA

class SiteBrowsers:
    """一次巡检_round的生命周期内持有；按需惰性启动，结束时统一关闭。"""
    def __init__(self):
        self._pw = None
        self._contexts = {}

    def _start_pw(self):
        if self._pw is None:
            self._pw = sync_playwright().start()
        return self._pw

    def get(self, site: str) -> BrowserContext:
        if site not in SITE_CONFIGS:
            raise KeyError(f"未知站点 {site}")
        if site not in self._contexts:
            cfg = SITE_CONFIGS[site]
            os.makedirs(cfg["profile_dir"], exist_ok=True)
            ctx = self._start_pw().chromium.launch_persistent_context(
                cfg["profile_dir"],
                headless=True,
                user_agent=UA,
                locale=cfg["locale"],
                timezone_id=cfg["timezone"],
                viewport={"width": 1366, "height": 768},
                args=["--no-sandbox", "--disable-dev-shm-usage"],
            )
            ctx.add_cookies([{"name": "i18n-prefs", "value": cfg["currency"],
                              "domain": cfg["domain"], "path": "/"}])
            self._contexts[site] = ctx
        return self._contexts[site]

    def close(self):
        for ctx in self._contexts.values():
            try: ctx.close()
            except Exception: pass
        self._contexts.clear()
        if self._pw:
            try: self._pw.stop()
            except Exception: pass
            self._pw = None


def glow_text(page) -> str:
    try:
        el = page.locator("#nav-global-location-popover-link").first
        return " ".join(el.inner_text(timeout=2000).split()) if el.count() else ""
    except Exception:
        return ""

def location_ok(site, glow) -> bool:
    digits = re.sub(r"\D", "", SITE_CONFIGS[site]["postcode"])
    return digits in re.sub(r"\D", "", glow or "")

def ensure_location(page, site, max_retry=2, log=None):
    """打开商品页后调用：验证邮编，未生效则重设（Enter 提交 → 按钮兜底 → reload 验证）。"""
    def P(*a):
        if log: print(*a)
    cfg = SITE_CONFIGS[site]
    g = glow_text(page)
    if location_ok(site, g):
        P(f"[{site}] 邮编已生效(免设): {g}")
        return True, g
    for attempt in range(1, max_retry + 1):
        try:
            P(f"[{site}] 邮编尝试{attempt}: 打开弹窗")
            page.click("#nav-global-location-popover-link", timeout=8000)
            page.wait_for_selector("#GLUXZipUpdateInput", state="visible", timeout=8000)
            time.sleep(1)
            page.fill("#GLUXZipUpdateInput", cfg["postcode"])
            page.press("#GLUXZipUpdateInput", "Enter")
            time.sleep(2)
            try:  # 兜底：弹窗若还开着就点按钮
                btn = page.locator("#GLUXZipUpdate")
                if btn.count() and btn.first.is_visible():
                    btn.first.click(timeout=3000, force=True)
                    P(f"[{site}] 追加按钮点击")
            except Exception:
                pass
            time.sleep(3)
            P(f"[{site}] reload 验证")
            page.reload(wait_until="domcontentloaded", timeout=45000)
            time.sleep(3)
            g = glow_text(page)
            if location_ok(site, g):
                P(f"[{site}] 邮编生效: {g}")
                return True, g
            P(f"[{site}] 未生效: {g}")
        except Exception as e:
            P(f"[{site}] 尝试{attempt}异常: {type(e).__name__}")
            try: page.keyboard.press("Escape")
            except Exception: pass
    return False, glow_text(page)
