#!/usr/bin/env python3
"""Prepare only. The founder reviews and confirms in the browser. Python stdlib."""
import argparse, base64, json, os, pathlib, urllib.request, urllib.error
API = 'https://kghdjjjwnpanzpuagqjb.supabase.co/functions/v1/launch-public'
def request(action, data, key=None):
    payload = json.dumps(dict(data, action=action)).encode()
    headers = {'Content-Type': 'application/json'}
    if key: headers['Authorization'] = 'Bearer ' + key
    try:
        with urllib.request.urlopen(urllib.request.Request(API, data=payload, headers=headers), timeout=30) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        raise SystemExit(json.load(error).get('error', 'Request failed'))
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('action', choices=['prepare'])
    parser.add_argument('product_json', type=pathlib.Path)
    parser.add_argument('--image', required=True, action='append', type=pathlib.Path, help='Repeat for up to 6 images; first is the cover. Recommend 1080 x 1920 px (9:16); other ratios display center-cropped')
    parser.add_argument('--video', type=pathlib.Path, help='Optional MP4 demo up to 5 MB, recommended 1080 x 1920 px (9:16)')
    parser.add_argument('--receipt', type=pathlib.Path, default=pathlib.Path('launch-private-receipt.json'))
    parser.add_argument('--key-file', type=pathlib.Path, help='Existing private receipt for a product revision')
    args = parser.parse_args()
    if args.receipt.exists(): raise SystemExit('Receipt already exists. Use it to resume, or choose a new --receipt path. Do not overwrite your key.')
    product = json.loads(args.product_json.read_text())
    if len(args.image)>6: raise SystemExit('Use at most 6 images.')
    media=[(i,'image',p.read_bytes()) for i,p in enumerate(args.image)]
    if args.video: media.append((6,'video',args.video.read_bytes()))
    if any(len(data)>5*1024*1024 for _,_,data in media): raise SystemExit('Each media file must be at most 5 MB.')
    key = json.loads(args.key_file.read_text())['managementKey'] if args.key_file else None
    print('Media: portrait 9:16, recommended 1080 x 1920 px. Other ratios are displayed with a centered crop; originals are retained.')
    print('Review the cropped preview of every image and video before confirming.')
    print('This command sends product details and the image to FounderOmni Showcase to create a PRIVATE DRAFT.')
    print('Run it only after the founder authorizes this transmission. It does not confirm or publish a listing.')
    receipt = request('prepare', product, key)
    # Save the capability before upload so a failed upload cannot lose access.
    fd = os.open(args.receipt, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, 'w') as stream: json.dump(receipt, stream, indent=2)
    for slot,kind,data in media:
        request('upload', {'submissionId': receipt['submissionId'], 'slot':slot,'mediaType':kind,'resetMedia':slot==0,'mediaBase64':base64.b64encode(data).decode()}, receipt['managementKey'])
    print('Draft prepared. Give this PRIVATE review link to the founder:')
    print(receipt['reviewUrl'])
    print('Founder: review the preview, request the email code, and confirm submission yourself.')
    print('Keep the receipt private:', args.receipt)
if __name__ == '__main__': main()
