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

SRC = r"D:\workbbbbbb\排班工具.html"
OUT = r"D:\workbbbbbb\build\_hm_e2e.html"
DOM = r"D:\workbbbbbb\build\_hm_dom.html"
TXT = r"D:\workbbbbbb\build\_hm_out.txt"

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 flush() { document.getElementById('E2E').textContent = out.join(' || '); }
  function run() {
    if (done) return; done = true;
    try {
      var st = window.__PB.state();
      push('people=' + st.people.length);
      push('before=' + st.people.map(function (p) { return (p.areas || []).length; }).join(','));
      window.__PB.reassignByHome();
      var a = st.people.map(function (p) { return (p.areas || []).length; });
      push('after=' + a.join(','));
      push('spread=' + (Math.max.apply(null, a) - Math.min.apply(null, a)));
      var used = {}, tot = 0;
      st.people.forEach(function (p) { (p.areas || []).forEach(function (x) { if (!used[x]) { used[x] = 1; tot++; } }); });
      push('covered=' + tot);
      push('manualAll=' + st.people.every(function (p) { return !p.manual; }));
      // 第一人详情：网点清单
      document.querySelector('[data-tab="v-people"]').click();
      var row = document.querySelector('#peopleList .row[data-pid]');
      if (row) row.click();
      var body = document.querySelector('[data-editor]');
      var txt = body ? body.textContent : '';
      push('hasOrgBlock=' + (txt.indexOf('个网点') >= 0));
      push('orgN=' + window.__PB.areaOrgsOf(st.people[0]).length);
      var m = txt.match(/·\s*([^\s·]+支行[^\s]*)/);
      push('sampleOrg=' + (m ? m[1] : 'none'));
      push('hasAddr=' + /区|县/.test(txt));
      push('listLen=' + txt.length);
      // 按住址距离函数
      push('h2a=' + window.__PB.homeToAreaDist(st.people[0], (st.people[0].areas || [''])[0]));
      // 联网核实（单点）
      window.__PB.netGeocode('桦枫居').then(function (g) {
        push('net=' + (g ? (g.lat.toFixed(4) + ',' + g.lng.toFixed(4) + ' ' + g.label) : 'null'));
      })['catch'](function (e) {
        push('netERR=' + e.message);
      }).then(function () {
        push('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
        flush();
        document.getElementById('E2E').setAttribute('data-final', '1');
      });
    } catch (e) { push('ERR ' + e.message); push('ERRS=skip'); flush(); }
  }
  if (document.readyState === 'complete') run(); else window.addEventListener('load', function () { setTimeout(run, 300); });
  setTimeout(function () { if (!done) { 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] + 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/e2eHM%d' % (int(time.time()) % 100000)
    r = subprocess.run([edge, '--headless=new', '--disable-gpu', '--user-data-dir=' + prof,
                        '--virtual-time-budget=16000', '--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()
