#!/usr/bin/env python3
"""校验同一次计算的观测快照，生成自包含的 HTML 计算全景图。只解析和绘图，不查询或推断业务关系。"""
from __future__ import annotations

import argparse
from collections import defaultdict
import hashlib
import json
from pathlib import Path
import re

PREFIX = 'calculation.panorama.'  # 同一 span 内的快照传输属性前缀。
SCHEMAS = ('calculation-panorama-v1', 'calculation-panorama-v2')  # v1 是逻辑依赖，v2 是本次查询构建。
COUNTS = ('field', 'advanced_component', 'parameter', 'dynamic', 'linkage')  # 旧条件树的五类直接条件计数。


def decode_attributes(attrs):
    """拼合同一 span 的分块并核对长度、摘要；缺失或截断时拒绝生成貌似完整的快照。"""
    if attrs.get(PREFIX + 'status') != 'CAPTURED':
        raise ValueError('全景快照未成功记录：' + str(attrs.get(PREFIX + 'status', 'UNKNOWN')))
    count = int(attrs[PREFIX + 'part_count'])
    if not 1 <= count <= 16:
        raise ValueError('全景分块数量无效')
    parts = []
    for index in range(count):
        part = attrs.get(PREFIX + f'part_{index}')
        if not isinstance(part, str):
            raise ValueError(f'全景快照缺少第 {index} 块，不能宣称完整')
        parts.append(part)
    body = ''.join(parts)
    # 服务端长度单位为 UTF-16 code unit；哈希为 UTF-8，包含非 BMP 名称时也能核对。
    if len(body.encode('utf-16-le')) // 2 != int(attrs[PREFIX + 'length']):
        raise ValueError('全景快照长度不符，可能已截断')
    if hashlib.sha256(body.encode('utf-8')).hexdigest() != attrs[PREFIX + 'sha256']:
        raise ValueError('全景快照摘要不符，不能混用不同计算的分块')
    return json.loads(body)


def candidates(value, inherited=None):
    """接受 MCP 原始 JSON 响应、定向查询行或已解析快照；只在所属行内继承身份。"""
    found = []
    if isinstance(value, dict):
        identity = dict(inherited or {})
        for key in ('span_id', 'trace_id'):
            if isinstance(value.get(key), str):
                identity[key] = value[key]
        if isinstance(value.get('data'), dict):
            for key in ('span_id', 'trace_id'):
                if isinstance(value['data'].get(key), str):
                    identity[key] = value['data'][key]
        attributes = {}
        for key, child in value.items():
            if key.startswith('attributes_') and isinstance(child, dict):
                attributes.update(child)
        if PREFIX + 'status' in attributes or 'filter_conditions.tree_summary' in attributes:
            return [(attributes, identity)]
        if value.get('schema') in SCHEMAS or 'tree' in value and 'declared' in value:
            return [(value, identity)]
        if PREFIX + 'status' in value or 'filter_conditions.tree_summary' in value:
            return [(value, identity)]
        for key, child in value.items():
            if key == 'text' and isinstance(child, str):
                try:
                    child = json.loads(child)
                except ValueError:
                    continue
            found.extend(candidates(child, identity))
    elif isinstance(value, list):
        for child in value:
            found.extend(candidates(child, inherited))
    return found


def legacy_tree(value):
    """统一历史路径摘要的输入形式，保留声明数量和截断标记供后续核对。"""
    if 'tree' in value:
        return value
    summary = value['filter_conditions.tree_summary']
    rows = []
    for path, body in re.findall(r'([^\s,\[\]{}]+)\{([^{}]*)\}', summary):
        rows.append({'path': path.split('->'), 'fields': dict(part.split('=', 1) for part in body.split(','))})
    if not rows:
        raise ValueError('旧条件摘要没有可解析的路径')
    return {'tree': rows, 'declared': {
        key: value.get('filter_conditions.' + key) for key in ('node_count', 'path_node_count', 'max_depth')
    }, 'truncated': '...' in summary, 'rootTableId': value.get('filter_conditions.root_table_id')}


