#!/usr/bin/env python3
"""Extract only audited, unmodified OFL/Apache fonts to a private runtime cache."""
from pathlib import Path
from io import BytesIO
import datetime
import hashlib
import importlib.metadata
import json
import os
import tarfile
from fontTools.ttLib import TTFont
from lxml import html

BASE = Path(__file__).resolve().parents[1]
LOCK = json.loads((BASE / 'runtime-lock.json').read_text())
OUTPUT = Path(os.environ.get('OFFICE_BUILD_ROOT', str(Path.home() / '.cache/tabmorph/office-build'))) / 'curated-fonts'
EVIDENCE = BASE / 'fonts'
OUTPUT.mkdir(parents=True, exist_ok=True)
EVIDENCE.mkdir(exist_ok=True)
sha = lambda b: hashlib.sha256(b).hexdigest()
prefixes = ['Caladea', 'Carlito', 'LiberationMono', 'LiberationSans', 'LiberationSerif', 'NotoSans', 'NotoSerif', 'NotoKufiArabic', 'NotoNaskhArabic', 'NotoSansArabic', 'NotoSansHebrew', 'NotoSerifHebrew']
payload = Path(LOCK['files']['soffice.data']['cache']).read_bytes()
assert sha(payload) == LOCK['files']['soffice.data']['sha256']
metadata = Path(LOCK['files']['soffice.data.js.metadata']['cache']).read_bytes()
assert sha(metadata) == LOCK['files']['soffice.data.js.metadata']['sha256']
archive = Path(LOCK['files']['libreoffice-efaf067-source.tar.gz']['cache'])
assert sha(archive.read_bytes()) == LOCK['files']['libreoffice-efaf067-source.tar.gz']['sha256']
with tarfile.open(archive) as source:
    entry = next(m for m in source if m.name.endswith('/readlicense_oo/license/license.xml'))
    license_xml = source.extractfile(entry).read()
document = html.fromstring(license_xml)
for label, anchor in [('OFL-1.1', 'a__SIL_Open_Font_License__version_1_1'), ('Apache-2.0', 'a__Apache_License_version_2_0')]:
    node = document.xpath('//*[@id=$id]/ancestor::h1[1]', id=anchor)[0]
    text = [' '.join(node.itertext())]
    for sibling in node.itersiblings():
        if sibling.tag in ['hr', 'h1']:
            break
        text.append(' '.join(sibling.itertext()))
    (EVIDENCE / (label + '.txt')).write_text('\n\n'.join(text) + '\n')

rows, notices, covered = [], [], set()
for file in json.loads(metadata)['files']:
    name = Path(file['filename']).name
    if not file['filename'].startswith('/instdir/share/fonts/truetype/') or not any(name.startswith(p + '-') for p in prefixes):
        continue
    data = payload[file['start']:file['end']]
    font = TTFont(BytesIO(data))
    values = lambda key: sorted(set(n.toUnicode() for n in font['name'].names if n.nameID == key))
    terms = '\n'.join(values(13) + values(14))
    license_id = 'Apache-2.0' if name.startswith('Caladea-') else 'OFL-1.1'
    assert ('Apache License' in terms if license_id == 'Apache-2.0' else 'Open Font License' in terms)
    assert 'General Public License' not in terms and 'GPL' not in terms
    assert font['OS/2'].fsType == 0, (name, font['OS/2'].fsType)
    cmap = font.getBestCmap()
    covered.update(cmap)
    (OUTPUT / name).write_bytes(data)
    row = {'name': name, 'sourceVirtualPath': file['filename'], 'sourceOffset': [file['start'], file['end']], 'bytes': len(data), 'sha256': sha(data), 'license': license_id, 'family': values(1), 'copyright': values(0), 'version': values(5), 'licenseMetadata': values(13), 'licenseUrl': values(14), 'fsType': font['OS/2'].fsType, 'mappedCodepoints': len(cmap), 'unmodifiedFontBytes': True}
    rows.append(row)
    notices.append(name + '\n' + '\n'.join(values(0)) + '\n' + terms)
    font.close()
assert len(rows) == 38
(EVIDENCE / 'NOTICES.txt').write_text('\n\n'.join(notices) + '\n')
manifest = {
    'checkedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'producerSha256': sha(Path(__file__).read_bytes()),
    'tool': {'fontTools': importlib.metadata.version('fonttools')}, 'privateCache': str(OUTPUT),
    'sourceRuntimeDataSha256': sha(payload), 'sourceMetadataSha256': sha(metadata), 'primarySourceCommit': LOCK['sourceCommit'], 'primaryLicenseXmlSha256': sha(license_xml),
    'files': rows, 'bytes': sum(r['bytes'] for r in rows), 'mappedCodepointsUnion': len(covered),
    'selectedControlCodepoints': {c: ord(c) in covered for c in 'AéΩЖאش界कก'},
    'exclusions': 'No Culmus, LiberationSansNarrow, unresolved license, GPL/AGPL-only or other runtime resources are copied. The older runtime itself is not accepted. No font subsetting, renaming or modification.',
    'status': 'Audited candidate font bytes in private cache only. No production dependency or coverage added. New-runtime font discovery/fallback/embedding and layout remain unverified. This selection does not cover all writing systems.'
}
(EVIDENCE / 'manifest.json').write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + '\n')
print(json.dumps({'fonts': len(rows), 'bytes': manifest['bytes'], 'controls': manifest['selectedControlCodepoints']}))
