"""
练习 04: 用 Playwright 监听响应。

前置:
1. 你已经会用 `02_persistent_context.py` 启动带用户目录的浏览器
2. 最好先手动完成一次抖音登录
3. 打开一个抖音博主主页，或者让脚本自己打开

目标:
1. 学会 `page.on("response", callback)`
2. 学会筛选你关心的接口 URL
3. 打印响应状态码和 URL
4. 尝试读取 JSON 响应体

建议:
- 第一版先只打印 URL，别急着做完整解析
- 如果没看到目标接口，手动滚动页面触发加载
- 你也可以对比试一下 `page.expect_response(...)` 的写法

运行:
    ./.venv/bin/python learning/playwright_basics/04_listen_response.py
"""

from __future__ import annotations

import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from Douyin import DEFAULT_USER_URL

USER_DATA_DIR = PROJECT_ROOT / ".playwright-douyin-profile"
LISTEN_TARGET = "web/aweme/post/"


def is_target_response_url(url: str) -> bool:
    return LISTEN_TARGET in url


def try_read_json_payload(response):
    try:
        payload = response.json()
    except Exception:
        return None
    return payload if isinstance(payload, dict) else None


def main() -> None:
    from playwright.sync_api import sync_playwright

    def on_response(response) -> None:
        if not is_target_response_url(response.url):
            return

        print(f"[INFO] 命中目标响应: {response.status} {response.url}")
        payload = try_read_json_payload(response)
        if payload is None:
            print("[WARN] 这个响应不是可直接读取的 JSON 字典。")
            return

        print(f"[INFO] JSON keys: {list(payload.keys())[:10]}")

    with sync_playwright() as playwright:
        context = playwright.chromium.launch_persistent_context(
            user_data_dir=str(USER_DATA_DIR),
            headless=False,
        )
        page = context.pages[0] if context.pages else context.new_page()
        page.on("response", on_response)
        page.goto(DEFAULT_USER_URL)
        print(f"[INFO] 当前 URL: {page.url}")
        print("[INFO] 已开始监听响应。请在页面中滚动一下，观察是否出现目标接口。")
        input("观察输出后按回车退出...")
        context.close()


if __name__ == "__main__":
    main()
