import re
import subprocess
from math import sin, pi, cos, inf
from pathlib import Path
from random import randint
from typing import List, Tuple

image_dir = Path("/tmp/microscope/rotated")

cmdline = ["/media/source/multiblend/src/multiblend", "--all-threads", "-o", image_dir / "output.jpg", "--"]

PX_PER_MM = 166
ANGLE = 1.35

svg = (image_dir / "image_rects.svg").open("w")
svg.write(f'<svg xmlns="http://www.w3.org/2000/svg">')

translate_parens_space = str.maketrans('', '', '() ')
name_regex = re.compile(r"(\d+)_x(\d+)_y(\d+).jpg")
min_x = inf
max_x = -inf
min_y = inf
max_y = -inf
photos: List[Tuple[Path, float, float]] = []
for entry in image_dir.iterdir():
    m = name_regex.match(entry.name)
    if not m:
        continue
    x = float(m.group(2))
    y = float(m.group(3))
    min_x = min(min_x, x)
    max_x = max(max_x, x)
    min_y = min(min_y, y)
    max_y = max(max_y, y)
    photos.append((entry, x, y))

middle_x = (min_x + max_x) / 2
middle_y = (min_y + max_y) / 2
for photo in photos:
    cmdline.append(photo[0])
    x_mm = -(photo[1] - middle_x) * PX_PER_MM
    y_mm = (photo[2] - middle_y) * PX_PER_MM
    sin_theta = sin(ANGLE * pi / 180)
    cos_theta = cos(ANGLE * pi / 180)
    x_transformed = x_mm * cos_theta - y_mm * sin_theta
    y_transformed = x_mm * sin_theta + y_mm * cos_theta
    cmdline.append(f"{int(x_transformed)},{int(y_transformed)}")
    svg.write(
        f'<rect x="{int(x_transformed)}" y="{int(y_transformed)}" width="1920" height="1080" fill="#{randint(0, 255):02x}{randint(0, 255):02x}{randint(0, 255):02x}"/>')

svg.write('</svg>')
svg.close()
print(cmdline)
subprocess.run(cmdline)
