# -*- coding: utf-8 -*-
"""验证「额外辖区（离行外挂/外派点）不算正常辖区」：覆盖数应为 18 / 18。"""
import io, os

SRC = r"D:\workbbbbbb\排班工具.html"
OUT = r"D:\workbbbbbb\build\_extra_e2e.html"

ERRTRAP = ('<script>window.__ERRS=[];window.addEventListener("error",function(e){'
           'window.__ERRS.push((e.message||"")+" @line"+e.lineno);});</script>')

TEST = r"""
<script>
(function () {
  var done = false;
  function run() {
    if (done) return; done = true;
    var out = [];
    try {
      var s = window.__PB.state();
      var extra = (s.county && s.county.extra) || [];
      out.push('extra=' + extra.join('|'));
      var holders = [];
      s.people.forEach(function (p) {
        var a = p.areas || [];
        extra.forEach(function (x) { if (a.indexOf(x) >= 0) holders.push(p.n + ':' + x); });
      });
      out.push('extraHolders=' + holders.length + '(' + holders.join('|') + ')');
      var ns = s.people.map(function (p) { return (p.areas || []).length; });
      out.push('perCounts=' + ns.join(','));
      out.push('spread=' + (Math.max.apply(null, ns) - Math.min.apply(null, ns)));
      out.push('total=' + ns.reduce(function (a, b) { return a + b; }, 0));
      out.push('cover=' + document.getElementById('areaCover').textContent);
      out.push('note=' + document.getElementById('areaOffNote').innerHTML.replace(/<br>/g, ' / '));
      var rows = document.querySelectorAll('#areaSummary .row');
      var xr = [];
      for (var i = 0; i < rows.length; i++) {
        if (rows[i].textContent.indexOf('额外·不计入正常辖区') >= 0) xr.push(rows[i].querySelector('.t1').textContent);
      }
      out.push('extraRows=' + xr.length + '(' + xr.join('|') + ')');
    } catch (e) {
      out.push('ERR ' + e.message);
    }
    out.push('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
    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 = io.open(SRC, encoding='utf-8').read()
i = html.find('<script>window.__PAIBAN_DATA__')
assert i > 0, 'data script not found'
html = html[:i] + ERRTRAP + html[i:]
end = html.rfind('</body>')
assert end > 0
html = html[:end] + TEST + html[end:]
io.open(OUT, 'w', encoding='utf-8').write(html)
print('out=', OUT, 'size=', round(os.path.getsize(OUT) / 1024.0, 1), 'KB')
