#!/usr/bin/env python3
"""Read-only PNG export inventory check. No uploads, translation or pixel decoding."""
import hashlib
import json
from pathlib import Path
import struct
import sys
import zlib


def png_info(path):
    if path.stat().st_size > 32 * 1024 * 1024:
        raise ValueError('file exceeds this checker\'s 32 MiB limit')
    data = path.read_bytes()
    if data[:8] != b'\x89PNG\r\n\x1a\n':
        raise ValueError('expected a PNG file')
    offset, header, transparency, image_data, ended = 8, None, False, False, False
    while offset < len(data):
        if offset + 12 > len(data):
            raise ValueError('truncated PNG chunk')
        length = struct.unpack('>I', data[offset:offset + 4])[0]
        kind = data[offset + 4:offset + 8]
        end = offset + 12 + length
        if end > len(data):
            raise ValueError('truncated PNG chunk data')
        body = data[offset + 8:end - 4]
        crc = struct.unpack('>I', data[end - 4:end])[0]
        if zlib.crc32(kind + body) & 0xffffffff != crc:
            raise ValueError('PNG checksum mismatch')
        if header is None:
            if kind != b'IHDR' or length != 13:
                raise ValueError('missing PNG header')
            width, height, depth, colour, compression, filtering, interlace = struct.unpack('>IIBBBBB', body)
            if not width or not height or colour not in (0, 2, 3, 4, 6):
                raise ValueError('unsupported PNG header')
            header = (width, height, colour)
        elif kind == b'IHDR':
            raise ValueError('duplicate PNG header')
        transparency |= kind == b'tRNS'
        image_data |= kind == b'IDAT' and bool(length)
        offset = end
        if kind == b'IEND':
            if length or offset != len(data):
                raise ValueError('invalid PNG end')
            ended = True
            break
    if not ended or not image_data:
        raise ValueError('missing PNG image data or end')
    return {'width': header[0], 'height': header[1],
            'alpha_or_transparency': header[2] in (4, 6) or transparency,
            'sha256': hashlib.sha256(data).hexdigest()}


def check(manifest):
    doc = json.loads(manifest.read_text(encoding='utf-8'))
    width, height = doc['profile']['width'], doc['profile']['height']
    if any(type(n) is not int or n < 1 for n in (width, height)):
        raise ValueError('profile needs positive integer width and height')
    required = doc['required']
    if not isinstance(required, dict) or not required:
        raise ValueError('required needs locale names and ordered slot lists')
    if any(not isinstance(k, str) or not isinstance(v, list) or not v or
           any(not isinstance(s, str) or not s for s in v) or len(v) != len(set(v))
           for k, v in required.items()):
        raise ValueError('required slots must be nonempty unique strings')
    wanted = {(locale, slot) for locale, slots in required.items() for slot in slots}
    base, seen, hashes, errors, warnings, files = manifest.parent.resolve(), set(), {}, [], [], {}
    for index, item in enumerate(doc['assets'], 1):
        key = (item['locale'], item['slot'])
        label = '/'.join(key)
        if key not in wanted:
            errors.append(f'{label}: undeclared locale/slot')
        if key in seen:
            errors.append(f'{label}: duplicate locale/slot')
        seen.add(key)
        try:
            path = (base / item['file']).resolve()
            if not path.is_relative_to(base):
                raise ValueError('file must stay inside the manifest folder')
            info = png_info(path)
            if (info['width'], info['height']) != (width, height):
                errors.append(f'{label}: {info["width"]}x{info["height"]}, expected {width}x{height}')
            if info['alpha_or_transparency']:
                errors.append(f'{label}: alpha channel or transparency present')
            digest = info['sha256']
            if digest in hashes:
                warnings.append(f'{label}: same PNG bytes as {hashes[digest]}; inspect whether intentional')
            else:
                hashes[digest] = label
            files[key] = {'locale': key[0], 'slot': key[1], 'file': item['file'], **info}
        except (OSError, ValueError) as exc:
            errors.append(f'{label}: {exc}')
    for locale, slot in sorted(wanted - seen):
        errors.append(f'{locale}/{slot}: missing required export')
    plan = [files[(locale, slot)] for locale, slots in required.items()
            for slot in slots if (locale, slot) in files]
    return {'ok': not errors, 'errors': errors, 'warnings': warnings, 'ordered_plan': plan,
            'limits': 'PNG metadata/inventory only. No pixel decoding, language recognition, app review or upload.'}


if __name__ == '__main__':
    try:
        if len(sys.argv) != 2:
            raise ValueError('usage: python3 check_exports.py manifest.json')
        result = check(Path(sys.argv[1]))
    except (OSError, ValueError, KeyError, TypeError) as exc:
        result = {'ok': False, 'errors': [f'invalid manifest: {exc}'], 'warnings': []}
    print(json.dumps(result, indent=2, ensure_ascii=False))
    raise SystemExit(0 if result['ok'] else 1)
