#!/usr/bin/env python3
"""Python 3.10+. Text requests use the standard library; references also need export.py and Pillow.
Each successful API generation costs one credit. No automatic replacement generations.
"""
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

BASE = 'https://ai-gif-generator.com'
MAX_RESULT = 32 * 1024 * 1024


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def edit_image(output, prompt='', input=None, key=None, expected_charge_units=0,
               send=None, wait=time.sleep):
    """Generate or resume the original job. Confirm one credit with expected_charge_units=20."""
    if not key or not input and not prompt.strip() or len(prompt.encode('utf-16-le')) // 2 > 4000:
        raise ValueError('Set AIGIFGENERATOR_API_KEY and provide text, an image, or both; text limit 4,000 characters.')
    if type(expected_charge_units) is not int or expected_charge_units < 0:
        raise ValueError('Confirm the charge using expected_charge_units.')
    output = Path(output).resolve()
    if output.suffix.lower() != '.gif':
        raise ValueError('Use a .gif output path')
    if output.exists():
        raise ValueError('Output already exists; use a new path only for an intentional new generation.')
    state_path = Path(str(output) + '.aigifgenerator.json')
    lock_path = Path(str(state_path) + '.lock')
    try:
        lock = os.open(lock_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    except FileExistsError:
        raise ValueError('Another process owns this output. If it stopped, remove only the .lock file; keep the recovery JSON.') from None
    prepared_directory = None
    try:
        with os.fdopen(lock, 'w', encoding='utf-8') as handle:
            json.dump({'pid': os.getpid(), 'createdAt': int(time.time() * 1000)}, handle)
        source_hash = ''
        if input:
            if os.path.getsize(input) > 25 * 1024 * 1024:
                raise ValueError('Input exceeds 25 MiB')
            digest = hashlib.sha256()
            with open(input, 'rb') as handle:
                for chunk in iter(lambda: handle.read(65536), b''):
                    digest.update(chunk)
            source_hash = digest.hexdigest()
        state = None
        if state_path.exists():
            if state_path.stat().st_size > 65536:
                raise ValueError('Invalid recovery file; keep it for review.')
            state = json.loads(state_path.read_text(encoding='utf-8'))
            now = time.time() * 1000
            if not isinstance(state, dict) or state.get('sourceHash') != source_hash or state.get('prompt') != prompt:
                raise ValueError('Saved request differs; preserve it while a generation is uncertain.')
            created = state.get('createdAt')
            request_data = state.get('request', {})
            if type(created) not in (int, float) or not now - 6 * 86400000 <= created <= now + 300000 or not re.fullmatch(r'[-\w]{16,80}', request_data.get('idempotencyKey', ''), re.ASCII) or request_data.get('expectedChargeUnits') != expected_charge_units or state.get('id') and not re.fullmatch(r'[0-9a-f-]{36}', state['id']):
                raise ValueError('Invalid or old recovery state; preserve it while a generation is uncertain.')

        def save(initial=False):
            if initial:
                descriptor = os.open(state_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
                with os.fdopen(descriptor, 'w', encoding='utf-8') as handle:
                    json.dump(state, handle)
                    handle.flush()
                    os.fsync(handle.fileno())
                return
            temporary = Path(str(state_path) + '.' + uuid.uuid4().hex + '.tmp')
            try:
                descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
                with os.fdopen(descriptor, 'w', encoding='utf-8') as handle:
                    json.dump(state, handle)
                    handle.flush()
                    os.fsync(handle.fileno())
                os.replace(temporary, state_path)
            finally:
                temporary.unlink(missing_ok=True)

        opener = urllib.request.build_opener(NoRedirect())
        transport = send or opener.open

        def request(path, method='GET', body=None, binary=False, download=False):
            url = urllib.parse.urljoin(BASE, path)
            parsed = urllib.parse.urlsplit(url)
            if parsed.scheme != 'https' or parsed.netloc != 'ai-gif-generator.com' or not parsed.path.startswith('/api/'):
                raise ValueError('Unexpected API URL')
            headers = {'Authorization': 'Bearer ' + key}
            if body is not None:
                headers['Content-Type'] = 'image/png' if binary else 'application/json'
            data = body if binary else json.dumps(body).encode('utf-8') if body is not None else None
            try:
                response = transport(urllib.request.Request(url, data=data, headers=headers, method=method), timeout=300 if binary or download else 90)
            except urllib.error.HTTPError as error:
                response = error
            except (OSError, urllib.error.URLError):
                raise RuntimeError('Connection interrupted. Resume with the same output path; do not create a replacement generation.') from None
            status = response.status
            if not 200 <= status < 300:
                try:
                    error_data = json.loads(response.read(65536))
                except (ValueError, OSError):
                    error_data = {}
                code = error_data.get('error', '')
                code = code if isinstance(code, str) and re.fullmatch(r'[a-z_]{1,80}', code) else 'request_failed'
                retry = response.headers.get('Retry-After', '')
                response.close()
                raise RuntimeError(f'API {status}: {code}.' + (f' Wait at least {retry} seconds before retrying.' if retry.isdigit() else '') + ' Resume with the same output path; terminal failure requires an intentional new submission.')
            if download:
                return response
            try:
                data = response.read(65537)
                if len(data) > 65536:
                    raise ValueError('Oversized API response')
                return json.loads(data)
            finally:
                response.close()

        prepared = None

        def reference():
            nonlocal prepared, prepared_directory
            if prepared is None:
                module_path = Path(__file__).with_name('export.py')
                spec = importlib.util.spec_from_file_location('aigifgenerator_prepare', module_path)
                module = importlib.util.module_from_spec(spec)
                try:
                    spec.loader.exec_module(module)
                except ModuleNotFoundError:
                    raise RuntimeError('Reference inputs require export.py beside edit.py and Pillow: python -m pip install Pillow') from None
                prepared_directory = tempfile.TemporaryDirectory(prefix='aigifgenerator-')
                png = Path(prepared_directory.name) / 'reference.png'
                metadata = module.prepare(input, png)
                prepared = (metadata, png.read_bytes())
            return prepared

        if state is None:
            draft = {'prompt': prompt.strip()}
            if input:
                draft['reference'] = reference()[0]
            quote = request('/api/v1/edits/quote', 'POST', draft)
            if quote['chargeUnits'] != expected_charge_units:
                raise ValueError(f"Confirm the quoted charge of {quote['chargeUnits']} accounting units using expected_charge_units.")
            state = {'createdAt': int(time.time() * 1000), 'sourceHash': source_hash, 'prompt': prompt, 'request': {**draft, 'expectedChargeUnits': quote['chargeUnits'], 'idempotencyKey': str(uuid.uuid4())}}
            save(initial=True)
        job = request('/api/v1/edits/' + state['id']) if state.get('id') else request('/api/v1/edits', 'POST', state['request'])
        if not re.fullmatch(r'[0-9a-f-]{36}', job.get('id', '')):
            raise ValueError('Invalid job response; preserve recovery state.')
        if not state.get('id'):
            state['id'] = job['id']
            save()
        if job['state'] == 'awaiting_upload' and not job.get('uploaded'):
            metadata, png = reference()
            if metadata != state['request'].get('reference'):
                raise ValueError('Prepared reference changed; restore the same source and encoder before resuming')
            request('/api/v1/edits/' + job['id'] + '/upload', 'PUT', png, binary=True)
        if state['request'].get('reference') and job['state'] in ('awaiting_upload', 'queued'):
            request('/api/v1/edits/' + job['id'] + '/submit', 'POST', {})
        deadline = time.monotonic() + 20 * 60
        while job['state'] in ('awaiting_upload', 'queued', 'processing'):
            if time.monotonic() > deadline:
                raise RuntimeError('Still processing. Resume with the same output path.')
            wait(min(10, max(3, job.get('pollAfterMs', 3000) / 1000)))
            job = request('/api/v1/edits/' + state['id'])
        if job['state'] != 'ready':
            raise RuntimeError('Generation is terminal or unavailable; preserve recovery state. Submit a fresh generation explicitly to try again.')
        response = request(job['resultUrl'], download=True)
        temporary = Path(str(output) + '.' + uuid.uuid4().hex + '.part')
        try:
            if response.headers.get('Content-Type', '').split(';')[0] != 'image/gif':
                raise ValueError('Unexpected result type')
            descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
            length, header = 0, b''
            with os.fdopen(descriptor, 'wb') as handle:
                while True:
                    chunk = response.read(65536)
                    if not chunk:
                        break
                    length += len(chunk)
                    if length > MAX_RESULT:
                        raise ValueError('Result exceeds 32 MiB')
                    header = (header + chunk[:6])[:6]
                    handle.write(chunk)
                declared = response.headers.get('Content-Length')
                if length < 14 or header not in (b'GIF87a', b'GIF89a') or declared is not None and int(declared) != length:
                    raise ValueError('Incomplete GIF download. Resume the original job.')
                handle.flush()
                os.fsync(handle.fileno())
            os.link(temporary, output)
        finally:
            response.close()
            temporary.unlink(missing_ok=True)
        state_path.unlink()
        return job
    finally:
        if prepared_directory is not None:
            prepared_directory.cleanup()
        lock_path.unlink(missing_ok=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('output', help='.gif output path; reuse the same path to resume')
    parser.add_argument('--prompt', default='')
    parser.add_argument('--input', help='Optional still JPEG, PNG or WebP, or a GIF using its first frame')
    options = parser.parse_args()
    try:
        print(edit_image(options.output, options.prompt, options.input, os.environ.get('AIGIFGENERATOR_API_KEY'), expected_charge_units=20)['id'])
    except (OSError, ValueError, RuntimeError) as error:
        parser.exit(1, str(error) + '\n')
