#!/usr/bin/python3.12
"""每日截图脚本 - 被 daily_report_auto.sh 调用"""
import sys, os
from playwright.sync_api import sync_playwright

CN_URL = "http://localhost:8082/daily-report.html"
KO_URL = "http://localhost:8082/ko-daily-report.html"
CN_OUT = "/data/news/cn-screenshot-ipad.png"
KO_OUT = "/data/news/ko-screenshot-ipad.png"
CHROME = "/home/ubuntu/.cache/ms-playwright/chromium-1217/chrome-linux64/chrome"

def snap(url, out, label):
    print(f"[{label}] 开始截图...")
    with sync_playwright() as p:
        b = p.chromium.launch(headless=True, executable_path=CHROME)
        ctx = b.new_context(viewport={"width":768,"height":1024}, device_scale_factor=2,
            user_agent="Mozilla/5.0 (iPad; CPU OS 16_0 like Mac OS X) AppleWebKit/605.1.15")
        pg = ctx.new_page()
        pg.goto(url, wait_until="load", timeout=60000)
        pg.wait_for_timeout(2000)
        total = pg.evaluate("document.body.scrollHeight")
        for i in range(1, 21):
            pg.evaluate(f"window.scrollTo(0, ({total}/20)*{i})")
            pg.wait_for_timeout(200)
        pg.evaluate("window.scrollTo(0,0)")
        pg.wait_for_timeout(5000)
        missing = pg.evaluate("() => Array.from(document.querySelectorAll('img')).filter(i => !i.complete).length")
        print(f"  未加载图片: {missing}")
        pg.screenshot(path=out, full_page=True)
        sz = os.path.getsize(out)//1024
        print(f"  已保存: {out} ({sz}KB)")
        b.close()

snap(CN_URL, CN_OUT, "中文")
snap(KO_URL, KO_OUT, "韩文")
print("全部截图完成")
