"""Build an offline HTML reading edition of an existing clustering report."""
from __future__ import annotations

import argparse
import base64
import hashlib
import html
import json
import mimetypes
import os
from pathlib import Path
from urllib.parse import unquote, urlsplit


def sha256(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def build_html_report(source, destination=None):
    from markdown_it import MarkdownIt

    source = Path(source).resolve()
    destination = Path(destination).resolve() if destination else source.with_suffix('.html')
    if destination == source:
        raise ValueError('HTML output must differ from the source Markdown report')
    source_hash = sha256(source)
    folder = source.parent
    assets = {source: source_hash}
    summary_path = folder/'summary.json'
    summary = json.loads(summary_path.read_text()) if summary_path.exists() else {}
    if summary:
        assets[summary_path] = sha256(summary_path)

    parser = MarkdownIt('commonmark', {'html': False}).enable('table')
    tokens = parser.parse(source.read_text())
    title = source.stem
    navigation = []
    for index, token in enumerate(tokens):
        if token.type == 'heading_open':
            text = tokens[index+1].content
            if token.tag == 'h1' and title == source.stem:
                title = text
            elif token.tag == 'h2':
                identifier = f'section-{len(navigation)+1}'
                token.attrSet('id', identifier)
                navigation.append((identifier, text))
    # The source title is rendered once in the page header.
    if tokens and tokens[0].type == 'heading_open' and tokens[0].tag == 'h1':
        tokens = tokens[3:]

    def embed(path):
        path = Path(path)
        assets[path] = sha256(path)
        mime = mimetypes.guess_type(path.name)[0] or 'application/octet-stream'
        return f'data:{mime};base64,'+base64.b64encode(path.read_bytes()).decode()

    original_link = parser.renderer.rules.get('link_open', parser.renderer.renderToken)

    def link_open(items, index, options, env):
        token = items[index]
        href = token.attrGet('href') or ''
        # Preserve relative links even when --output places the edition elsewhere.
        parsed = urlsplit(href)
        if not parsed.scheme and parsed.path and not href.startswith('#'):
            target = folder/unquote(parsed.path)
            relative = Path(os.path.relpath(target, destination.parent)).as_posix()
            token.attrSet('href', relative+('?' + parsed.query if parsed.query else '')+('#'+parsed.fragment if parsed.fragment else ''))
        return original_link(items, index, options, env)

    def image(items, index, options, env):
        token = items[index]
        href = token.attrGet('src') or ''
        parsed = urlsplit(href)
        path = folder/unquote(parsed.path)
        if not parsed.scheme:
            if not path.is_file():
                raise FileNotFoundError(f'Report figure missing: {path}')
            href = embed(path)
        label = html.escape(token.content)
        return (f'<button type="button" class="figure" aria-label="放大：{label}">'
                f'<img src="{html.escape(href, quote=True)}" alt="{label}" loading="lazy">'
                f'<span>{label}<small>点击放大</small></span></button>')

    table_rows = []
    in_body = False
    for token in tokens:
        if token.type == 'table_open':
            table_rows.append(0)
        elif token.type == 'tbody_open':
            in_body = True
        elif token.type == 'tbody_close':
            in_body = False
        elif token.type == 'tr_open' and in_body:
            table_rows[-1] += 1
    table_index = 0

    def table_open(items, index, options, env):
        nonlocal table_index
        count = table_rows[table_index]
        table_index += 1
        return ('<div class="table-card"><div class="table-meta">'
                f'<span>表 {table_index}</span><span class="row-count">{count} 行</span></div>'
                '<div class="table-scroll" tabindex="0"><table>\n')

    parser.renderer.rules.update(link_open=link_open, image=image, table_open=table_open,
                                 table_close=lambda *args: '</table></div></div>\n')
    body = parser.renderer.render(tokens, parser.options, {})
    toc = ''.join(f'<a href="#{identifier}">{html.escape(label)}</a>' for identifier,label in navigation)
    font_style = ''
    reading_font = Path.home()/'.cache/pallet_analysis/PalletReportReadingSans.woff'
    font = reading_font if reading_font.exists() else folder/'PalletReportSans.woff'
    license_path = folder/'FONT_LICENSE.txt'
    if font.exists() and license_path.exists():
        font_style = "@font-face{font-family:PalletReport;src:url('"+embed(font)+"') format('woff');font-display:swap}"
        assets[license_path] = sha256(license_path)
    else:
        license_path = None
    validation = summary.get('validation', {})
    clustering = summary.get('clustering', {})
    metrics = [('标注目标', validation.get('actual_targets')),
               ('外观结构簇', clustering.get('appearance', {}).get('clusters')),
               ('可见几何簇', clustering.get('geometry', {}).get('clusters')),
               ('几何可聚类目标', clustering.get('geometry', {}).get('targets')),
               ('几何证据存疑', validation.get('geometry_status', {}).get('foreground_depth_or_view_ambiguous'))]
    cards = ''.join(f'<div class="metric"><strong>{value:,}</strong><span>{label}</span></div>'
                    for label,value in metrics if value is not None)
    relative_root = Path(os.path.relpath(folder, destination.parent)).as_posix()
    def local(file):
        return html.escape((Path(relative_root)/file).as_posix(), quote=True)
    source_link = html.escape(Path(os.path.relpath(source, destination.parent)).as_posix(), quote=True)
    footer = f'由<a href="{source_link}">原始中文报告</a>生成 · 图表可离线阅读'
    if license_path:
        # Keep the bundled font's license with the self-contained edition.
        license_text = license_path.read_text()
        footer += '<details class="font-license"><summary>字体许可</summary><pre>'+html.escape(license_text)+'</pre></details>'
    document = '''<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>__TITLE__</title><style>
__FONT__
:root{--ink:#172d40;--muted:#607486;--accent:#007b87;--line:#dce5ec;--paper:#fff;--background:#eef3f7;--nav:#142d40}
*{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:30px}body{margin:0;background:var(--background);color:var(--ink);font:15px/1.8 PalletReport,"Noto Sans CJK SC","Microsoft YaHei",system-ui,sans-serif}a{color:var(--accent);text-underline-offset:3px}button,input{font:inherit}button{cursor:pointer}button:focus-visible,a:focus-visible,input:focus-visible,.table-scroll:focus-visible{outline:3px solid #2e9fac;outline-offset:3px}.layout{display:grid;grid-template-columns:245px minmax(0,1fr);max-width:1700px;margin:auto}.sidebar{position:sticky;top:0;height:100vh;background:var(--nav);color:#e4edf4;padding:34px 25px}.brand{font-size:13px;letter-spacing:.1em;color:#94bdc9}.sidebar b{display:block;font-size:21px;line-height:1.6;margin:12px 0 26px}.toc{display:grid;gap:8px}.toc a{display:block;padding:10px 12px;border-radius:6px;color:#cddce6;text-decoration:none;line-height:1.55}.toc a:hover,.toc a.active{background:#29485e;color:#fff}.sidebar .note{position:absolute;bottom:30px;left:25px;right:25px;color:#a9c1ce;font-size:12px}.content{min-width:0;padding:38px 45px 48px}.hero{margin-bottom:25px}.eyebrow{color:var(--accent);font-size:12px;font-weight:700;letter-spacing:.14em}.hero h1{font-size:32px;line-height:1.5;max-width:980px;margin:10px 0 14px}.hero p{color:var(--muted);margin:0;max-width:900px}.actions{display:flex;gap:10px;flex-wrap:wrap;margin:22px 0}.action{padding:8px 16px;background:white;border:1px solid var(--line);border-radius:6px;text-decoration:none;color:var(--ink)}.action.primary{background:var(--accent);border-color:var(--accent);color:#fff}.metrics{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;margin:20px 0 28px}.metric{background:white;border:1px solid var(--line);border-radius:9px;padding:17px 16px}.metric strong{display:block;font-size:29px;line-height:1.4;font-variant-numeric:tabular-nums}.metric span{color:var(--muted);font-size:13px}.reading-tools{display:flex;align-items:center;gap:14px;flex-wrap:wrap;margin-bottom:22px}.reading-tools label{display:flex;gap:10px;align-items:center}.reading-tools input{background:white;border:1px solid #bdcbd7;border-radius:5px;padding:7px 11px;width:300px;max-width:100%}.reading-tools small{color:var(--muted)}.mobile-toc{display:none}article{background:var(--paper);border:1px solid var(--line);border-radius:10px;padding:26px 32px;min-width:0}article>p:first-child{margin-top:0}p{margin:16px 0}h2{font-size:24px;line-height:1.5;border-bottom:1px solid var(--line);padding-bottom:13px;margin:44px 0 20px}h3{font-size:19px;margin:28px 0 12px}strong{font-weight:700}code{font:13px/1.65 PalletReport,ui-monospace,monospace;background:#edf3f6;color:#24556b;padding:2px 5px;border-radius:4px;overflow-wrap:anywhere}pre{background:#172d40;color:#e6edf2;padding:18px 20px;border-radius:7px;overflow:auto}pre code{font:13px/1.7 ui-monospace,monospace;color:inherit;background:none;padding:0}.table-card{margin:22px 0;border:1px solid var(--line);border-radius:7px;overflow:hidden}.table-meta{display:flex;justify-content:space-between;padding:8px 13px;background:#eff4f7;color:var(--muted);font-size:12px}.table-scroll{overflow:auto}table{border-collapse:collapse;width:100%;font-size:13px;line-height:1.65}thead{background:#e5edf3;color:#244559}th,td{padding:11px 12px;border-bottom:1px solid #e1e9ef;vertical-align:top;min-width:85px}th{font-weight:700;white-space:nowrap;text-align:left}th:first-child,td:first-child{min-width:155px}tbody tr:nth-child(even){background:#f8fafb}tbody tr:hover{background:#eef6f8}tbody tr:last-child td{border-bottom:0}td a{white-space:nowrap}td[style*="right"]{font-variant-numeric:tabular-nums}.figure{display:block;width:100%;background:#f8fafb;border:1px solid var(--line);border-radius:8px;padding:12px;margin:24px 0;color:var(--ink);text-align:left}.figure img{display:block;max-width:100%;width:auto;max-height:740px;object-fit:contain;margin:auto;background:white}.figure>span{display:flex;justify-content:space-between;padding:10px 3px 0;font-size:13px}.figure small{color:var(--muted)}.figure:hover{border-color:#61a2af}footer{font-size:12px;color:var(--muted);margin-top:24px}.font-license{margin-top:12px}.font-license pre{font:11px/1.5 ui-monospace,monospace;white-space:pre-wrap}.lightbox{border:0;border-radius:8px;padding:18px;background:white;width:min(1500px,96vw);max-height:96vh}.lightbox::backdrop{background:#142b40bd}.lightbox .dialog-bar{display:flex;justify-content:space-between;gap:15px;align-items:center;margin-bottom:14px}.lightbox button{border:1px solid var(--line);border-radius:5px;padding:5px 13px;background:#f6f9fb}.lightbox img{display:block;max-width:100%;max-height:82vh;margin:auto;object-fit:contain}
@media(max-width:1100px){.layout{grid-template-columns:210px minmax(0,1fr)}.sidebar{padding:28px 18px}.content{padding:28px 24px}.metrics{grid-template-columns:repeat(3,minmax(0,1fr))}article{padding:22px}.hero h1{font-size:28px}}
@media(max-width:780px){.layout{display:block}.sidebar{display:none}.content{padding:23px 16px}.hero h1{font-size:25px}.metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.metric{padding:13px}.metric strong{font-size:25px}article{padding:18px 15px}.mobile-toc{display:block;border:1px solid var(--line);border-radius:6px;background:white;padding:10px 13px;margin:17px 0}.mobile-toc .toc a{color:var(--ink);padding:6px}.mobile-toc .toc a:hover{background:#edf4f7}.reading-tools label{display:block;width:100%}.reading-tools input{display:block;width:100%;margin-top:7px}h2{font-size:21px}.figure{padding:5px}th,td{padding:8px 10px}.figure>span{padding:8px}.lightbox{padding:12px}}
@media print{@page{size:A4;margin:14mm}html{scroll-behavior:auto}body{background:white;font-size:10pt;color:#172d40}.layout{display:block}.sidebar,.actions,.reading-tools,.mobile-toc,.lightbox,.figure small,.font-license{display:none!important}.content{padding:0}.hero h1{font-size:22pt}.hero p{font-size:10pt}.metrics{grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}.metric{padding:8px;border-radius:0}.metric strong{font-size:18pt}.metric span{font-size:8pt}article{border:0;padding:0;border-radius:0}h2{font-size:15pt;margin-top:25px;break-after:avoid}p{orphans:3;widows:3}.table-card{border:0;overflow:visible}.table-scroll{overflow:visible}table{font-size:8pt;line-height:1.5;table-layout:auto}thead{display:table-header-group}th,td,th:first-child,td:first-child{min-width:0;padding:5px 6px;white-space:normal!important;overflow-wrap:anywhere}tbody tr{break-inside:avoid}tbody tr[hidden]{display:table-row!important}.figure{break-inside:avoid;border:0;padding:0;background:white}.figure img{max-height:180mm}.figure>span{padding:3px 0;font-size:9pt}.figure>span small{display:none}a{color:#24566f;text-decoration:none}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#f1f4f6;color:#172d40;border:1px solid #dae3e9}footer{font-size:8pt}}
</style></head><body>
<div class="layout"><aside class="sidebar"><div class="brand">PALLET / RESEARCH REPORT</div><b>托盘目标<br>多属性聚类</b><nav class="toc" aria-label="报告章节">__TOC__</nav><p class="note">所有细类属性均为候选。<br>可见三维范围不代表完整规格。</p></aside>
<main class="content"><header class="hero"><div class="eyebrow">聚类结果 · 候选属性 · 复核依据</div><h1>__TITLE__</h1><p>结合强度图外观与点云几何，提供候选结构、证据等级与采集条件分析。</p><div class="actions"><a class="action primary" href="__GALLERY__">浏览目标图册</a><a class="action" href="__CSV__">逐目标 CSV</a><a class="action" href="__SOURCE__">Markdown 原文</a><button class="action" id="print-report" type="button">打印 / 保存 PDF</button></div></header>
<div class="metrics">__METRICS__</div><details class="mobile-toc"><summary>章节目录</summary><nav class="toc">__TOC__</nav></details>
<div class="reading-tools"><label for="table-search">筛选表格<input type="search" id="table-search" placeholder="簇编号、结构候选或质量状态" autocomplete="off"></label><small>筛选仅影响表格行；打印保留完整报告。</small></div>
<article>__BODY__</article><footer>__FOOTER__</footer></main></div>
<dialog class="lightbox" id="figure-dialog"><div class="dialog-bar"><strong id="figure-title"></strong><button type="button" id="close-figure">关闭</button></div><img id="figure-large" alt=""></dialog>
<script>
const search=document.getElementById('table-search');
const tables=[...document.querySelectorAll('.table-card')].map(card=>({card,rows:[...card.querySelectorAll('tbody tr')]}));
search.addEventListener('input',()=>{const term=search.value.trim().toLocaleLowerCase();for(const table of tables){let visible=0;for(const row of table.rows){row.hidden=!!term&&!row.textContent.toLocaleLowerCase().includes(term);if(!row.hidden)visible++}table.card.querySelector('.row-count').textContent=term?`${visible} / ${table.rows.length} 行`:`${table.rows.length} 行`}});
document.getElementById('print-report').onclick=()=>window.print();
const dialog=document.getElementById('figure-dialog');for(const button of document.querySelectorAll('.figure'))button.onclick=()=>{const source=button.querySelector('img'),large=document.getElementById('figure-large');large.src=source.src;large.alt=source.alt;document.getElementById('figure-title').textContent=source.alt;dialog.showModal()};document.getElementById('close-figure').onclick=()=>dialog.close();dialog.onclick=event=>{if(event.target===dialog){const bounds=dialog.getBoundingClientRect();if(event.clientX<bounds.left||event.clientX>bounds.right||event.clientY<bounds.top||event.clientY>bounds.bottom)dialog.close()}};
const chapters=[...document.querySelectorAll('article h2')],links=[...document.querySelectorAll('.sidebar .toc a')];if('IntersectionObserver' in window){const observer=new IntersectionObserver(entries=>{for(const entry of entries)if(entry.isIntersecting){for(const link of links)link.classList.toggle('active',link.hash==='#'+entry.target.id)}},{rootMargin:'-10% 0px -65% 0px'});chapters.forEach(chapter=>observer.observe(chapter))}
</script></body></html>'''
    replacements = {'__TITLE__': html.escape(title), '__FONT__': font_style,
                    '__TOC__': toc, '__GALLERY__': local('gallery.html'), '__CSV__': local('targets.csv'),
                    '__SOURCE__': source_link, '__METRICS__': cards, '__BODY__': body, '__FOOTER__': footer}
    # One replacement pass keeps source text containing template-like strings literal.
    import re
    document = re.sub('|'.join(map(re.escape, replacements)), lambda match: replacements[match[0]], document)
    destination.parent.mkdir(parents=True, exist_ok=True)
    temporary = destination.with_suffix(destination.suffix+'.tmp')
    temporary.write_text(document)
    temporary.replace(destination)
    if any(sha256(path) != expected for path,expected in assets.items()):
        raise ValueError('Report inputs changed during HTML generation')
    record = {'kind': 'html_reading_edition', 'source': str(source), 'source_sha256': source_hash,
              'html': str(destination), 'html_sha256': sha256(destination),
              'renderer_sha256': sha256(__file__), 'sections': len(navigation), 'tables': len(table_rows),
              'table_rows': table_rows, 'embedded_assets': {str(p):h for p,h in assets.items() if p != source},
              'original_inputs_unchanged': True}
    destination.with_name(destination.stem+'_manifest.json').write_text(json.dumps(record, ensure_ascii=False, indent=2)+'\n')
    return record


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('source', nargs='?', help='Source Markdown report; defaults to latest completed analysis.')
    parser.add_argument('--output', help='HTML destination; defaults to report_zh.html beside the source.')
    args = parser.parse_args(argv)
    source = args.source
    if not source:
        latest = Path('outputs/pallet_target_clustering_v1/latest.json')
        source = json.loads(latest.read_text())['report']
    record = build_html_report(source, args.output)
    print(json.dumps({k:record[k] for k in ('html','sections','tables','original_inputs_unchanged')}, ensure_ascii=False))


if __name__ == '__main__':
    main()
