"""贾影档 小字版 (Jia Ying Dang Text) — full build.

Applies the V1.2 "coarse grain" ink-loss treatment (user-approved at 64/100 px)
to every CJK glyph of the released V1.1 Archive Black, as a separately named
family. The V1.1 font itself stays the large-title version, unchanged.

Fixes vs. the handoff experiment: quadratic outlines are flattened before
rasterizing (the old full build died at ~16.5k glyphs), composites are
decomposed, each glyph is isolated so one failure never kills the whole run,
and work is checkpointed so a restart resumes.
"""
import sys, json, math, hashlib, time, pickle, argparse, traceback
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent / 'exp'))
import numpy as np, cv2
from fontTools.ttLib import TTFont
from fontTools.pens.recordingPen import DecomposingRecordingPen
from revise_fonts import FlattenPen, mask_coords
import tex2
from fontTools.pens.ttGlyphPen import TTGlyphPen
PARAMS = dict(tex2.DEFAULT, zone_cell=45, zone_thr=0.25, zone_gain=0.8, zone_void=0.32, base_void=0.16, edge_amp=0.85, grain_cell=5, halo_gain=0.5, streak=0.35)
EPS, MINAREA = 1.0, 4
SCALE = 0.6  # mask px per font unit
def scaled(P, k):
    q = dict(P)
    for key in ('edge_cell','patch_cell','zone_cell','grain_cell'): q[key] = max(2, int(round(P[key]*k)))
    for key in ('edge_soft','edge_halo','min_wall'): q[key] = P[key]*k
    q['crumb'] = P['crumb']*k*k
    q['streak_a'] = max(2, round(3*k)); q['streak_b'] = round(45*k)
    return q
PS = scaled(PARAMS, SCALE)

def vectorize(mask, x0, y1, unit):
    contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    pen = TTGlyphPen(None); skip = set()
    for i, c in enumerate(contours):
        par = int(hierarchy[0, i, 3])
        if par in skip or abs(cv2.contourArea(c)) < MINAREA: skip.add(i); continue
        p = cv2.approxPolyDP(c, EPS, True)[:, 0, :].astype(np.float64)
        if len(p) < 3: skip.add(i); continue
        p[:, 0] = (p[:, 0] + x0) * unit; p[:, 1] = (y1 - p[:, 1]) * unit
        depth = 0; q = par
        while q >= 0: depth += 1; q = int(hierarchy[0, q, 3])
        area = np.sum(p[:, 0] * np.roll(p[:, 1], -1) - p[:, 1] * np.roll(p[:, 0], -1))
        if (area < 0) != (depth % 2 == 0): p = p[::-1]
        p = np.round(p).astype(int)
        pen.moveTo(tuple(p[0]))
        for pt in p[1:]: pen.lineTo(tuple(pt))
        pen.closePath()
    return pen.glyph()

cv2.setNumThreads(1)
HERE = Path(__file__).resolve().parent
SRC = HERE / 'v1.1/dang/JiaYingDang-ArchiveBlack.ttf'
OUT = HERE / 'out'
TESTS = ['档案解密','往事追踪','最后来信','沉默证据','追凶千里','一锤定音','孤胆英雄','正义归来','昆明警方',
         '神速破案','北京大兴摔童案','穿山贾说了啥','警察悬疑露霜藏赢','旧案重启','尘封往事','刑侦八虎']

_font = None
def _get_font():
    global _font
    if _font is None: _font = TTFont(SRC)
    return _font

def outline(name):
    f = _get_font(); gs = f.getGlyphSet()
    rec = DecomposingRecordingPen(gs); gs[name].draw(rec)
    pen = FlattenPen(); rec.replay(pen)
    if pen.points: pen._closePath()
    coords = []; ends = []
    for c in pen.contours:
        if len(c) < 3: continue
        coords.extend(c); ends.append(len(coords) - 1)
    return coords, ends

