#!/usr/bin/env python3
"""Разбирает каноническую легенду метрик halleg (local/Source/Trader_Reporting.html, слаг /metrics-legend)
в структурированный JSON: local/platform/data/_canon.json"""
import re, json, html, os
SRC = os.path.join(os.path.dirname(__file__), '..', 'Source', 'Trader_Reporting.html')
OUT = os.path.join(os.path.dirname(__file__), '..', 'platform', 'data', '_canon.json')
s = open(SRC, encoding='utf-8').read()
def clean(x):
    x = re.sub(r'<br\s*/?>', '\n', x)
    x = re.sub(r'<[^>]+>', '', x)
    return html.unescape(x).strip()
meta = {}
m = re.search(r'Актуалізовано:\s*([\d-]+)', s); meta['updated_at'] = m.group(1) if m else None
m = re.search(r'Власники означень:\s*(.*?)<', s); meta['owners'] = clean(m.group(1)) if m else None
meta['timezone'] = 'IST (Asia/Kolkata, UTC+5:30)'
meta['source'] = 'ClickHouse-репліка hermes'
meta['rule'] = 'Метрика рахується тільки так, як тут описано; якщо звіт рахує інакше — виправляється звіт.'
meta['saved_from'] = 'https://reports.halleg.renderhorizon.org/metrics-legend'
out = []
group = None
for part in re.split(r'(<h2 class="group">.*?</h2>)', s):
    gm = re.match(r'<h2 class="group">(.*?)</h2>', part)
    if gm: group = clean(gm.group(1)); continue
    for mm in re.finditer(r'<div class="metric" id="([^"]+)">(.*?)(?=<div class="metric" id=|<footer|$)', part, re.S):
        mid, body = mm.group(1), mm.group(2)
        name_full = clean(re.search(r'<h3>(.*?)</h3>', body, re.S).group(1))
        name_en, _, name_uk = name_full.partition(' — ')
        syn = re.search(r'<div class="syn">(.*?)</div>', body, re.S)
        syn = clean(syn.group(1)) if syn else ''
        syn = re.sub(r'^Синоніми( у звітах)?:\s*', '', syn)
        synonyms = [x.strip() for x in re.split(r',\s*', syn) if x.strip()]
        rows = {}
        for rm in re.finditer(r'<div class="row"><span class="lbl">(.*?)</span>(.*?)</div>(?=\s*(?:<div class="row"|<div class="note"|<div class="reports"|<p|$))', body, re.S):
            rows[clean(rm.group(1))] = clean(rm.group(2))
        notes = [clean(x) for x in re.findall(r'<div class="(?:warn|note)">(.*?)</div>', body, re.S)]
        out.append(dict(canon_id=mid, group=group, name_en=name_en.strip(), name_uk=name_uk.strip(), synonyms=synonyms, rows=rows, notes=notes))
json.dump(dict(meta=meta, metrics=out), open(OUT, 'w'), ensure_ascii=False, indent=1)
print(len(out), 'метрик канона;', meta)
for o in out: print(f"{o['canon_id']:18} {o['name_en']:28} rows={list(o['rows'])} syn={len(o['synonyms'])} notes={len(o['notes'])}")
