#!/usr/bin/env /usr/bin/python3
import json, os, re, subprocess, textwrap, math
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageFilter

ROOT = Path('/home/ubuntu/lobbytracker')
OUT = ROOT / 'public' / 'cards'
OUT.mkdir(parents=True, exist_ok=True)
BASE_URL = 'https://lobbytracker.vercel.app'

politicians = json.loads(Path('/tmp/lobby_politicians.json').read_text())
connections = json.loads(Path('/tmp/lobby_connections.json').read_text())
by_pol = {}
for c in connections:
    by_pol.setdefault(c['politician_id'], []).append(c)

font_bold = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'
font_reg = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
F = lambda size: ImageFont.truetype(font_bold, size)
FR = lambda size: ImageFont.truetype(font_reg, size)

def slug(s):
    import unicodedata
    s = unicodedata.normalize('NFKD', s).encode('ascii','ignore').decode().lower()
    return re.sub(r'[^a-z0-9]+','-',s).strip('-')

def money(ars, usd):
    if ars and ars > 0:
        a = f"ARS ${ars/1e9:.1f}B" if ars >= 1e9 else f"ARS ${ars/1e6:.0f}M"
        u = f"≈ USD ${usd/1e6:.1f}M" if usd and usd >= 1e6 else (f"≈ USD ${int(usd):,}" if usd else "")
        return a, u
    if usd and usd > 0:
        return f"USD ${usd/1e6:.1f}M" if usd >= 1e6 else f"USD ${int(usd):,}", ""
    return "0", "SIN MONTO PÚBLICO"

def wrap(draw, text, font, width):
    words = text.split()
    lines=[]; cur=''
    for w in words:
        test = (cur+' '+w).strip()
        if draw.textbbox((0,0), test, font=font)[2] <= width:
            cur=test
        else:
            if cur: lines.append(cur)
            cur=w
    if cur: lines.append(cur)
    return lines

def draw_text_fit(draw, xy, text, max_width, max_size, min_size, fill, stroke_fill=None, stroke_width=0):
    size=max_size
    while size>=min_size:
        font=F(size)
        lines=wrap(draw, text, font, max_width)
        h=sum(draw.textbbox((0,0),l,font=font,stroke_width=stroke_width)[3]+6 for l in lines)
        if len(lines)<=2 and h<150:
            break
        size-=2
    x,y=xy
    for l in lines[:2]:
        draw.text((x,y), l, font=font, fill=fill, stroke_width=stroke_width, stroke_fill=stroke_fill)
        y += size+10
    return y

# curated card bullets: only source-backed; QR/detail page carries full evidence list
manual = {
 'Horacio Rodríguez Larreta': [
  'Convenio GCBA–Cámara de Comercio Argentino-Israelí (2022)',
  'Visita oficial a Israel: Herzog, Knéset y agenda bilateral',
  'Encuentro en DAIA con Knoblovits, Eyal Sela y AMIA',
  'Waldo Wolff, ex VP DAIA, incorporado a gabinete porteño',
  'Contratos Danaide / CoDeSur reportados por prensa: requieren auditoría oficial'
 ],
 'Javier Milei': [
  'Visita oficial a Israel y reunión con Netanyahu',
  'Memorándum contra terrorismo y antisemitismo',
  'Anuncio de embajada argentina en Jerusalén',
  'Reuniones y actos con DAIA / AMIA / Congreso Judío',
  'Alianza estratégica de defensa Argentina–Israel'
 ],
 'Gerardo Werthein': [
  'Gira oficial a Israel como canciller',
  'Reunión con Gideon Sa’ar: comercio, inversión e innovación',
  'Reunión con Isaac Herzog: defensa, seguridad y agua',
  'Encuentro Empresarial Argentina–Israel 2024',
  'Mensaje público de apoyo a Israel en acto DAIA'
 ],
 'Patricia Bullrich': [
  'Viaje a Israel para tecnología de seguridad fronteriza',
  'Reunión con DAIA por seguridad comunitaria',
  'Declaración AMIA en reunión de seguridad Mercosur',
  'Distinción DAIA por combate al financiamiento terrorista',
  'Acuerdos de defensa Argentina–Israel bajo su área'
 ],
 'Jorge Macri': [
  'Reuniones con AMIA, DAIA, CJL, Museo del Holocausto e Israel',
  'Decreto porteño contra antisemitismo celebrado por entidades',
  'Encuentro Empresarial Argentina–Israel 2024',
  'Acciones GCBA por rehenes y memoria del 7 de octubre',
  'Premios Ana Frank: reclamo AMIA, Embajada y rehenes'
 ],
 'Waldo Wolff': [
  'Ex vicepresidente de DAIA',
  'Ministro de Seguridad porteño: reunión DAIA / AMIA / ADL',
  'Participó en visita de seguridad a Israel (2016)',
  'Exposición ante Congreso Judío Mundial por AMIA',
  'Encuentro Empresarial Argentina–Israel 2024'
 ]
}

