#!/usr/bin/env python3
"""Change the visible Special Sessions paragraph to US English."""

from PIL import Image, ImageDraw, ImageFont


IMAGE = "cfp_p2_fixed.png"


def fraunces(size):
    font = ImageFont.truetype("Fraunces.ttf", size)
    font.set_variation_by_axes([28, 400, 0, 0])
    return font


image = Image.open(IMAGE).convert("RGB")
draw = ImageDraw.Draw(image)

# This is the approved three-line Special Sessions paragraph in the 3x render.
region = (120, 1650, 1750, 1810)
pixels = image.load()
xs, ys = [], []
for y in range(region[1], region[3]):
    for x in range(region[0], region[2]):
        r, g, b = pixels[x, y]
        if r < 120 and g < 120 and b < 120:
            xs.append(x)
            ys.append(y)
if not xs:
    raise SystemExit("Special Sessions paragraph not found")
box = (min(xs), min(ys), max(xs), max(ys))
background = image.getpixel((1700, box[1] - 10))
draw.rectangle((box[0] - 4, box[1] - 8, 1760, box[3] + 10), fill=background)

text = (
    "Researchers are invited to propose Special Sessions on focused or rapidly developing "
    "areas within the scope of META 2027. Proposals should identify the scientific theme, "
    "the organizers and prospective contributors."
)
font = fraunces(42)
line_height = (box[3] - box[1]) / 3.0 * 1.02
lines, current = [], ""
for word in text.split():
    candidate = f"{current} {word}".strip()
    if draw.textlength(candidate, font=font) > 1620 - box[0] and current:
        lines.append(current)
        current = word
    else:
        current = candidate
lines.append(current)

y = box[1] + 34
for line in lines:
    draw.text((box[0], y), line, font=font, fill=(58, 58, 56), anchor="ls")
    y += line_height

image.save(IMAGE)
print(f"Updated {IMAGE}: {len(lines)} lines")