def work(name):
    try:
        f = _get_font(); unit = f['head'].unitsPerEm / 1000 / SCALE
        coords, ends = outline(name)
        if not ends: return name, None, {'skip': 'empty'}
        mask, x0, y1 = mask_coords(coords, ends, [1]*len(coords), unit)
        seed = int(hashlib.sha256(name.encode()).hexdigest()[:8], 16)
        mask = tex2.texture(mask, seed, PS); stats = {}
        g = vectorize(mask, x0, y1, unit)
        if not g.numberOfContours: return name, None, {'skip': 'vanished'}
        g.recalcBounds(None)
        return name, g.compile(None, recalcBBoxes=False), stats
    except Exception as e:
        return name, None, {'error': repr(e), 'tb': traceback.format_exc()[-600:]}

def main():
    ap = argparse.ArgumentParser(); ap.add_argument('--preview', action='store_true'); ap.add_argument('--workers', type=int, default=2)
    a = ap.parse_args(); OUT.mkdir(exist_ok=True)
    font = TTFont(SRC); cmap = font.getBestCmap()
    if a.preview:
        names = sorted({cmap[ord(c)] for c in ''.join(TESTS) if ord(c) in cmap})
    else:
        names = sorted({n for cp, n in cmap.items() if 0x3400 <= cp <= 0x9fff or 0x20000 <= cp <= 0x323af or 0xf900 <= cp <= 0xfaff})
    ck = OUT / ('ck-v12p.pkl' if a.preview else 'ck-v12.pkl')
    done = pickle.loads(ck.read_bytes()) if ck.exists() else {}
    todo = [n for n in names if n not in done]
    print('glyphs', len(names), 'todo', len(todo), flush=True)
    t0 = time.monotonic()
    from multiprocessing import Pool
    with Pool(a.workers) as pool:
        for i, res in enumerate(pool.imap_unordered(work, todo, chunksize=16), 1):
            done[res[0]] = (res[1], res[2])
            if i % 1000 == 0:
                ck.write_bytes(pickle.dumps(done)); print(i, len(todo), round(time.monotonic()-t0), flush=True)
    ck.write_bytes(pickle.dumps(done))
    assemble(font, done, a.preview)

def assemble(font, done, preview):
    unit = font['head'].unitsPerEm / 1000; glyf = font['glyf']; errors = []; changed = 0; stats = []
    import struct
    from fontTools.ttLib.tables._g_l_y_f import Glyph
    for name, (data, st) in done.items():
        if data is None:
            if 'error' in st: errors.append((name, st['error']))
            continue
        adv, _ = font['hmtx'][name]
        xmin = struct.unpack('>hhhhh', data[:10])[1]
        glyf[name] = Glyph(data); font['hmtx'].metrics[name] = (adv, xmin); changed += 1
    print('changed', changed, 'errors', len(errors), errors[:5], flush=True)
    # Names: separate family so it installs side by side with V1.1.
    nm = font['name']
    for rec in nm.names:
        if rec.nameID in (3, 5):
            rec.string = rec.toUnicode().replace('1.100', '1.200')
        if rec.nameID == 10:
            rec.string = 'OFL display adaptation of Source Han Serif CN Heavy. V1.2 letterpress wear visible at all sizes.'
    font['head'].fontRevision = 1.2
    if preview:
        from fontTools import subset
        o = subset.Options(); o.layout_features = []; o.name_IDs = ['*']; o.name_languages = ['*']
        s = subset.Subsetter(o); s.populate(text=''.join(TESTS) + '0123456789'); s.subset(font)
        dest = OUT / 'JiaYingDang-v12-preview.ttf'
    else:
        dest = OUT / 'JiaYingDang-ArchiveBlack.ttf'
    font.save(dest)
    (OUT / ('report-preview.json' if preview else 'report-full.json')).write_text(json.dumps(dict(
        changed=changed, errors=errors, mean_ink_loss=round(float(np.mean(stats)) if stats else 0, 4),
        parent_sha256=hashlib.sha256(SRC.read_bytes()).hexdigest()), ensure_ascii=False, indent=1))
    print('saved', dest, dest.stat().st_size, flush=True)

if __name__ == '__main__':
    main()