for p in politicians:
    W,H=1080,1350
    img=Image.new('RGB',(W,H),(4,4,6))
    draw=ImageDraw.Draw(img)
    # background gradients / lightning
    import random
    random.seed(p['id'])
    for y in range(H):
        r = int(22 + 60*(1-y/H) + 30*math.sin(y/95))
        draw.line((0,y,W,y), fill=(r, 0, 6))
    # radial dark vignette
    overlay=Image.new('RGBA',(W,H),(0,0,0,0)); od=ImageDraw.Draw(overlay)
    for i in range(18):
        od.ellipse((-220-i*18,80-i*18,W+120+i*18,H+260+i*18), outline=(0,0,0,10), width=18)
    img=Image.alpha_composite(img.convert('RGBA'), overlay).convert('RGB'); draw=ImageDraw.Draw(img)
    # lightning scribbles
    for _ in range(7):
        x=random.randint(30,W-30); y=random.randint(100,520)
        pts=[]
        for k in range(6):
            pts.append((x+random.randint(-70,70), y+k*random.randint(35,70)))
        draw.line(pts, fill=(210,20,30), width=random.randint(3,7))
    # abstract obelisk + flag/star/money/document
    draw.polygon([(100,610),(150,240),(200,610)], fill=(35,35,38), outline=(130,130,135))
    draw.rectangle((130,610,170,850), fill=(26,26,28), outline=(100,100,105))
    cx,cy=850,315
    for angle in range(0,180,30):
        import math as m
        x1=cx+int(145*m.cos(m.radians(angle))); y1=cy+int(145*m.sin(m.radians(angle)))
        x2=cx-int(145*m.cos(m.radians(angle))); y2=cy-int(145*m.sin(m.radians(angle)))
        draw.line((x1,y1,x2,y2), fill=(80,120,180), width=5)
    # money stacks
    for i in range(5):
        x=690+i*28; y=850+i*18
        draw.rounded_rectangle((x,y,x+260,y+82), radius=8, fill=(178,190,170), outline=(30,70,35), width=2)
        draw.text((x+82,y+24),'USD',font=F(26),fill=(35,80,40))
    # contract paper
    draw.polygon([(70,835),(430,790),(460,1070),(100,1115)], fill=(214,210,190), outline=(110,0,0), width=4)
    draw.text((115,850),'CONTRATO',font=F(38),fill=(80,0,0))
    draw.text((115,900),'FUENTES\nPÚBLICAS',font=F(30),fill=(25,25,25),spacing=6)
    # silhouette / portrait placeholder
    sx=W//2; sy=430
    draw.ellipse((sx-115,sy-170,sx+115,sy+60), fill=(18,18,20), outline=(180,30,35), width=5)
    draw.polygon([(sx-250,760),(sx-110,515),(sx+110,515),(sx+250,760)], fill=(14,14,16), outline=(160,24,30))
    initials=''.join([x[0] for x in p['name'].split()[:2]])
    draw.text((sx-48,sy-58), initials, font=F(76), fill=(230,230,230))
    # top/headers
    draw.text((56,42),'LOBBY TRACKER ARGENTINA',font=F(34),fill=(255,255,255),stroke_width=2,stroke_fill=(80,0,0))
    draw.text((56,84),'DATOS TRAZABLES · FUENTES CLICKEABLES',font=F(22),fill=(255,160,160))
    lastname=p['name'].split()[-1].upper()
    firstname=' '.join(p['name'].split()[:-1]).upper()
    draw.text((56,675), firstname, font=F(42), fill=(235,235,235), stroke_width=2, stroke_fill=(80,0,0))
    draw_text_fit(draw,(56,724), lastname, 720, 80, 42, (255,255,255), (85,0,0), 3)
    ars,usd=money(p.get('total_lobby_ars') or 0, p.get('total_lobby_usd') or 0)
    draw.text((56,840), ars, font=F(58), fill=(255,255,255), stroke_width=3, stroke_fill=(80,0,0))
    draw.text((60,910), usd, font=F(32), fill=(255,170,170))
    draw.text((60,950),'ISRAEL LOBBY TRACKER TOTAL',font=F(28),fill=(255,255,255))
    # bullets
    y=1005
    for b in manual[p['name']][:5]:
        lines=wrap(draw,b,F(25),690)
        draw.text((70,y),'•',font=F(27),fill=(255,70,75))
        for j,l in enumerate(lines[:2]):
            draw.text((105,y+j*29),l,font=F(25),fill=(245,245,245))
        y += 32*min(2,len(lines))+12
    # QR
    url=f"{BASE_URL}/p/{p['id']}"
    qr_path=f'/tmp/qr_{slug(p["name"])}.png'
    subprocess.run(['qrencode','-o',qr_path,'-s','8','-m','1',url],check=True)
    qr=Image.open(qr_path).convert('RGB').resize((210,210),Image.Resampling.NEAREST)
    img.paste(qr,(810,1058))
    draw.rectangle((800,1048,1030,1292),outline=(255,255,255),width=3)
    draw.text((794,1300),'ESCANEAR',font=F(25),fill=(255,255,255))
    draw.text((56,1284),'lobbytracker.vercel.app',font=F(28),fill=(255,210,210))
    draw.text((56,1318),'MAY 2026 · cada conexión debe tener evidencia pública',font=FR(18),fill=(180,180,180))
    # final sharpen
    img=img.filter(ImageFilter.UnsharpMask(radius=1.1,percent=120,threshold=3))
    out=OUT / f"{slug(p['name'])}.png"
    img.save(out, quality=95)
    print(p['name'], out, url)
