# -*- coding: utf-8 -*-
import io, os, subprocess, time, html as H

SRC = r"D:\workbbbbbb\排班工具.html"
OUT = r"D:\workbbbbbb\build\_ls_e2e.html"
DOM = r"D:\workbbbbbb\build\_ls_dom.html"
TXT = r"D:\workbbbbbb\build\_ls_out.txt"

STUB = ('<script>(function(){try{Storage.prototype.setItem=function(){'
        'throw new DOMException("denied","SecurityError");};}catch(e){}})();</script>')
ERRTRAP = '<script>window.__ERRS=[];window.addEventListener("error",function(e){window.__ERRS.push((e.message||"")+" @"+e.lineno);});</script>'

TEST = r"""
<div id="E2E">PENDING</div>
<script>
(function () {
  var out = [], done = false;
  function push(s) { out.push(s); }
  function run() {
    if (done) return; done = true;
    try {
      var w = document.getElementById('lsWarn');
      push('warnShown=' + (w ? (w.style.display !== 'none') : 'none'));
      push('warnText=' + (w ? w.textContent.replace(/\s+/g, ' ').slice(0, 80) : ''));
      push('why=' + (document.getElementById('lsWarnWhy') || {}).textContent);
      push('hint=' + (document.getElementById('saveHint') || {}).textContent);
      push('hintCls=' + (document.getElementById('saveHint') || {}).className);
      push('lsOk=' + window.__PB.ls().ok + '/' + window.__PB.ls().why);
      push('exportBtn=' + !!document.getElementById('btnLsExport'));
      // 改状态，触发 save()，不能抛错
      var p0 = window.__PB.state().people[0].n;
      document.querySelector('[data-tab="v-people"]').click();
      var row = document.querySelector('#peopleList .row[data-pid]');
      if (row) row.click();
      var chip = document.querySelector('#peopleList [data-pstat="外勤"]');
      push('chipFound=' + !!chip);
      if (chip) chip.click();
      push('statusNow=' + window.__PB.state().people[0].status);
      push('hintAfter=' + (document.getElementById('saveHint') || {}).textContent);
      push('peopleRows=' + window.__PB.peopleRows().length);
      push('buildXlsxLen=' + (window.__PB.buildXlsx(window.__PB.peopleRows()).length ? 'ok' : '0'));
      push('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
    } catch (e) { push('ERR ' + e.message); }
    document.getElementById('E2E').textContent = out.join(' || ');
  }
  if (document.readyState === 'complete') run(); else window.addEventListener('load', function () { setTimeout(run, 300); });
  setTimeout(run, 4000);
})();
</script>
"""


def main():
    with io.open(SRC, encoding='utf-8') as f:
        h = f.read()
    i = h.find('<script>window.__PAIBAN_DATA__')
    h = h[:i] + STUB + ERRTRAP + h[i:]
    e = h.rfind('</body>')
    h = h[:e] + TEST + h[e:]
    with io.open(OUT, 'w', encoding='utf-8') as f:
        f.write(h)
    print('built', os.path.getsize(OUT))

    edge = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
    subprocess.run(['taskkill', '/F', '/IM', 'msedge.exe'], capture_output=True)
    time.sleep(2)
    prof = 'C:/Windows/Temp/e2eLS%d' % (int(time.time()) % 100000)
    r = subprocess.run([edge, '--headless=new', '--disable-gpu', '--user-data-dir=' + prof,
                        '--virtual-time-budget=9000', '--dump-dom', OUT], capture_output=True)
    with io.open(DOM, 'wb') as f:
        f.write(r.stdout)
    print('dom', len(r.stdout))

    with io.open(DOM, encoding='utf-8', errors='replace') as f:
        s = f.read()
    k = s.find('id="E2E"')
    if k < 0:
        txt = 'NO_E2E dom=%d' % len(s)
    else:
        b = s.find('>', k) + 1
        e2 = s.find('</div>', b)
        txt = H.unescape(s[b:e2]).strip()
    with io.open(TXT, 'w', encoding='utf-8') as f:
        f.write(txt)
    print('extracted', len(txt))


main()
