"""Diagnostic script: navigate to a Zhihu question, fill + submit an answer,
take screenshots at key steps, and upload them to Slack.

Usage:
    python scripts/zhihu_debug_publish.py \
        --url "https://www.zhihu.com/question/1992659642908702603"
"""

import sys
import os
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from health.utils.env_loader import load_env_with_extras
load_env_with_extras()

import click
from slack_sdk import WebClient
from playwright.sync_api import sync_playwright
from playwright_stealth import Stealth

STATE_FILE = Path(__file__).resolve().parents[1].parent / "data" / "zhihu_state.json"
SCREENSHOT_DIR = Path("/tmp/zhihu_debug")
SCREENSHOT_DIR.mkdir(exist_ok=True)

DUMMY_TEXT = "这是一段测试文字，用于诊断知乎发布流程是否正常。请勿实际发布。"


def upload(client: WebClient, channel: str, path: Path, comment: str) -> None:
    with path.open("rb") as f:
        client.files_upload_v2(
            channel=channel,
            file=f,
            filename=path.name,
            initial_comment=comment,
        )
    print(f"Uploaded: {path.name}")


@click.command()
@click.option("--url", required=True, help="Zhihu question URL to test")
@click.option("--submit", is_flag=True, default=False, help="Actually click 发布 (default: dry run, no submit)")
def main(url: str, submit: bool) -> None:
    token = os.environ.get("OBSIDIAN_SLACK_BOT_TOKEN")
    channel = os.environ.get("ZHIHU_NOTIFY_CHANNEL", "")
    client = WebClient(token=token)

    import json
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(
            viewport={"width": 1280, "height": 800},
            user_agent=(
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/122.0.0.0 Safari/537.36"
            ),
        )

        # Load session
        if STATE_FILE.exists():
            data = json.loads(STATE_FILE.read_text())
            context.add_cookies(data.get("cookies", []))
            print(f"Loaded {len(data.get('cookies', []))} cookies")
        else:
            print("WARNING: no state file found, not logged in")

        page = context.new_page()
        Stealth().apply_stealth_sync(page)

        # ── Step 1: navigate ──────────────────────────────────────────────────
        print(f"Navigating to: {url}")
        page.goto(url, wait_until="domcontentloaded", timeout=30000)
        page.wait_for_timeout(3000)

        s1 = SCREENSHOT_DIR / "1_after_navigate.png"
        page.screenshot(path=str(s1), full_page=False)
        upload(client, channel, s1, f"📸 Step 1: after navigation to question page (login={page.url})")

        # ── Step 2: scroll + find 写回答 button ──────────────────────────────
        page.evaluate("window.scrollBy(0, 400)")
        page.wait_for_timeout(800)

        # Log all buttons
        texts = page.evaluate("""
            () => Array.from(document.querySelectorAll('button, a, [role="button"]'))
                       .map(e => e.textContent.trim())
                       .filter(t => t.length > 0 && t.length < 30)
        """)
        print(f"Buttons/links on page: {texts[:40]}")
        client.chat_postMessage(channel=channel, text=f"🔍 页面按钮列表：`{texts[:40]}`")

        # Try click
        clicked = page.evaluate("""
            () => {
                const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
                let node;
                while ((node = walker.nextNode())) {
                    const t = node.textContent.trim();
                    if (['写回答','回答问题','回答','发起回答'].includes(t)) {
                        const el = node.parentElement;
                        const btn = el.closest('button, a, [role="button"]') || el;
                        btn.click();
                        return t;
                    }
                }
                return null;
            }
        """)
        print(f"Clicked '写回答' text: {clicked!r}")
        if not clicked:
            s_err = SCREENSHOT_DIR / "2_no_write_button.png"
            page.screenshot(path=str(s_err))
            upload(client, channel, s_err, "❌ Step 2: 未找到写回答按钮，截图如下")
            browser.close()
            return

        page.wait_for_timeout(2000)
        s2 = SCREENSHOT_DIR / "2_after_click_write.png"
        page.screenshot(path=str(s2), full_page=False)
        upload(client, channel, s2, f"📸 Step 2: after clicking '{clicked}' — editor should be visible")

        # ── Step 3: fill editor ───────────────────────────────────────────────
        editor_sels = [
            ".DraftEditor-content[contenteditable='true']",
            ".RichText [contenteditable='true']",
            "[contenteditable='true'].public-DraftEditor-content",
        ]
        editor = None
        for sel in editor_sels:
            try:
                page.wait_for_selector(sel, timeout=5000)
                editor = page.locator(sel).first
                print(f"Found editor via: {sel}")
                break
            except Exception:
                continue

        if editor is None:
            s_err2 = SCREENSHOT_DIR / "3_no_editor.png"
            page.screenshot(path=str(s_err2))
            upload(client, channel, s_err2, "❌ Step 3: 未找到编辑器，截图如下")
            browser.close()
            return

        editor.click()
        page.wait_for_timeout(400)
        page.evaluate(
            """(text) => {
                const ed = document.querySelector(
                    '.DraftEditor-content[contenteditable="true"],'
                    + '.RichText [contenteditable="true"],'
                    + '[contenteditable="true"].public-DraftEditor-content'
                );
                if (ed) { ed.focus(); document.execCommand('insertText', false, text); }
            }""",
            DUMMY_TEXT,
        )
        page.wait_for_timeout(600)

        content_len = page.evaluate("""
            () => {
                const ed = document.querySelector('[contenteditable="true"]');
                return ed ? ed.textContent.length : 0;
            }
        """)
        print(f"Editor content length after fill: {content_len}")

        s3 = SCREENSHOT_DIR / "3_after_fill.png"
        page.screenshot(path=str(s3), full_page=False)
        upload(client, channel, s3, f"📸 Step 3: after filling editor ({content_len} chars)")

        if not submit:
            print("Dry run — not clicking 发布. Pass --submit to actually submit.")
            client.chat_postMessage(channel=channel, text="ℹ️ 诊断完成（dry run，未点击发布）")
            browser.close()
            return

        # ── Step 4: click 发布 ────────────────────────────────────────────────
        publish_sels = [
            "button:has-text('发布回答')",
            ".AnswerForm button:has-text('发布')",
            ".AnswerForm button:has-text('提交')",
            "button:has-text('发布')",
            "button:has-text('提交')",
            "button.SubmitAnswer",
            "[data-za-element-name='SubmitAnswer']",
        ]
        published = False
        matched_sel = None
        for sel in publish_sels:
            try:
                btn = page.locator(sel).first
                btn.wait_for(state="visible", timeout=3000)
                btn.click()
                published = True
                matched_sel = sel
                print(f"Clicked 发布 via: {sel}")
                break
            except Exception:
                continue

        if not published:
            s_err3 = SCREENSHOT_DIR / "4_no_publish_btn.png"
            page.screenshot(path=str(s_err3))
            upload(client, channel, s_err3, "❌ Step 4: 未找到发布按钮，截图如下")
            browser.close()
            return

        # Wait and screenshot multiple times to catch any dialog
        for i, delay in enumerate([1000, 2000, 3000], start=1):
            page.wait_for_timeout(delay)
            # Log buttons at this moment
            btns_now = page.evaluate("""
                () => Array.from(document.querySelectorAll('button, a[role="button"]'))
                           .map(e => e.textContent.trim())
                           .filter(t => t.length > 0 && t.length < 30)
            """)
            print(f"+{i}s buttons: {btns_now[:20]}")
            s = SCREENSHOT_DIR / f"4_{i}s_after_publish.png"
            page.screenshot(path=str(s), full_page=False)
            upload(client, channel, s, f"📸 Step 4 (+{i}s after 发布 click): url={page.url}")

        print(f"Final URL: {page.url}")
        browser.close()


if __name__ == "__main__":
    main()
