"""合成离线样本检查。与同名 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):
    def cut(unit,start,end):
        if type(start) is not int or type(end) is not int or start<0 or end<=start:raise ValueError('区间错误')
        text=d['source']
        if unit=='codepoint':
            if end>len(text):raise ValueError('越界')
            return text[start:end]
        enc,width=('utf-16-le',2) if unit=='utf16' else ('utf-8',1)
        b=text.encode(enc)
        if end*width>len(b):raise ValueError('越界')
        return b[start*width:end*width].decode(enc,'strict')
    assert sha(d['source'].encode())==d['source_sha256']
    out={u:cut(u,*coords) for u,coords in d['coordinates'].items()}
    assert all(x==d['quote'] for x in out.values())
    assert rejected(lambda:cut('utf8',2,4))
    assert sha((d['source']+'改版').encode())!=d['source_sha256']
    return {'quotes':out,'wrong_unit_rejected':True,'changed_source_rejected':True}

if __name__=='__main__':
    base=Path(__file__).resolve().parent
    data=json.loads((base/'a012.json').read_text('utf-8'))
    result=verify(data,base)
    print(json.dumps({'id':'A012','passed':True,'result':result},ensure_ascii=True))
