# -*- coding: utf-8 -*-
"""校验住址/辖区同步：跑无头 Edge 读 people 的 district/autoArea，再点自动认领看覆盖。"""
import io, os, sys, subprocess, time, html as H
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
BASE = r"D:\workbbbbbb"
OUT = os.path.join(BASE, "排班工具.html")
B = os.path.join(BASE, "build")

ERRTRAP = '<script>window.__ERRS=[];window.addEventListener("error",function(e){window.__ERRS.push((e.message||"")+" @line"+e.lineno);});</script>'
TEST = r'''
<script>
(function(){
  function run(){
    if (window.__done) return; window.__done = 1;
    var out = [], PB = window.__PB;
    function push(s){ out.push(s); }
    try {
      var st = PB.state();
      push('peopleN=' + st.people.length);
      st.people.forEach(function(p){
        push('P ' + p.n + ' | ' + p.home + ' | ' + (p.district||'-') + ' | auto=' + (p.autoArea||'-') + ' | areas=' + (p.areas||[]).join('/') + ' | manual=' + !!p.manual);
      });
      var btn = document.getElementById('btnAutoArea');
      if (btn) btn.click();
      var st2 = PB.state();
      var cnt = {}, tot = 0, per = [];
      st2.people.forEach(function(p){
        var a = p.areas || [];
        per.push(a.length);
        a.forEach(function(x){ cnt[x] = (cnt[x]||0)+1; tot++; });
      });
      push('afterAuto perCounts=' + per.join(','));
      push('covered=' + Object.keys(cnt).length + ' total=' + tot);
      var miss = st2.areas.filter(function(x){ return (x.r2.indexOf('富阳')<0 && x.r2.indexOf('临安')<0 && x.r2.indexOf('建德')<0 && x.r2.indexOf('桐庐')<0 && x.r2.indexOf('淳安')<0 && x.r2.indexOf('上海')<0) && !cnt[x.r2]; }).map(function(x){return x.r2;});
      push('missN=' + miss.length + '(' + miss.join(',') + ')');
      var arrow = function(n){ return st2.people.filter(function(p){return p.n===n;})[0]; };
      var sy = arrow('孙银刚'), lk = arrow('梁凯炯');
      push('孙银刚 areas=' + (sy?sy.areas.join('/'):'?'));
      push('梁凯炯 areas=' + (lk?lk.areas.join('/'):'?'));
      var js = st2.people.map(function(p){ return {n:p.n, home:p.home, d:p.district, aa:p.autoArea, areas:p.areas, note:p.addrNote}; });
      push('AREAJSON=' + JSON.stringify(js));
      push('ERRS=' + ((window.__ERRS||[]).join(' ; ')||'none'));
    } catch (e) { push('ERR ' + (e && e.message) + ' @@ ' + (e && e.stack ? e.stack.split('\n').slice(0,3).join(' <= ') : '')); }
    var d = document.createElement('div'); d.id = 'E2E'; d.textContent = out.join(' || ');
    document.body.appendChild(d);
  }
  if (document.readyState === 'complete') run(); else window.addEventListener('load', function(){ setTimeout(run, 300); });
  setTimeout(run, 4000);
})();
</script>
'''
html = open(OUT, 'r', encoding='utf-8').read()
html = html.replace('<script>window.__PAIBAN_DATA__', ERRTRAP + '<script>window.__PAIBAN_DATA__', 1)
i = html.rfind('</body>')
html = html[:i] + TEST + html[i:]
P1 = os.path.join(B, '_addr_e2e.html')
open(P1, 'w', encoding='utf-8').write(html)

EDGE = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
PROF = "C:/Windows/Temp/e2eAddr1"
DOM = os.path.join(B, '_addr_dom.html')
subprocess.call(["taskkill", "/F", "/IM", "msedge.exe"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(2)
subprocess.call([EDGE, "--headless=new", "--disable-gpu", "--user-data-dir=" + PROF,
                 "--virtual-time-budget=10000", "--dump-dom", "file:///" + P1.replace("\\", "/")],
                stdout=open(DOM, "w", encoding="utf-8"), stderr=subprocess.DEVNULL)

s = open(DOM, 'r', encoding='utf-8', errors='replace').read()
k = s.find('id="E2E"')
if k < 0:
    txt = "NO_E2E len=%d" % len(s)
else:
    a = s.find('>', k); b = s.find('</div>', a)
    txt = H.unescape(s[a+1:b]).replace(' || ', '\n')
open(os.path.join(B, '_addr_out.txt'), 'w', encoding='utf-8').write(txt)
print(txt)
