#!/usr/bin/env python3
"""Porta foto, sfondi, icona e suoni della 1.5 nell'app nuova e scrive src/immagini.ts.

Si lancia dal clone locale, una volta (o dopo aver cambiato le immagini sorgente):
    python3 scripts/prepara-immagini.py "/Users/paolo/Server/Siti Web/_private/ - App/SpotTheSpy"
"""
import pathlib
import shutil
import subprocess
import sys

from PIL import Image

RADICE = pathlib.Path(sys.argv[1])
V15 = RADICE / 'spotTheSpy 1.5' / 'spotTheSpy'
XC = V15 / 'Assets.xcassets'
MAT = RADICE / ' - mat'
PROGETTO = pathlib.Path(__file__).resolve().parent.parent
OUT = PROGETTO / 'assets'
STILI = 'abc'
LUOGHI = [n for n in range(1, 61) if n != 30]  # il 30 (McDonald's) è stato tolto
FONDO_ICONA = (0x31, 0x50, 0x69)


def jpg(src, dst, qualita):
    Image.open(src).convert('RGB').save(dst, 'JPEG', quality=qualita, optimize=True, progressive=True)


(OUT / 'luoghi').mkdir(parents=True, exist_ok=True)
(OUT / 'suoni').mkdir(exist_ok=True)

for n in LUOGHI:
    for s in STILI:
        jpg(XC / f'{n:02d}_{s}.imageset' / f'{n:02d}_{s}.jpg', OUT / 'luoghi' / f'{n:02d}_{s}.jpg', 78)
for s in STILI:
    jpg(XC / f'spia_{s}.imageset' / f'spia_{s}.jpg', OUT / f'spia_{s}.jpg', 80)
    jpg(XC / f'intro_{s}.imageset' / f'intro_{s}.jpg', OUT / f'intro_{s}.jpg', 80)
Image.open(XC / 'titolo.imageset' / 'titolo.png').save(OUT / 'titolo.png', optimize=True)

# Mascherina del timer: nella 1.5 era uno schermo intero nero con un ovale trasparente
# al centro. Si ritaglia attorno all'ovale, in 4:3 come le foto, così si sovrappone
# alla foto qualunque sia la forma dello schermo.
m = Image.open(XC / 'timer.imageset' / 'timer.png').convert('RGBA')
buco = m.getchannel('A').point(lambda v: 255 if v < 250 else 0)
x0, y0, x1, y1 = buco.getbbox()
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
w = (x1 - x0) * 1.08
h = w * 3 / 4
if h < (y1 - y0) * 1.08:
    h = (y1 - y0) * 1.08
    w = h * 4 / 3
# Il ritaglio può uscire dall'immagine originale: fuori c'è nero pieno, non trasparenza,
# altrimenti ai lati si vedrebbe la foto.
BORDO = 400
tela = Image.new('RGBA', (m.width + 2 * BORDO, m.height + 2 * BORDO), (0, 0, 0, 255))
tela.paste(m, (BORDO, BORDO))
tela.crop((round(cx - w / 2) + BORDO, round(cy - h / 2) + BORDO, round(cx + w / 2) + BORDO, round(cy + h / 2) + BORDO)).save(OUT / 'mascherina.png', optimize=True)

# Icona: iOS usa quella della 1.5 così com'è. Android la vuole adattiva: il simbolo
# (cappello e punto di domanda) su fondo pieno, dentro la zona sicura centrale.
icona = Image.open(MAT / 'icona' / 'AppIcon.png').convert('RGB')
icona.save(OUT / 'icon.png')
simbolo = icona.crop((160, 160, 880, 880))  # ridotto di 20px per lato: a (140,140,900,900) si vedeva il bordo arrotondato del vecchio pulsante negli angoli in alto
primo_piano = Image.new('RGB', (1024, 1024), FONDO_ICONA)
primo_piano.paste(simbolo.resize((600, 600), Image.LANCZOS), (212, 212))
primo_piano.save(OUT / 'adaptive-icon.png')

# Icona delle notifiche Android: solo il simbolo, bianco su trasparente.
chiaro = simbolo.convert('L').point(lambda v: 255 if v > 160 else 0)
notifica = Image.new('RGBA', simbolo.size, (255, 255, 255, 0))
notifica.putalpha(chiaro)
bianco = Image.new('RGBA', simbolo.size, (255, 255, 255, 255))
bianco.putalpha(chiaro)
bianco.resize((96, 96), Image.LANCZOS).save(OUT / 'notifica.png')

# Suoni. Il «paparapa» di fine tempo diventa .wav, perché le notifiche di iOS non
# accettano .m4a; lo usa anche l'app, così il file è uno solo.
SUONI = V15 / 'Sounds'
for nome in ['click.mp3', 'page.mp3', 'failure.mp3', 'suspense.mp3', 'tick.wav', 'vittoria.wav']:
    shutil.copy(SUONI / nome, OUT / 'suoni' / nome)
subprocess.run(['afconvert', '-f', 'WAVE', '-d', 'LEI16@44100', str(SUONI / 'paparapa.m4a'), str(OUT / 'suoni' / 'paparapa.wav')], check=True)

# src/immagini.ts: React Native vuole require() con il percorso scritto per esteso.
r = ['// Generato da scripts/prepara-immagini.py: non modificare a mano.', "import type { Stile } from './gioco.ts';", '']
r.append('export const FOTO_LUOGHI: Record<Stile, Record<number, number>> = {')
for s in STILI:
    r.append(f'  {s}: {{')
    r += [f"    {n}: require('../assets/luoghi/{n:02d}_{s}.jpg')," for n in LUOGHI]
    r.append('  },')
r += ['};', '']
r.append('export const FOTO_SPIA: Record<Stile, number> = {')
r += [f"  {s}: require('../assets/spia_{s}.jpg')," for s in STILI]
r += ['};', '']
r.append('export const SFONDI: Record<Stile, number> = {')
r += [f"  {s}: require('../assets/intro_{s}.jpg')," for s in STILI]
r += ['};', '']
r.append("export const TITOLO: number = require('../assets/titolo.png');")
r.append("export const MASCHERINA: number = require('../assets/mascherina.png');")
(PROGETTO / 'src' / 'immagini.ts').write_text('\n'.join(r) + '\n')
print('fatto')
