#!/usr/bin/env python3

import sys
import json
import tempfile
import os
import subprocess
import multiprocessing
from os.path import splitext, exists

def run_mozjpeg(infile, outfile):
  mozjpeg_args = ['mozjpeg', '-quality', '85', '-optimize', infile]
  with open(outfile, 'w') as f:
    subprocess.run(mozjpeg_args, check=True, stdout=f)

def run_webp(infile, outfile):
  cwebp_args = ['cwebp', infile, '-o', outfile, '-m', '6', '-q', '85']
  subprocess.run(cwebp_args, check=True)

def run_cavif(infile, outfile):
  avifenc_args = ['cavif', '--cpu-used', '0', '--crf', '18', '-i', infile, '-o', outfile]
  subprocess.run(avifenc_args, check=True)

if len(sys.argv) != 2:
  print('Usage: {} file'.format(sys.argv[0]))
  print('Creates smaller versions of the original file')

filename = sys.argv[1]

root = splitext(filename)[0]

expected_end = '-orig.jpg'

if not filename.endswith(expected_end):
  print("expected file {} to end with {}, but it didn't".format(filename, expected_end))

output_root = root.removesuffix('-orig')

if not exists(filename):
  print("I don't see {}, sure that's the right filename?".format(filename))

arg_file = root + '.json'

if not exists(arg_file):
  print('I need an argument file with the name {} to work'.format(arg_file))

convert_args = None
with open(arg_file, 'r') as f:
    convert_args = json.loads(f.read())

with tempfile.TemporaryDirectory() as tmpdirname:
  tmp_file = os.path.join(tmpdirname, 'tmp.png')
  convert_args = ['convert', filename, '-resize', convert_args['resize-geometry'], tmp_file]
  subprocess.run(convert_args, check=True)
  run_mozjpeg(tmp_file, output_root + '.jpg')
  jpeg_size = os.path.getsize(output_root + '.jpg')
  run_webp(tmp_file, output_root + '.webp')
  webp_size = os.path.getsize(output_root + '.webp')
  # Don't use the webp file if it's bigger than the jpeg
  if jpeg_size < webp_size:
    print('Will not use {}.webp as it is bigger than the jpg'.format(output_root))
    os.remove(output_root + '.webp')
  run_cavif(tmp_file, output_root + '.avif')
  avif_size = os.path.getsize(output_root + '.avif')
  # Don't use the avif file if it's bigger than the jpeg or the webp
  if webp_size < avif_size or jpeg_size < avif_size:
    print('Will not use {}.avif as it is either bigger than the jpg/webp version'.format(output_root))
    os.remove(output_root + '.avif')