#!/usr/bin/env python3
"""Retain original OFL fonts from pinned official releases; never modify fonts."""
import datetime
import hashlib
import io
import json
from pathlib import Path
import shutil
import subprocess
import zipfile
from fontTools.ttLib import TTFont, TTCollection

BASE = Path(__file__).resolve().parents[1]
OUT = BASE / 'fonts/multilingual'
OUT.mkdir(parents=True, exist_ok=True)
old = json.loads((BASE / 'fonts/manifest.json').read_text())
cache = Path(old['privateCache']).parent / 'multilingual-fonts'
cache.mkdir(exist_ok=True)
sha = lambda b: hashlib.sha256(b).hexdigest()
records, sources = [], []

def fetch(url, name, size=None, sha256=None, git_blob=None):
    p = cache / name
    if not p.exists():
        subprocess.run(['curl', '--fail', '--location', '--retry', '2', '--silent',
                        '--show-error', '--max-time', '180', url, '-o', str(p)], check=True)
    b = p.read_bytes()
    if size is not None:
        assert len(b) == size, name
    if sha256:
        assert sha(b) == sha256, name
    if git_blob:
        assert hashlib.sha1(b'blob ' + str(len(b)).encode() + b'\0' + b).hexdigest() == git_blob, name
    sources.append({'url': url, 'name': name, 'bytes': len(b), 'sha256': sha(b), 'gitBlob': git_blob})
    return b

def record(name, b, source, license_file):
    fonts = TTCollection(io.BytesIO(b)).fonts if b[:4] == b'ttcf' else [TTFont(io.BytesIO(b))]
    faces = []
    for font in fonts:
        names = lambda n: sorted({x.toUnicode() for x in font['name'].names if x.nameID == n})
        assert font['OS/2'].fsType == 0, name
        faces.append({'family': names(1), 'style': names(2), 'postscript': names(6),
                      'copyright': names(0), 'version': names(5), 'licenseMetadata': names(13),
                      'licenseUrl': names(14), 'mappedCodepoints': len(font.getBestCmap()),
                      'fsType': font['OS/2'].fsType})
        font.close()
    (cache / name).write_bytes(b)
    records.append({'name': name, 'bytes': len(b), 'sha256': sha(b), 'license': 'OFL-1.1',
                    'fsType': 0, 'unmodifiedFontBytes': True, 'source': source,
                    'licenseFile': license_file, 'faces': faces})

for f in old['files']:
    b = (Path(old['privateCache']) / f['name']).read_bytes()
    assert len(b) == f['bytes'] and sha(b) == f['sha256']
    shutil.copyfile(Path(old['privateCache']) / f['name'], cache / f['name'])
    records.append(f)

cjk = [
    ('Sans', '523d033d6cb47f4a80c58a35753646f5c3608a78', 'Regular', 19484784, 'a2033d0e4e53f568c3f418a7d5d8c951af3f76c1'),
    ('Sans', '523d033d6cb47f4a80c58a35753646f5c3608a78', 'Bold', 20050760, 'ce48b99a84eb3300774353f1f15ce686e53b6734'),
    ('Serif', '9b0f1436e455d902de067a2501422e5dc71ad16b', 'Regular', 26411360, 'e72653a3a41fc9a8930e0cb40af310c4472a753b'),
    ('Serif', '9b0f1436e455d902de067a2501422e5dc71ad16b', 'Bold', 27397052, '1a313a7e4f8dbb97c5bbb8b0f949dc48d55ec233'),
]
for family, commit, weight, size, blob in cjk:
    stem = f'Noto{family}CJK-{weight}.ttc'
    url = f'https://raw.githubusercontent.com/notofonts/noto-cjk/{commit}/{family}/OTC/{stem}'
    license_name = f'Noto{family}CJK-OFL.txt'
    license_path = 'LICENSE' if family == 'Sans' else 'Serif/LICENSE'
    lic = fetch(f'https://raw.githubusercontent.com/notofonts/noto-cjk/{commit}/{license_path}', license_name)
    assert b'SIL OPEN FONT LICENSE Version 1.1' in lic
    (OUT / license_name).write_bytes(lic)
    record(stem, fetch(url, stem, size=size, git_blob=blob), url, license_name)

for family, size, digest in [
    ('Sans', 4720990, 'af889cc673fc714060ce5e4e088fbad32aa4c0571a19958efeaff128a22da485'),
    ('Serif', 5733486, '89e3c04bfc54d9a5dd0aec660bf974ad46df38385df7d9397c083482d515049a')
]:
    stem = f'Noto{family}Thai'
    tag = stem + '-v2.002'
    url = f'https://github.com/notofonts/thai/releases/download/{tag}/{tag}.zip'
    archive = fetch(url, tag + '.zip', size=size, sha256=digest)
    with zipfile.ZipFile(io.BytesIO(archive)) as z:
        license_name = stem + '-OFL.txt'
        lic = z.read('OFL.txt')
        assert b'SIL OPEN FONT LICENSE Version 1.1' in lic
        (OUT / license_name).write_bytes(lic)
        for weight in ['Regular', 'Bold']:
            name = f'{stem}-{weight}.ttf'
            member = f'{stem}/hinted/ttf/{name}'
            record(name, z.read(member), url + '#' + member, license_name)

report = {'checkedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(),
          'producerSha256': sha(Path(__file__).read_bytes()),
          'baselineManifestSha256': sha((BASE / 'fonts/manifest.json').read_bytes()),
          'privateCache': str(cache), 'sources': sources, 'files': records,
          'method': '38 unchanged baseline fonts plus original regular/bold Noto CJK collections covering JP/KR/SC/TC/HK and original hinted Thai sans/serif fonts. No font subsetting, renaming, conversion or binary modification. Browser layout/glyph/shaping validation is a separate gate.'}
(OUT / 'manifest.json').write_text(json.dumps(report, indent=2, ensure_ascii=False) + '\n')
print(json.dumps({'manifest': str(OUT / 'manifest.json'), 'fonts': len(records), 'bytes': sum(x['bytes'] for x in records)}))
