"""合成离线样本检查。与同名 JSON 及文中列出的附件放在同一目录运行。"""
from pathlib import Path, PurePosixPath
import base64, hashlib, io, inspect, json, math, re, subprocess, sys, tempfile, wave, zipfile
from collections import Counter, defaultdict
from datetime import date, datetime
from decimal import Decimal
sys.dont_write_bytecode=True

def sha(b): return hashlib.sha256(b).hexdigest()
def rejected(fn):
    try: fn()
    except (ValueError,TypeError,KeyError,UnicodeError,OverflowError): return True
    return False

def git(root,*args,input=None,check=True):
    r=subprocess.run(['git','-c','core.autocrlf=false',*args],cwd=root,input=input,capture_output=True,check=check)
    return r

def verify(d,base):
    from markdown_it import MarkdownIt
    from importlib.metadata import version
    parser=MarkdownIt('commonmark').enable('table')
    def cell(row,escape=True):
        value=row['value'].replace('\n','／')
        if '`' in value:raise ValueError('本示例不接收反引号')
        if escape:value=value.replace(chr(92),chr(92)*2).replace('|',chr(92)+'|')
        return '`'+value+'`' if row['code'] else value
    def render(escape=True):
        return '| 名称 | 值 |\n| --- | --- |\n'+'\n'.join('| '+r['name']+' | '+cell(r,escape)+' |' for r in d['rows'])+'\n'
    def cells(markdown):
        tokens=parser.parse(markdown);rows=[];current=None;body=False;in_cell=False
        for token in tokens:
            if token.type=='tbody_open':body=True
            elif token.type=='tbody_close':body=False
            elif body and token.type=='tr_open':current=[]
            elif body and token.type=='td_open':in_cell=True
            elif body and token.type=='td_close':in_cell=False
            elif body and in_cell and token.type=='inline':current.append(''.join(x.content for x in token.children if x.type in ('text','code_inline')))
            elif body and token.type=='tr_close':rows.append(current)
        return rows
    markdown=render();out=cells(markdown)
    assert len(out)==3 and all(len(r)==2 for r in out)
    assert [r[1] for r in out]==d['expected_display'];assert [r[1] for r in cells(render(False))]!=d['expected_display']
    assert d['rows'][2]['value']=='第一行\n第二行'
    return {'table_markdown':markdown,'parsed_cells':out,'raw_json_preserved':True,'parser':'markdown-it-py '+version('markdown-it-py'),'unescaped_counterexample_failed':True}

if __name__=='__main__':
    base=Path(__file__).resolve().parent
    data=json.loads((base/'a044.json').read_text('utf-8'))
    result=verify(data,base)
    print(json.dumps({'id':'A044','passed':True,'result':result},ensure_ascii=True))
