# SPDX-License-Identifier: GPL-3.0-only
"""Refresh public camera reference data and the attributed X-Trans III colour tables.

Run with Python, Pillow and numpy. No account or user data is downloaded.
"""
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.parse import quote
from io import BytesIO
import json
import hashlib
import numpy as np
from PIL import Image

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'public' / 'recipe-lab'
OUT.mkdir(parents=True, exist_ok=True)
LUTS = OUT / 'luts'
LUTS.mkdir(exist_ok=True)
API = 'https://api.reciperoom.io/api/v1'
REV = '3b3180f82d4dcea1e6e8c5648473539a910d7f49'

def read(url):
    with urlopen(Request(url, headers={'User-Agent': 'RecipeRoom-RecipeLab-reference-sync'}), timeout=30) as response:
        return response.read()

catalog = {}
for key, route in [('cameras', '/cameras'), ('profiles', '/cameras/setting-fields'), ('simulations', '/film-simulations')]:
    payload = json.loads(read(API + route))
    if not payload.get('success'):
        raise ValueError('Reference request failed: ' + route)
    catalog[key] = payload['data']
(OUT / 'catalog.json').write_text(json.dumps(catalog, separators=(',', ':')) + '\n')

names = ['Provia', 'Velvia', 'Astia', 'Classic Chrome', 'Pro Neg Hi', 'Pro Neg Std',
         'Acros', 'Acros+Ye', 'Acros+R', 'Acros+G', 'Mono', 'Mono+Ye', 'Mono+R', 'Mono+G', 'Sepia']
manifest = {}
for name in names:
    path = 'HaldCLUT/Fujifilm XTrans III/Fuji XTrans III - ' + name + '.png'
    raw = read('https://raw.githubusercontent.com/cedeber/hald-clut/' + REV + '/' + quote(path))
    image = Image.open(BytesIO(raw)).convert('RGB')
    # Hald order is red-fastest, then green, then blue. Sample the cube, not the 2D image.
    width, height = image.size
    cube_size = round((width * height) ** (1 / 3))
    assert cube_size ** 3 == width * height
    cube = np.asarray(image, dtype=np.float32).reshape(cube_size, cube_size, cube_size, 3)
    coords = np.linspace(0, cube_size - 1, 33)
    low = coords.astype(int)
    high = np.minimum(low + 1, cube_size - 1)
    weight = coords - low
    result = np.zeros((33, 33, 33, 3), dtype=np.float32)
    for dz in range(2):
        for dy in range(2):
            for dx in range(2):
                z, y, x = [high if bit else low for bit in (dz, dy, dx)]
                wz, wy, wx = [weight if bit else 1 - weight for bit in (dz, dy, dx)]
                result += cube[z[:, None, None], y[None, :, None], x[None, None, :]] * (wz[:, None, None] * wy[None, :, None] * wx[None, None, :])[..., None]
    filename = name.lower().replace(' ', '-').replace('+', '-') + '.rgb'
    (LUTS / filename).write_bytes(np.rint(result).astype(np.uint8).tobytes())
    manifest[name] = {'file': filename, 'source': path, 'sourceSha256': hashlib.sha256(raw).hexdigest(), 'size': 33}
    print('Prepared', name)
(LUTS / 'manifest.json').write_text(json.dumps({'revision': REV, 'tables': manifest}, indent=2) + '\n')
for name in ['LICENSE', 'HaldCLUT/Fujifilm XTrans III/README.txt']:
    target = 'LICENSE-GPL-3.0.txt' if name == 'LICENSE' else 'UPSTREAM-README.txt'
    (LUTS / target).write_bytes(read('https://raw.githubusercontent.com/cedeber/hald-clut/' + REV + '/' + quote(name)))
print('Public catalog and 15 colour tables refreshed.')
