#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""定点截图：用负 body margin 把目标区块顶到视口顶部，Chrome headless 视口截图。
沙盒场景可先注入点击脚本走完对话，再做截图。"""
import io
import json
import os
import subprocess
import sys

W = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
SRC = os.path.join(W, '培训与上手', '培训', '价格谈判培训_攻心为上.html')
OUT = os.path.join(W, '培训与上手', '培训', '_shots_price')
TMP = '/tmp/_shotbuild'
CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
os.makedirs(OUT, exist_ok=True)
os.makedirs(TMP, exist_ok=True)

html = io.open(SRC, encoding='utf-8').read()
geom = json.load(io.open('/tmp/_price_geom.json'))
assert html.count('</head>') == 1 and html.count('</body>') == 1


def render(top, h, name, click_js=''):
    H = min(h + 44, 2600)
    inject = ('<style>html{overflow:hidden !important}'
              'body{margin-top:-%dpx !important}</style>' % top)
    doc = html.replace('</head>', inject + '</head>', 1)
    if click_js:
        doc = doc.replace('</body>', '<script>window.addEventListener("load",function(){%s});</script></body>'
                          % click_js, 1)
    tmp = os.path.join(TMP, name.replace('.png', '.html'))
    io.open(tmp, 'w', encoding='utf-8').write(doc)
    png = os.path.join(OUT, name)
    cmd = [CHROME, '--headless=new', '--disable-gpu', '--no-sandbox', '--hide-scrollbars',
           '--force-device-scale-factor=1', '--window-size=1500,%d' % H,
           '--virtual-time-budget=4000', '--screenshot=' + png,
           'file://' + tmp]
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    ok = os.path.exists(png) and os.path.getsize(png) > 5000
    print('  %-46s 1500x%-5d %s %dKB' % (name, H, 'OK ' if ok else 'FAIL',
                                        (os.path.getsize(png) // 1024) if os.path.exists(png) else 0))
    if not ok:
        print('     stderr:', (r.stderr or '')[-300:])
    return ok


SB1_DONE = ('document.querySelectorAll("#sb-tabs .sb-tab")[0].click();'
            'setTimeout(function(){for(var i=0;i<3;i++){var o=document.querySelectorAll("#sb-stage .opt");'
            'if(o.length)o[1].click();}},60);')
SB3_DONE = ('document.querySelectorAll("#sb-tabs .sb-tab")[2].click();'
            'setTimeout(function(){var ks=[1,2,1];var i=0;var t=setInterval(function(){'
            'var o=document.querySelectorAll("#sb-stage .opt");'
            'if(o.length){o[Math.min(ks[i],o.length-1)].click();i++;}'
            'if(i>=3){clearInterval(t);}},70);},60);')

jobs = [
    ('s0', '01_开篇_为什么谈判决定单子成败.png', ''),
    ('s1', '02_第1章_需求探询.png', ''),
    ('s2', '03_第2章_上桌三条件.png', ''),
    ('s3', '04_第3章_开价与让步.png', ''),
    ('s4', '05_第4章_探寻底价.png', ''),
    ('s5', '06_第5章_异议处理.png', ''),
    ('s6', '07_沙盒_对话演练_初始.png', ''),
    ('s6', '08_沙盒_选错也有反馈.png', SB1_DONE),
    ('s6', '08b_沙盒_场景3走完.png', SB3_DONE),
    ('s7', '09_速查卡.png', ''),
    ('s8', '10_自检清单.png', ''),
    ('s9', '11_附录_出处.png', ''),
]
ok = 0
for sid, nm, cjs in jobs:
    g = geom[sid]
    if render(g['top'], g['h'], nm, cjs):
        ok += 1
print('DONE %d/%d' % (ok, len(jobs)))
