#!/usr/bin/env python3
"""Prepare one reference locally: python export.py input.jpg prepared.png.
Requires Pillow. GIFs use their first frame. Prints prepared PNG geometry, bytes and SHA-256.
GIF downloads must be saved directly; never resample or convert the result.
"""
import hashlib
import json
import math
import os
import sys
from PIL import Image, ImageOps

def prepare(source, output):
    if os.path.getsize(source) > 25 * 1024 * 1024:
        raise ValueError('Input exceeds 25 MiB')
    Image.MAX_IMAGE_PIXELS = 50_000_000
    with Image.open(source) as opened:
        if opened.format not in ('JPEG', 'PNG', 'WEBP', 'GIF') or opened.format != 'GIF' and getattr(opened, 'n_frames', 1) != 1:
            raise ValueError('Use one still JPEG, PNG or WebP, or the first frame of a GIF')
        if opened.format == 'GIF':
            opened.seek(0)
        if max(opened.size) > 16384 or opened.width * opened.height > 50_000_000:
            raise ValueError('Invalid source geometry')
        image = ImageOps.exif_transpose(opened).convert('RGBA')
        if opened.info.get('icc_profile'):
            from PIL import ImageCms
            import io
            image = ImageCms.profileToProfile(image, ImageCms.ImageCmsProfile(io.BytesIO(opened.info['icc_profile'])), ImageCms.createProfile('sRGB'), outputMode='RGBA')
        scale = min(1, 3840 / max(image.size), math.sqrt(7_000_000 / (image.width * image.height)))
        dimensions = (max(1, math.floor(image.width * scale)), max(1, math.floor(image.height * scale)))
        if image.size != dimensions:
            image = image.resize(dimensions, Image.Resampling.LANCZOS)
        image.save(output, format='PNG')
    with open(output, 'rb') as handle:
        data = handle.read(32 * 1024 * 1024 + 1)
    if len(data) > 32 * 1024 * 1024:
        raise ValueError('Prepared PNG exceeds 32 MiB')
    return {'width': dimensions[0], 'height': dimensions[1], 'uploadBytes': len(data), 'uploadSha256': hashlib.sha256(data).hexdigest()}

def run(action, source, _plan_file, output):
    if action != 'prepare':
        raise ValueError('Only reference preparation is supported')
    return prepare(source, output)

if __name__ == '__main__':
    if len(sys.argv) != 3:
        raise SystemExit(__doc__)
    print(json.dumps(prepare(*sys.argv[1:])))
