from PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageFilter
from pathlib import Path
import zipfile

OUT = Path('/root/agent_public/files/agilizer/daily/2026-08-21')
OUT.mkdir(parents=True, exist_ok=True)
BASE = Path('/root/.hermes/profiles/davinci/cache/images/openai_codex_gpt-image-2-high_20260821_080224_f0b3887d.png')
LOGO = Path('/root/projects/HoltiErp/frontend/src/assets/logo-agilizer.png')
FINAL = OUT / 'agilizer_post_viral_2026-08-21_e-so-dar-uma-olhadinha.png'
CAPTION = OUT / 'legenda_agilizer_post_viral_2026-08-21.txt'
ZIP = OUT / 'pack_agilizer_post_viral_2026-08-21.zip'

W, H = 1080, 1350
GREEN = (0, 203, 67)
DARK = (3, 20, 11)
MINT = (124, 255, 208)
OFFWHITE = (244, 247, 242)

img = Image.open(BASE).convert('RGB')
# exact 4:5 crop/resize, generated already close to target ratio
img = img.resize((W, H), Image.Resampling.LANCZOS)

# Editorial dark/green color grade: contrast, desaturate slightly, deepen shadows
img = ImageEnhance.Color(img).enhance(0.78)
img = ImageEnhance.Contrast(img).enhance(1.22)
img = ImageEnhance.Brightness(img).enhance(0.92)

# Deep left/top gradient for headline legibility, without hiding the photo
rgba = img.convert('RGBA')
overlay = Image.new('RGBA', (W, H), (0, 0, 0, 0))
p = overlay.load()
for y in range(H):
    for x in range(W):
        left = max(0, 1 - x / 760)
        top = max(0, 1 - y / 760)
        bottom = max(0, (y - 970) / 380)
        alpha = int(205 * max(left * 0.95, top * 0.58, bottom * 0.38))
        # subtle Agilizer dark green rather than neutral black
        p[x, y] = (DARK[0], DARK[1], DARK[2], min(alpha, 212))
rgba = Image.alpha_composite(rgba, overlay)

# Subtle brand accents
acc = Image.new('RGBA', (W, H), (0, 0, 0, 0))
d = ImageDraw.Draw(acc)
d.rounded_rectangle([64, 102, 182, 112], radius=5, fill=GREEN + (235,))
d.rounded_rectangle([64, 1168, 278, 1176], radius=4, fill=MINT + (155,))
d.line([(72, 1215), (412, 1215)], fill=GREEN + (90,), width=2)
rgba = Image.alpha_composite(rgba, acc)

draw = ImageDraw.Draw(rgba)
font_title = '/usr/share/fonts/opentype/urw-base35/NimbusSansNarrow-Bold.otf'
font_sub = '/usr/share/fonts/opentype/urw-base35/NimbusSans-Bold.otf'
font_regular = '/usr/share/fonts/opentype/urw-base35/NimbusSans-Regular.otf'

def fit_font(text, max_width, start_size, min_size=50):
    size = start_size
    while size >= min_size:
        f = ImageFont.truetype(font_title, size=size)
        bbox = draw.textbbox((0, 0), text, font=f, stroke_width=0)
        if bbox[2] - bbox[0] <= max_width:
            return f
        size -= 2
    return ImageFont.truetype(font_title, size=min_size)

x = 64
y = 170
lines = [
    ('É SÓ DAR', OFFWHITE, 118),
    ('UMA', OFFWHITE, 118),
    ('OLHADINHA', GREEN, 118),
]
for text, color, start in lines:
    f = fit_font(text, 610, start)
    # strong but controlled shadow
    draw.text((x+4, y+5), text, font=f, fill=(0,0,0,150), stroke_width=2, stroke_fill=(0,0,0,90))
    draw.text((x, y), text, font=f, fill=color, stroke_width=1, stroke_fill=(0,0,0,85))
    bbox = draw.textbbox((x, y), text, font=f)
    y += (bbox[3] - bbox[1]) + 10

# tiny context tag, non-sales
small = ImageFont.truetype(font_sub, 29)
tag = 'FRASES QUE TODA OFICINA JÁ OUVIU'
tag_bbox = draw.textbbox((0, 0), tag, font=small)
tag_w = tag_bbox[2] - tag_bbox[0]
tag_h = tag_bbox[3] - tag_bbox[1]
d.rounded_rectangle([64, y+26, 64 + tag_w + 32, y + tag_h + 49], radius=18, fill=(3,20,11,188), outline=GREEN+(170,), width=2)
draw.text((80, y+34), tag, font=small, fill=OFFWHITE)

# Place original logo discreetly bottom-left, preserving proportions
logo = Image.open(LOGO).convert('RGBA')
logo_w = 190
logo_h = int(logo.height * logo_w / logo.width)
logo = logo.resize((logo_w, logo_h), Image.Resampling.LANCZOS)
# soft plate to guarantee legibility without changing logo asset
plate = Image.new('RGBA', (logo_w + 40, logo_h + 28), (3,20,11,132))
plate = plate.filter(ImageFilter.GaussianBlur(0.4))
rgba.alpha_composite(plate, (54, H - logo_h - 76))
rgba.alpha_composite(logo, (74, H - logo_h - 62))

# export
rgba.convert('RGB').save(FINAL, quality=96, optimize=True)

caption = """É só dar uma olhadinha… e quando vê já tem diagnóstico, orçamento, ligação, explicação e prazo impossível. 😂\n\nQual frase clássica de cliente não pode faltar nessa lista?\n\nHashtags sugeridas:\n#oficinamecanica #mecanico #autoeletrico #autocenter #donodeoficina #gestaodeoficina #vidadeoficina #setorautomotivo #mecanicaautomotiva #oficina"""
CAPTION.write_text(caption, encoding='utf-8')

with zipfile.ZipFile(ZIP, 'w', compression=zipfile.ZIP_DEFLATED) as z:
    z.write(FINAL, FINAL.name)
    z.write(CAPTION, CAPTION.name)

print(FINAL)
print(CAPTION)
print(ZIP)