def from_legacy(value):
    """只还原旧记录能证明的条件传播图；未知参数身份保留 None，不转为无参数。"""
    tree = legacy_tree(value)
    rows = tree['tree']
    gaps = ['旧记录只包含条件展开关系；完整逻辑依赖、表名和逐节点参数身份未记录。']
    nodes, paths, identities = [], {}, defaultdict(list)
    for row in rows:
        fields, path = row['fields'], tuple(row['path'])
        if fields.get('cycle') == 'true' or fields.get('shared') == 'true':
            continue
        if not all(key in fields for key in COUNTS):
            gaps.append('部分路径缺少条件计数')
        node = {'id': f'condition-{len(nodes)}', 'tableId': path[-1], 'counts': fields,
                'fieldFilters': None, 'componentFilters': None, 'linkageFilters': None,
                'parameters': None, 'dynamicFields': None}
        nodes.append(node)
        paths[path] = node['id']
        identities[(path[-1], tuple(fields.get(k) for k in COUNTS))].append(node['id'])
    for row in rows:
        fields, path = row['fields'], tuple(row['path'])
        if fields.get('shared') == 'true':
            possible = identities[(path[-1], tuple(fields.get(k) for k in COUNTS))]
            if len(possible) == 1:
                paths[path] = possible[0]
            else:
                gaps.append('共享条件对象身份不唯一，保留未关联路径：' + ' → '.join(path))
        elif fields.get('cycle') == 'true':
            ancestors = [path[:n] for n in range(1, len(path)) if path[n - 1] == path[-1] and path[:n] in paths]
            if len(ancestors) == 1:
                paths[path] = paths[ancestors[0]]
            else:
                gaps.append('环路末端身份未确认')
    edges = sorted({(paths[path], paths[path[:-1]]) for path in paths if len(path) > 1 and path[:-1] in paths})
    declared = tree.get('declared', {})
    visible = sum(row['fields'].get('cycle') != 'true' for row in rows)
    checks = {'node_count': len(nodes), 'path_node_count': visible,
              'max_depth': max((len(row['path']) - 1 for row in rows), default=0)}
    for key, actual in checks.items():
        if declared.get(key) is None or int(declared[key]) != actual:
            gaps.append(f'旧条件树 {key} 未核对通过：声明 {declared.get(key)}，可见 {actual}')
    if tree.get('truncated') or len(paths) != len(rows):
        gaps.append('旧条件树路径不完整，不能宣称覆盖全部节点')
    return {'schema': 'legacy-condition-tree', 'rootTableId': rows[0]['path'][0],
            'tables': [{'id': table} for table in dict.fromkeys(node['tableId'] for node in nodes)],
            'dependencies': [], 'nodes': nodes,
            'conditionEdges': [{'source': a, 'target': b} for a, b in edges],
            'parameters': [], 'gaps': gaps, 'omittedNodes': 0, 'omittedEdges': 0,
            'notCaptured': ['完整计算依赖', '表定义筛选', '逐表参数身份', '物理执行'],
            'traceId': tree.get('traceId'), 'time': tree.get('time'), 'sourceSpan': tree.get('sourceSpan')}


