"""iPad截图：中文+韩文日报，触发懒加载，全页截图"""
import asyncio
from playwright.async_api import async_playwright

URL_CN = "http://localhost:8082/daily-report.html?t=1"
URL_KO = "http://localhost:8082/ko-daily-report.html?t=1"
OUT_CN = "/data/news/cn-screenshot-ipad.png"
OUT_KO = "/data/news/ko-screenshot-ipad.png"

async def scroll_and_screenshot(page, url, output):
    print("  打开 %s ..." % url.split('/')[-1])
    await page.goto(url, wait_until='load', timeout=60000)
    
    # 等待初始渲染
    await asyncio.sleep(2)
    
    # 滚动触发懒加载（20次）
    print("  滚动懒加载...")
    total = await page.evaluate("document.body.scrollHeight")
    for i in range(1, 21):
        scroll_to = int((total / 20) * i)
        await page.evaluate("window.scrollTo(0, %d)" % scroll_to)
        await asyncio.sleep(0.2)
    
    # 滚回顶部
    await page.evaluate("window.scrollTo(0, 0)")
    
    # 等待资源加载完成
    await asyncio.sleep(4)
    
    # 检查图片是否全部加载
    incomplete = await page.evaluate("""() => {
        const imgs = document.querySelectorAll('img');
        let count = 0;
        imgs.forEach(i => { if (!i.complete) count++; });
        return count;
    }""")
    print("  未加载图片: %d 张" % incomplete)
    
    # 截图
    await page.screenshot(path=output, full_page=True)
    print("  ✅ 已保存 %s" % output)

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            args=['--no-sandbox', '--disable-setuid-sandbox']
        )
        context = await browser.new_context(
            viewport={"width": 768, "height": 1024},
            device_scale_factor=2,
            user_agent="Mozilla/5.0 (iPad; CPU OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1"
        )
        page = await context.new_page()
        
        # 中文版
        await scroll_and_screenshot(page, URL_CN, OUT_CN)
        
        # 韩文版
        await scroll_and_screenshot(page, URL_KO, OUT_KO)
        
        await browser.close()
        print("\n全部完成")

asyncio.run(main())
