#!/usr/bin/env python3
"""
Fetches a Photos.app thumbnail by UUID from iCloud if needed.
Usage: python3 fetch_icloud_thumb.py <UUID> <output_path.jpg>
Exit 0 = success, 1 = not found, 2 = fetch failed
"""
import sys, os

def fetch(uuid_str, out_path):
    try:
        import Photos as PK
        import AppKit
    except ImportError:
        print("ERROR: pyobjc-framework-Photos not installed", file=sys.stderr)
        return 2

    result = PK.PHAsset.fetchAssetsWithLocalIdentifiers_options_([uuid_str], None)
    if result.count() == 0:
        print(f"NOT_FOUND: {uuid_str}", file=sys.stderr)
        return 1

    asset = result.objectAtIndex_(0)

    opts = PK.PHImageRequestOptions.new()
    opts.setNetworkAccessAllowed_(True)
    opts.setDeliveryMode_(PK.PHImageRequestOptionsDeliveryModeHighQualityFormat)
    opts.setSynchronous_(True)

    done = [None]
    def handler(image, info):
        done[0] = image

    PK.PHImageManager.defaultManager().requestImageForAsset_targetSize_contentMode_options_resultHandler_(
        asset,
        AppKit.NSMakeSize(400, 400),
        PK.PHImageContentModeAspectFill,
        opts,
        handler
    )

    if done[0] is None:
        print(f"FETCH_FAILED: {uuid_str}", file=sys.stderr)
        return 2

    try:
        tiff = done[0].TIFFRepresentation()
        bmp = AppKit.NSBitmapImageRep.imageRepWithData_(tiff)
        data = bmp.representationUsingType_properties_(
            AppKit.NSJPEGFileType,
            {AppKit.NSImageCompressionFactor: 0.82}
        )
        os.makedirs(os.path.dirname(out_path), exist_ok=True) if os.path.dirname(out_path) else None
        with open(out_path, 'wb') as f:
            f.write(bytes(data))
        print(f"OK {os.path.getsize(out_path)}", flush=True)
        return 0
    except Exception as e:
        print(f"SAVE_FAILED: {e}", file=sys.stderr)
        return 2


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: fetch_icloud_thumb.py <UUID> <output.jpg>", file=sys.stderr)
        sys.exit(1)
    sys.exit(fetch(sys.argv[1], sys.argv[2]))