def normalize(source, span_id=None, context=None):
    """选定单次快照并验证引用；context 只补入口说明，不用于补造逐表绑定和依赖。"""
    options = candidates(source)
    # MCP 可能同时返回 content 和 structuredContent，去掉同一份响应的重复表示。
    unique = {}
    for data, identity in options:
        if span_id and identity.get('span_id', data.get('sourceSpan')) != span_id:
            continue
        unique[(json.dumps(data, sort_keys=True, ensure_ascii=False), json.dumps(identity, sort_keys=True))] = (data, identity)
    if len(unique) != 1:
        raise ValueError(f'找到 {len(unique)} 份计算快照；请以 --span-id 选定本次计算，不能默认选最大一棵')
    data, identity = next(iter(unique.values()))
    if data.get(PREFIX + 'status'):
        snapshot = decode_attributes(data)
    elif data.get('schema') in SCHEMAS:
        snapshot = json.loads(json.dumps(data))
    else:
        snapshot = from_legacy(data)
    if snapshot.get('schema') == 'calculation-panorama-v2':
        # wire 中每份筛选正文只出现一次；展开仅供 HTML 展示，不回写 trace。
        conditions = snapshot['conditions']
        def expand(refs):
            if any(ref not in conditions for ref in refs):
                raise ValueError('筛选引用了未记录的条件，不能补造')
            return [dict(conditions[ref], _traceConditionId=ref) for ref in refs]
        for node in snapshot['nodes']:
            for key in ('fieldFilters', 'componentFilters', 'linkageFilters'):
                node[key] = expand(node[key])
        definitions = [table.get('definition') for table in snapshot['tables']]
        for table in snapshot['tables']:
            definitions.extend(table.get('variants', []))
        definitions.append(snapshot.get('componentDefinition'))
        for definition in definitions:
            if definition:
                for step in definition['filters']:
                    step['conditions'] = expand(step['conditions'])
        for stage in snapshot.get('componentStages', []):
            stage['conditions'] = expand(stage['conditions'])
        if snapshot.get('scope') != 'QUERY_BUILT':
            snapshot.setdefault('gaps', []).append('本次查询构建未完成，图中保留已确认部分，不代表完整成功计算。')
    known_trace = snapshot.get('traceId') or identity.get('trace_id')
    if known_trace and (context or {}).get('traceId', known_trace) != known_trace:
        raise ValueError('说明上下文与计算快照的 trace 不一致')
    if snapshot.get('componentId') and (context or {}).get('componentId', snapshot['componentId']) != snapshot['componentId']:
        raise ValueError('说明上下文与计算快照的组件不一致')
    for key, value in (context or {}).items():
        if key in ('traceId', 'componentId', 'componentName', 'time', 'summary', 'evidence', 'requestParameters'):
            if key == 'componentName' and snapshot.get('componentName'):
                continue
            snapshot[key] = value
    snapshot.setdefault('traceId', identity.get('trace_id'))
    snapshot.setdefault('sourceSpan', identity.get('span_id'))
    table_ids = [table['id'] for table in snapshot['tables']]
    node_ids = [node['id'] for node in snapshot['nodes']]
    if len(set(table_ids)) != len(table_ids) or len(set(node_ids)) != len(node_ids):
        raise ValueError('表或条件对象身份重复')
    if snapshot['rootTableId'] not in table_ids:
        raise ValueError('根表不在记录范围内')
    for node in snapshot['nodes']:
        if node['tableId'] not in table_ids:
            raise ValueError('条件节点引用了未记录的表')
    parameter_ids = [parameter['id'] for parameter in snapshot['parameters']]
    if len(parameter_ids) != len(set(parameter_ids)):
        raise ValueError('参数身份重复')
    for node in snapshot['nodes']:
        for parameter in node.get('parameters') or []:
            if parameter['id'] not in parameter_ids:
                raise ValueError('节点引用了未记录的参数')
    if snapshot.get('schema') == 'calculation-panorama-v2':
        def validate_condition(condition):
            if any(ref not in parameter_ids for ref in condition.get('parameterIds', [])):
                raise ValueError('筛选引用了未记录的参数')
            for child in condition.get('children', []):
                validate_condition(child)
        for condition in snapshot['conditions'].values():
            validate_condition(condition)
        control_ids = [control['id'] for control in snapshot.get('controls', [])]
        if len(control_ids) != len(set(control_ids)):
            raise ValueError('控件身份重复')
        for condition, sources in snapshot.get('conditionControls', {}).items():
            if condition not in snapshot['conditions'] or any(source not in control_ids for source in sources):
                raise ValueError('条件来源引用了未记录的筛选或控件')
        for node in snapshot['nodes']:
            for item in (node.get('parameters') or []) + (node.get('dynamicFields') or []):
                if any(source not in control_ids for source in item.get('controlIds', [])):
                    raise ValueError('覆盖项来源引用了未记录的控件')
        for dynamic in snapshot.get('dynamicDefinitions', []):
            if dynamic['tableId'] not in table_ids:
                raise ValueError('动态字段名称引用了未记录的表')
    for edges, ids in ((snapshot['dependencies'], set(table_ids)), (snapshot['conditionEdges'], set(node_ids))):
        if len({(edge['source'], edge['target']) for edge in edges}) != len(edges):
            raise ValueError('同一种依赖关系重复记录')
        for edge in edges:
            if edge['source'] not in ids or edge['target'] not in ids:
                raise ValueError('关系引用了未记录的节点，不能猜接')
    return snapshot


def render(snapshot, output):
    """将已校验的展示数据嵌入离线 HTML；业务文本转义后写入，防止结束 script 标签。"""
    template = Path(__file__).with_name('assets').joinpath('calculation-panorama.html').read_text(encoding='utf-8')
    payload = json.dumps(snapshot, ensure_ascii=False).replace('<', '\\u003c').replace('>', '\\u003e').replace('&', '\\u0026')
    document = template.replace('__PANORAMA_DATA__', payload)
    output = Path(output)
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(document, encoding='utf-8')
    return {'file': str(output.resolve()), 'tables': len(snapshot['tables']), 'conditionNodes': len(snapshot['nodes']),
            'dependencyEdges': len(snapshot['dependencies']), 'conditionEdges': len(snapshot['conditionEdges']),
            'scope': snapshot['schema'], 'gaps': snapshot.get('gaps', [])}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--input', required=True, type=Path)
    parser.add_argument('--output', required=True, type=Path)
    parser.add_argument('--span-id')
    parser.add_argument('--context', type=Path, help='同次计算已核实的入口名称、结论、全局参数；不用于推断逐表绑定')
    args = parser.parse_args()
    context = json.loads(args.context.read_text(encoding='utf-8-sig')) if args.context else None
    snapshot = normalize(json.loads(args.input.read_text(encoding='utf-8-sig')), args.span_id, context)
    print(json.dumps(render(snapshot, args.output), ensure_ascii=False))


if __name__ == '__main__':
    main()
