# -*- coding: utf-8 -*-
"""Patchright + ungoogled-chromium 136 真浏览器跑 Google Lens 流程。

替代 lens_pure_http.py（纯 HTTP 已被 Google 风控识破）。
接口与 lens_pure_http.google_lens_search 完全一致。
"""
import os
import sys
import time
import json
import re
from urllib.parse import urlparse, parse_qs

sys.path.append(os.path.dirname(sys.path[0]))
from patchright.sync_api import sync_playwright

# 复用纯 HTTP 版的 HTML 解析（已稳定）
from amazon_spider.lens_pure_http import parse_visual_matches, parse_ai_overview

CHROME_EXEC = os.environ.get(
    "LENS_CHROME_PATH",
    r"D:\新建文件夹\指纹浏览器\ungoogled-chromium_136.0.7103.113-1.1_windows_x64\chrome.exe",
)
USER_DATA_DIR = os.environ.get(
    "LENS_USER_DATA_DIR",
    r"D:\新建文件夹\指纹浏览器\lens_profile",
)
LENS_HOME = "https://lens.google.com/"
EI_RE = re.compile(r"""kEI\s*[:=]\s*['"]([A-Za-z0-9_-]{8,})['"]""")


def google_lens_search(image_path, hl="zh-CN"):
    if not os.path.exists(image_path):
        raise FileNotFoundError(image_path)
    if not os.path.exists(CHROME_EXEC):
        raise FileNotFoundError(f"chrome.exe 未找到: {CHROME_EXEC}")
    os.makedirs(USER_DATA_DIR, exist_ok=True)

    html = ""
    url = ""
    with sync_playwright() as p:
        context = p.chromium.launch_persistent_context(
            user_data_dir=USER_DATA_DIR,
            executable_path=CHROME_EXEC,
            headless=False,
            viewport={"width": 1366, "height": 768},
            locale="zh-CN",
            timezone_id="Asia/Shanghai",
            args=["--no-default-browser-check", "--no-first-run"],
        )
        page = context.pages[0] if context.pages else context.new_page()
        try:
            print(f"[1/3] open lens.google.com ...")
            page.goto(LENS_HOME, wait_until="domcontentloaded", timeout=30000)

            print(f"[2/3] upload {os.path.basename(image_path)} ...")
            # 页面有多个 input[type=file]，必须用 name=encoded_image 的那个才是 lens 上传入口
            file_input = page.locator('input[name="encoded_image"]')
            file_input.set_input_files(image_path)

            print(f"[3/3] wait for /search?vsrid=... + ei ...")
            try:
                page.wait_for_url(re.compile(r"google\.com/search\?"), timeout=45000)
                page.wait_for_function(
                    """() => /kEI\\s*[:=]\\s*['"][A-Za-z0-9_-]{8,}['"]/.test(document.documentElement.outerHTML)""",
                    timeout=30000,
                )
                time.sleep(3)
            except Exception as e:
                print(f"      [⚠️ timeout] current url: {page.url}")
                err_dump_dir = r"D:\新建文件夹\html_selenium_files"
                if os.path.isdir(err_dump_dir):
                    ts = int(time.time())
                    page.screenshot(path=os.path.join(err_dump_dir, f"patchright_err_{ts}.png"), full_page=True)
                    with open(os.path.join(err_dump_dir, f"patchright_err_{ts}.html"), "w", encoding="utf-8") as f:
                        f.write(page.content())
                    print(f"      [dump] patchright_err_{ts}.png/.html saved")
                raise

            html = page.content()
            url = page.url
        finally:
            context.close()

    dump_dir = r"D:\新建文件夹\html_selenium_files"
    if os.path.isdir(dump_dir):
        ts = int(time.time())
        with open(os.path.join(dump_dir, f"patchright_search_{ts}.html"), "w", encoding="utf-8") as f:
            f.write(html)
        print(f"      [dump] patchright_search_{ts}.html ({len(html)}b)")

    ei = (EI_RE.search(html) or [None, ""])[1]
    vsrid = (parse_qs(urlparse(url).query).get("vsrid") or [""])[0]
    matches = parse_visual_matches(html)
    ai_overview = parse_ai_overview(html)

    return {
        "result_url": url, "vsrid": vsrid, "ei": ei,
        "sca_esv": "", "mlro": "", "mlros": "", "mrc": "",
        "folsrch_status": 200, "folsrch_html_len": 0,
        "ai_overview": ai_overview, "visual_matches": matches,
        "folsrch_html": "",
    }


if __name__ == "__main__":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
    except Exception:
        pass
    img = sys.argv[1] if len(sys.argv) > 1 else r"C:\Users\ASUS\Downloads\snipaste20260522_104715.png"
    out = google_lens_search(img)
    print("===")
    ai = out.get('ai_overview') or {}
    if isinstance(ai, dict) and ai.get('available'):
        print(f"AI 概览摘要: {ai.get('summary','')[:400]}")
        for b in ai.get('bullets', [])[:6]:
            print(f"  • {b[:200]}")
    else:
        src = ai.get('source', '?') if isinstance(ai, dict) else 'na'
        print(f"AI 概览: (Google 未生成) [source={src}]")
    print(f"visual_matches count: {len(out['visual_matches'])}")
    for m in out["visual_matches"][:15]:
        print(" -", m["title"][:80], "|", m["url"][:80])
    dbg = os.path.join(os.path.dirname(__file__), "lens_patchright_result.json")
    with open(dbg, "w", encoding="utf-8") as f:
        json.dump({k: v for k, v in out.items() if k != "folsrch_html"}, f, ensure_ascii=False, indent=2)
    print("saved:", dbg)
