"""Monta comparativo lado a lado: ref original x versao Chacara."""
from PIL import Image, ImageDraw, ImageFont

REF = "/opt/mia/workspace/clientes/chacara-sonho-verde/refs_video/refs/1280w-3GyQI9VycXM.jpg"
NEW = "/opt/mia/workspace/clientes/chacara-sonho-verde/criativo_teste_ref_v1.png"
OUT = "/opt/mia/workspace/clientes/chacara-sonho-verde/comparativo_ref_vs_chacara.png"

# largura target por lado
side_w = 720
side_h = 900
gap = 40
pad_top = 90
pad_bot = 40
canvas_w = side_w * 2 + gap * 3
canvas_h = side_h + pad_top + pad_bot

canvas = Image.new("RGB", (canvas_w, canvas_h), (18, 22, 15))
draw = ImageDraw.Draw(canvas)

# tenta pegar fonte do sistema
try:
    font_title = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 22)
    font_label = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 18)
except Exception:
    font_title = ImageFont.load_default()
    font_label = ImageFont.load_default()

# labels
draw.text((gap + side_w//2, 35), "REF · Pousada Faustino",
          fill=(244, 239, 230), font=font_title, anchor="mm")
draw.text((gap + side_w//2, 62), "1280w-3GyQI9VycXM.jpg",
          fill=(180, 138, 87), font=font_label, anchor="mm")

draw.text((gap*2 + side_w + side_w//2, 35), "NEW · Chácara Sonho Verde",
          fill=(244, 239, 230), font=font_title, anchor="mm")
draw.text((gap*2 + side_w + side_w//2, 62), "criativo_teste_ref_v1.png",
          fill=(180, 138, 87), font=font_label, anchor="mm")

def fit(src_path, w, h):
    img = Image.open(src_path).convert("RGB")
    # preserva aspect, encaixa no box mantendo o mesmo formato 4:5 (essencial)
    # como ambos ja sao 4:5, o resize direto preserva proporcao
    src_ratio = img.width / img.height
    tgt_ratio = w / h
    if abs(src_ratio - tgt_ratio) < 0.02:
        return img.resize((w, h), Image.LANCZOS)
    # crop 4:5 centralizado se nao bater
    if src_ratio > tgt_ratio:
        new_w = int(img.height * tgt_ratio)
        left = (img.width - new_w) // 2
        img = img.crop((left, 0, left + new_w, img.height))
    else:
        new_h = int(img.width / tgt_ratio)
        top = (img.height - new_h) // 2
        img = img.crop((0, top, img.width, top + new_h))
    return img.resize((w, h), Image.LANCZOS)

ref_img = fit(REF, side_w, side_h)
new_img = fit(NEW, side_w, side_h)

canvas.paste(ref_img, (gap, pad_top))
canvas.paste(new_img, (gap*2 + side_w, pad_top))

# borda dourada suave em cada
def frame(draw, x, y, w, h, color=(180,138,87), width=2):
    draw.rectangle([x-1, y-1, x+w, y+h], outline=color, width=width)

frame(draw, gap, pad_top, side_w, side_h)
frame(draw, gap*2 + side_w, pad_top, side_w, side_h)

canvas.save(OUT, quality=94)
print(f"comparativo salvo: {OUT}")
