# -*- coding: utf-8 -*-
"""V3 页面结构整合 · 真实浏览器验收（Chromium CDP，不依赖 playwright）

用法： python3 v3/_cdp_check.py [文件路径]
输出： JSON（含 9 项验收所需的实测值）+ 控制台报错列表
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request

import websocket

URL = sys.argv[1] if len(sys.argv) > 1 else 'file:///data/workspace/南部大区城市看板/南部大区经营看板_v3.html'
PORT = 9333
CHROME = '/usr/bin/chromium'


class CDP(object):
    def __init__(self, port):
        self.port = port
        self.id = 0
        self.ws = None
        self.events = []

    def http(self, path):
        with urllib.request.urlopen('http://127.0.0.1:%d%s' % (self.port, path), timeout=5) as r:
            return json.loads(r.read().decode('utf-8'))

    def wait_up(self, sec=30):
        t0 = time.time()
        while time.time() - t0 < sec:
            try:
                self.http('/json/version')
                return True
            except Exception:
                time.sleep(0.2)
        return False

    def connect(self, url):
        tgt = None
        for _ in range(50):
            for t in self.http('/json/list'):
                if t.get('type') == 'page':
                    tgt = t
                    break
            if tgt:
                break
            time.sleep(0.2)
        assert tgt, 'no page target'
        self.ws = websocket.create_connection(tgt['webSocketDebuggerUrl'], timeout=60, max_size=1 << 26)
        return tgt

    def send(self, method, params=None):
        self.id += 1
        mid = self.id
        self.ws.send(json.dumps({'id': mid, 'method': method, 'params': params or {}}))
        while True:
            raw = self.ws.recv()
            msg = json.loads(raw)
            if msg.get('id') == mid:
                if 'error' in msg:
                    raise RuntimeError('%s -> %s' % (method, msg['error']))
                return msg.get('result', {})
            elif 'method' in msg:
                self.events.append(msg)

    def ev(self, expr, await_promise=False):
        r = self.send('Runtime.evaluate', {
            'expression': expr, 'returnByValue': True, 'awaitPromise': await_promise, 'userGesture': True})
        if 'exceptionDetails' in r:
            raise RuntimeError('JS error: %s' % json.dumps(r['exceptionDetails'], ensure_ascii=False)[:600])
        return r.get('result', {}).get('value')

    def wait_for(self, expr, sec=20):
        t0 = time.time()
        while time.time() - t0 < sec:
            try:
                if self.ev(expr):
                    return True
            except Exception:
                pass
            time.sleep(0.2)
        return False

    def errors(self):
        out = []
        for e in self.events:
            m = e.get('method')
            p = e.get('params', {})
            if m == 'Runtime.exceptionThrown':
                d = p.get('exceptionDetails', {})
                out.append('[exception] ' + str(d.get('text')) + ' :: ' + str((d.get('exception') or {}).get('description'))[:300])
            elif m == 'Runtime.consoleAPICalled' and p.get('type') == 'error':
                args = [str((a.get('value') if 'value' in a else a.get('description'))) for a in p.get('args', [])]
                out.append('[console.error] ' + ' '.join(args)[:400])
            elif m == 'Log.entryAdded':
                en = p.get('entry', {})
                if en.get('level') == 'error':
                    out.append('[log] ' + str(en.get('text'))[:300] + ' :: ' + str(en.get('url'))[:120])
        return out


def main():
    prof = tempfile.mkdtemp(prefix='v3cdp_')
    proc = subprocess.Popen([CHROME, '--headless=new', '--disable-gpu', '--no-sandbox', '--hide-scrollbars',
                             '--force-device-scale-factor=1', '--remote-debugging-port=%d' % PORT,
                             '--user-data-dir=' + prof, '--window-size=1280,900', '--remote-allow-origins=*', 'about:blank'],
                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    cdp = CDP(PORT)
    report = {}
    try:
        assert cdp.wait_up(), 'chromium 未就绪'
        cdp.connect(URL)
        cdp.send('Runtime.enable')
        cdp.send('Log.enable')
        cdp.send('Page.enable')
        cdp.send('Emulation.setDeviceMetricsOverride', {'width': 1280, 'height': 900, 'deviceScaleFactor': 1, 'mobile': False})
        cdp.send('Page.navigate', {'url': URL})
        ok = cdp.wait_for("!!(window.DATA && document.querySelector('#v3main tr.v3mrow') && (document.querySelectorAll('#v3main thead th').length>0))", 40)
        report['loaded'] = ok
        time.sleep(1.2)

        # ① 页签
        report['tabs'] = cdp.ev("Array.from(document.querySelectorAll('.tabs button')).map(b=>b.textContent.trim())")

        # ② 主表结构
        report['main_cols'] = cdp.ev("document.querySelectorAll('#v3main thead th').length")
        report['main_col_names'] = cdp.ev("Array.from(document.querySelectorAll('#v3main thead th')).map(x=>x.textContent.trim())")
        report['main_rows'] = cdp.ev("document.querySelectorAll('#v3main tr.v3mrow').length")
        report['main_city_order'] = cdp.ev("Array.from(document.querySelectorAll('#v3main tr.v3mrow')).map(x=>x.dataset.city)")
        report['tblDirect_hidden'] = cdp.ev("(function(){var e=document.getElementById('tblDirect'); return !!e && getComputedStyle(e.parentNode).display==='none';})()")
        report['tblDirect_rows_kept'] = cdp.ev("document.querySelectorAll('#tblDirect tr.clickable').length")
        report['v3t2goal_gone'] = cdp.ev("!document.getElementById('v3t2goal')")

        # ③ 月份切换：大区 + 广州
        def snap(month):
            return cdp.ev("""(function(){
              var s=document.getElementById('v3Month'); s.value='%s'; s.dispatchEvent(new Event('change',{bubbles:true}));
              function row(c){var tr=document.querySelector('#v3main tr.v3mrow[data-city="'+c+'"]');
                return tr? Array.from(tr.children).map(td=>td.textContent.replace(/\\s+/g,' ').trim()) : null;}
              return {month:s.value, region:row('__REGION__'), gz:row('广州市'),
                      region_header:Array.from(document.querySelectorAll('#v3main thead th')).map(x=>x.textContent.trim()),
                      note:document.getElementById('v3MoNote').textContent.replace(/\\s+/g,' ').trim()};
            })()""" % month)

        report['m202610'] = snap('202610')
        report['m202611'] = snap('202611')
        report['m202612'] = snap('202612')
        report['m202610_back'] = snap('202610')
        report['detail_rows_after_switch'] = cdp.ev("document.querySelectorAll('#v3main tr.v3detail').length")

        # ⑤ 广州下钻
        rep = cdp.ev("""(function(){
          var tr=document.querySelector('#v3main tr.v3mrow[data-city="广州市"]'); tr.click();
          var d=document.querySelector('#v3main tr.v3detail');
          if(!d) return {ok:false};
          var mods=d.querySelectorAll('.v3mod');
          var tbl=d.querySelector('.v3sub');
          var body=Array.from(tbl.querySelectorAll('tbody tr')).map(r=>Array.from(r.children).map(c=>c.textContent.replace(/\\s+/g,' ').trim()));
          return {ok:true, modules:mods.length, mod_titles:Array.from(mods).map(m=>m.querySelector('h4').textContent.replace(/\\s+/g,' ').trim().slice(0,40)),
            cost_rows:body, concl:Array.from(d.querySelectorAll('.v3concl li')).map(li=>li.textContent.replace(/\\s+/g,' ').trim()),
            svg_count:d.querySelectorAll('svg.v3svg').length, tables:d.querySelectorAll('table').length,
            svg_pts:Array.from(d.querySelectorAll('svg.v3svg polyline')).map(p=>p.getAttribute('points').split(' ').length)};
        })()""")
        report['drill_gz'] = rep
        report['data_gz'] = cdp.ev("""(function(){var v=DATA.cities12['广州市'];
          return {cost:v['成本'].mtd, ele_rate:v['-电费费率'].mtd, gp:v['毛利额'].mtd, gpm:v['毛利率'].mtd,
                  kwh:v['-单用户用电量'].mtd, yx:v['营销费'].mtd, rent:v['租金'].mtd};})()""")

        # ⑥ 测算跳转
        rep6 = cdp.ev("""(function(){
          var b=document.querySelector('#v3main tr.v3mrow[data-city="广州市"] .v3go'); b.click(); return true;})()""")
        time.sleep(2.0)
        report['planner'] = cdp.ev("""(function(){
          var t6=document.getElementById('t6');
          var sc=document.querySelector('#plBar select[data-k="scope"]');
          var ms=document.querySelector('#plBar select[data-k="month"]');
          return {plbar: !!document.getElementById('plBar'),
                  scope_opts: sc?Array.from(sc.options).map(o=>o.value).slice(0,4):null,
                  tab_t6_on: t6.classList.contains('on'),
                  t6_visible: t6.offsetParent!==null,
                  scope: sc?sc.value:null, month: ms?ms.value:null,
                  cards: (document.querySelector('#plCards')||{}).textContent ? document.querySelector('#plCards').textContent.replace(/\\s+/g,' ').trim().slice(0,160) : null};
        })()""")

        # ⑦ 专项分析默认收起（回到 t2 检查）
        report['details'] = cdp.ev("""(function(){
          var b=document.querySelector('.tabs button[data-t="t2"]'); b.click();
          var d=document.getElementById('v3det');
          var riskDrawnBefore = !!(window.echarts && document.getElementById('chRisk') && echarts.getInstanceByDom(document.getElementById('chRisk')));
          return {open:d.open, risk_init_before_open:riskDrawnBefore,
                  contrib_text:(document.getElementById('contribBody').textContent||'').replace(/\\s+/g,' ').trim().slice(0,60),
                  chRisk_h:document.getElementById('chRisk').clientHeight};
        })()""")
        time.sleep(0.4)
        report['details_after_open'] = cdp.ev("""(function(){
          var d=document.getElementById('v3det'); d.open=true; d.dispatchEvent(new Event('toggle'));
          return {open:d.open};})()""")
        time.sleep(1.0)
        report['details_open_state'] = cdp.ev("""(function(){
          var d=document.getElementById('v3det'), c=document.getElementById('chRisk');
          return {open:d.open, risk_init: !!(window.echarts && echarts.getInstanceByDom(c)),
                  chRisk_h:c.clientHeight, contrib_has_rows: document.querySelectorAll('#contribBody tr').length};
        })()""")

        # ⑨ 宽度
        MEAS = """(function(){
              var de=document.documentElement, b=document.body;
              var cw=de.clientWidth, out=[];
              Array.from(document.querySelectorAll('body *')).forEach(function(el){
                var r=el.getBoundingClientRect();
                if(r.width>0 && r.right>cw+1){ out.push({tag:el.tagName, id:el.id, cls:(el.className||'').toString().slice(0,30), right:Math.round(r.right)}); }
              });
              out.sort(function(a,b){return b.right-a.right;});
              return {de_sw:de.scrollWidth, de_cw:cw, body_sw:b.scrollWidth, overflow:de.scrollWidth-de.clientWidth,
                      offenders: out.slice(0,6),
                      v3wrap_sw:(function(){var w=document.querySelector('#v3main').parentNode; return w.scrollWidth-w.clientWidth;})(),
                      drill_w:(function(){var d=document.querySelector('.v3drill'); return d?Math.round(d.getBoundingClientRect().width):null;})()};
            })()"""

        def width(w):
            cdp.send('Emulation.setDeviceMetricsOverride', {'width': w, 'height': 900, 'deviceScaleFactor': 1, 'mobile': w < 500})
            time.sleep(1.6)
            return cdp.ev(MEAS)

        report['w1280'] = width(1280)
        report['w375'] = width(375)
        # 375 下：展开下钻 + 专项分析（最容易溢出的两种状态）
        cdp.ev("document.querySelector('#v3main tr.v3mrow[data-city=\"广州市\"]').click();")
        time.sleep(0.5)
        report['w375_drill_open'] = cdp.ev(MEAS)
        report['w375_drill_modules'] = cdp.ev("document.querySelectorAll('#v3main tr.v3detail .v3mod').length")
        cdp.ev("(function(){var d=document.getElementById('v3det'); d.open=true; d.dispatchEvent(new Event('toggle'));})()")
        time.sleep(1.5)
        report['w375_details_open'] = cdp.ev(MEAS)
        cdp.ev("(function(){var d=document.getElementById('v3det'); d.open=false; d.dispatchEvent(new Event('toggle'));})()")
        width(1280)

        # 其它页签数值抽样（对比 v2）
        report['t1_kpis'] = cdp.ev("(function(){document.querySelector('.tabs button[data-t=\"t1\"]').click(); return document.getElementById('kpiRow').textContent.replace(/\\s+/g,' ').trim().slice(0,200);})()")
        report['t3_first'] = cdp.ev("(function(){document.querySelector('.tabs button[data-t=\"t3\"]').click(); return document.getElementById('lyKpi').textContent.replace(/\\s+/g,' ').trim().slice(0,160);})()")
        report['t4_ok'] = cdp.ev("(function(){document.querySelector('.tabs button[data-t=\"t4\"]').click(); var c=document.getElementById('chMonth'); return !!echarts.getInstanceByDom(c);})()")
        time.sleep(0.6)

        report['console_errors'] = cdp.errors()
    finally:
        try:
            cdp.ws.close()
        except Exception:
            pass
        proc.terminate()
        try:
            proc.wait(timeout=10)
        except Exception:
            proc.kill()
        shutil.rmtree(prof, ignore_errors=True)

    print(json.dumps(report, ensure_ascii=False, indent=1))


if __name__ == '__main__':
    main()
