#!/usr/bin/env python3
"""Compact Make Me a Hanzi graphics.txt medians for local shape suggestions.

Only graphics.txt is used (Arphic Public License), not dictionary.txt (LGPL).
No recognizer implementation is imported. The binary contains normalized
stroke samples and spatial features; it is derivative data under the APL.
Usage: python3 Tools/build-handwriting-templates.py graphics.txt output.bin
See Shared/HandwritingData/PROVENANCE.txt for revision, license and format.
"""

import json
import math
from pathlib import Path
import struct
import sys

SAMPLES = 8
GRID = 8


def sample(points):
    lengths = [0.0]
    for a, b in zip(points, points[1:]):
        lengths.append(lengths[-1] + math.hypot(b[0] - a[0], b[1] - a[1]))
    if lengths[-1] < 1e-6:
        return [points[0]] * SAMPLES
    result = []
    segment = 1
    for i in range(SAMPLES):
        distance = lengths[-1] * i / (SAMPLES - 1)
        while segment < len(points) - 1 and lengths[segment] < distance:
            segment += 1
        span = lengths[segment] - lengths[segment - 1]
        fraction = (distance - lengths[segment - 1]) / span if span else 0
        a, b = points[segment - 1], points[segment]
        result.append((a[0] + (b[0] - a[0]) * fraction,
                       a[1] + (b[1] - a[1]) * fraction))
    return result


def normalize(strokes):
    points = [p for stroke in strokes for p in stroke]
    min_x = min(p[0] for p in points)
    min_y = min(p[1] for p in points)
    width = max(p[0] for p in points) - min_x
    height = max(p[1] for p in points) - min_y
    scale = 0.9 / max(width, height, 1)
    dx = (1 - width * scale) / 2 - min_x * scale
    dy = (1 - height * scale) / 2 - min_y * scale
    return [sample([(x * scale + dx, y * scale + dy) for x, y in stroke])
            for stroke in strokes]


def features(strokes):
    values = [0.0] * (GRID * GRID)
    for stroke in strokes:
        for a, b in zip(stroke, stroke[1:]):
            for step in range(4):
                t = step / 4
                x = (a[0] + (b[0] - a[0]) * t) * (GRID - 1)
                y = (a[1] + (b[1] - a[1]) * t) * (GRID - 1)
                ix, iy = int(x), int(y)
                fx, fy = x - ix, y - iy
                for gx, gy, weight in ((ix, iy, (1-fx)*(1-fy)),
                                       (ix+1, iy, fx*(1-fy)),
                                       (ix, iy+1, (1-fx)*fy),
                                       (ix+1, iy+1, fx*fy)):
                    if 0 <= gx < GRID and 0 <= gy < GRID:
                        values[gy * GRID + gx] += weight
    norm = math.sqrt(sum(v*v for v in values)) or 1
    return bytes(round(v / norm * 255) for v in values)


def main():
    if len(sys.argv) != 3:
        raise SystemExit("usage: build-handwriting-templates.py graphics.txt output.bin")
    records = []
    for line in Path(sys.argv[1]).read_text().splitlines():
        item = json.loads(line)
        strokes = [[(x, 900-y) for x, y in stroke] for stroke in item['medians'] if stroke]
        if not strokes or len(strokes) > 64 or len(item['character']) != 1:
            continue
        normalized = normalize(strokes)
        record = bytearray(struct.pack('<IB3x', ord(item['character']), len(strokes)))
        record.extend(features(normalized))
        for stroke in normalized:
            for x, y in stroke:
                record.extend((round(x * 255), round(y * 255)))
        records.append(record)
    output = bytearray(b'13HW\x01\x08\x08\x00')
    output.extend(struct.pack('<I', len(records)))
    notice = (
        'Modified by 13Type on 2026-09-30: Make Me a Hanzi graphics.txt medians '
        'were normalized, resampled to eight points per stroke and converted '
        'to spatial features and a compact binary format. Source revision '
        'bddc96d41bef78427ed0e034e9f7e31d71fd1b92. Derived from Arphic fonts, '
        'Copyright (C) 1999 Arphic Technology Co., Ltd. This derivative data '
        'is freely redistributable and modifiable under the Arphic Public '
        'License; see the unaltered ARPHICPL.TXT distributed with this file.'
    ).encode('utf-8')
    output.extend(struct.pack('<I', len(notice)))
    output.extend(notice)
    for record in records:
        output.extend(record)
    destination = Path(sys.argv[2])
    destination.parent.mkdir(parents=True, exist_ok=True)
    destination.write_bytes(output)
    print(f'{len(records)} character templates; {len(output):,} bytes')


if __name__ == '__main__':
    main()
