from playwright.sync_api import sync_playwright
import time, traceback

URL = "https://creator.xiaohongshu.com/publish/publish"

def click_tab_js(page, tab_text: str) -> bool:
    # 直接在页面里找“上传图文/上传视频”的 tab 容器并 JS 点击
    # 你的报错里显示可点击容器 class=creator-tab
    script = """
(t) => {
  const titles = Array.from(document.querySelectorAll("span.title"));
  const hit = titles.find(x => (x.textContent || "").trim() === t);
  if (!hit) return {ok:false, reason:"no-span-title"};
  // 向上找 creator-tab 容器
  const tab = hit.closest(".creator-tab") || hit.parentElement;
  if (!tab) return {ok:false, reason:"no-closest-tab"};
  tab.click();               // JS click: 不受 viewport 限制
  return {ok:true, reason:"clicked"};
}
"""
    res = page.evaluate(script, tab_text)
    print("JS_CLICK_RES =", res)
    return bool(res.get("ok"))

def dump_accepts(page):
    accepts = page.eval_on_selector_all(
        "input[type=file]",
        "els => els.map(e => e.getAttribute('accept'))"
    )
    print("FILE_INPUT_ACCEPTS =", accepts)

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    context = browser.new_context(storage_state="xhs_state.json")
    page = context.new_page()

    try:
        page.goto(URL, wait_until="domcontentloaded")
        page.wait_for_timeout(4000)

        # 先点“上传图文”
        ok = click_tab_js(page, "上传图文")
        page.wait_for_timeout(1500)

        # 验证：如果还是视频页，你会看到 accept 只有 mp4/mov
        dump_accepts(page)

        # 再补一刀：如果还没切过去，再点一次（有时第一次没触发）
        if not ok:
            print("第一次未点到，重试一次…")
            ok = click_tab_js(page, "上传图文")
            page.wait_for_timeout(1500)
            dump_accepts(page)

        print("如果切成功：页面顶部应高亮“上传图文”，accept 里应出现 jpg/png 等")

    except Exception as e:
        print("ERROR:", e)
        traceback.print_exc()

    input("按回车关闭浏览器...")
    browser.close()
