"""Version 1 metadata contract. Never installs a font or modifies its input."""
import json
import sys
import struct
if sys.platform == 'linux':
    import resource
    resource.setrlimit(resource.RLIMIT_AS, (256 * 1024**2, 256 * 1024**2))
    resource.setrlimit(resource.RLIMIT_CPU, (10, 10))
from fontTools.ttLib import TTFont

def inspect(path):
    with open(path, 'rb') as source:
        if source.read(4) not in (b'\x00\x01\x00\x00', b'OTTO'):
            raise ValueError('Only static TrueType/OpenType fonts are supported.')
        source.seek(0, 2)
        length = source.tell()
        if length > 10485760 or length < 12:
            raise ValueError('Invalid font size.')
        source.seek(4)
        count = struct.unpack('>H', source.read(2))[0]
        if count < 1 or count > 256 or 12 + count * 16 > length:
            raise ValueError('Invalid font table directory.')
        source.seek(12)
        for _ in range(count):
            tag, checksum, offset, size = struct.unpack('>4sIII', source.read(16))
            if offset + size > length:
                raise ValueError('Font table exceeds the file.')
    with TTFont(path, lazy=False, checkChecksums=2) as font:
        if 'fvar' in font:
            raise ValueError('Variable fonts are not supported.')
        for tag in font.keys():
            if tag != 'GlyphOrder':
                font[tag]
        names = font['name']
        family = names.getBestFamilyName()
        if not family:
            raise ValueError('Font family metadata is missing.')
        cmap = font.getBestCmap() or {}
        aliases = sorted({record.toUnicode().strip() for record in names.names if record.nameID in (1, 4, 6, 16) and record.toUnicode().strip()})
        return {'version': 1, 'family': family, 'aliases': aliases, 'full_name': names.getDebugName(4) or family, 'style': names.getBestSubFamilyName() or 'Regular',
                'weight': font['OS/2'].usWeightClass if 'OS/2' in font else 400,
                'arabic_coverage': all(code in cmap for code in [*range(0x0621, 0x063B), *range(0x0641, 0x064B)]),
                'arabic_character_count': sum(code in cmap for code in range(0x0600, 0x0700))}

try:
    print(json.dumps(inspect(sys.argv[1]), ensure_ascii=False))
except Exception:
    print(json.dumps({'error': 'The font is malformed or unsupported.'}))
    sys.exit(1)
