#!/usr/bin/env python3
import os, json, base64, pathlib, re, time, sys, textwrap
import requests
from PIL import Image, ImageDraw, ImageFont
import qrcode

ROOT=pathlib.Path('/home/ubuntu/lobbytracker')
DATA=json.loads(pathlib.Path('/tmp/lobby_politicians_full.json').read_text())
STYLE_IMG=pathlib.Path('/home/ubuntu/.hermes/image_cache/img_184c12b449fc.jpg')
OUT=ROOT/'public/cards/generated'
OUT.mkdir(parents=True, exist_ok=True)
API='https://openrouter.ai/api/v1/chat/completions'
KEY=os.environ.get('OPENROUTER_API_KEY')
if not KEY:
    env=pathlib.Path.home()/'.hermes/.env'
    if env.exists():
        for line in env.read_text().splitlines():
            if line.startswith('OPENROUTER_API_KEY='):
                KEY=line.split('=',1)[1].strip().strip('"')
if not KEY: raise SystemExit('missing OPENROUTER_API_KEY')

STYLE_B64=base64.b64encode(STYLE_IMG.read_bytes()).decode()

def slug(s):
    repl={'á':'a','é':'e','í':'i','ó':'o','ú':'u','ñ':'n','ü':'u','Á':'A','É':'E','Í':'I','Ó':'O','Ú':'U','Ñ':'N'}
    for a,b in repl.items(): s=s.replace(a,b)
    return re.sub(r'[^a-z0-9]+','-',s.lower()).strip('-')

def money(ars, usd):
    ars=int(ars or 0); usd=int(usd or 0)
    def fmt(n): return f"{n:,}".replace(',', '.')
    if ars>0 and usd>0: return f'ARS ${fmt(ars)}+ / ≈ USD ${fmt(usd)}+'
    if usd>0: return f'≈ USD ${fmt(usd)}+'
    if ars>0: return f'ARS ${fmt(ars)}+'
    return 'CONEXIONES REGISTRADAS'

def short_bullets(p):
    out=[]
    for c in p.get('connections') or []:
        desc=(c.get('description') or c.get('title') or '').strip()
        lg=((c.get('lobby_groups') or {}).get('name') or '').strip()
        if not desc: continue
        # keep specific, compact
        b=desc
        replacements=[('Participación como ','Participó como '),('Participación en ','Participó en '),('Asistencia en representación del Gobierno nacional al ','Asistió al '),('Durante su visita oficial a Israel, ','')]
        for a,bb in replacements: b=b.replace(a,bb)
        b=re.sub(r'\s+', ' ', b)
        if lg and len(b)<62 and lg not in b: b=f'{lg}: {b}'
        out.append(b[:92].rstrip(' .,;:'))
        if len(out)>=6: break
    return out

def visual_context(name):
    last=name.split()[-1].upper()
    base='Obelisco de Buenos Aires at left, Israeli flag / Star of David in the stormy background, stacks of US dollar bills, official documents and contracts on desk, red lightning, black smoke, expensive political thriller poster.'
    if 'Bullrich' in name:
        return base+' Subtle silhouettes of patrol boats / defense equipment in background, security-ministry mood.'
    if 'Milei' in name:
        return base+' Casa Rosada balcony / presidential trip atmosphere, diplomatic handshake silhouettes, no extra readable text.'
    if 'Werthein' in name:
        return base+' Foreign ministry/diplomatic summit atmosphere, business forum podium, trade documents.'
    if 'Jorge Macri' in name:
        return base+' Buenos Aires city government atmosphere, legislature/city hall silhouettes, decree papers.'
    if 'Wolff' in name:
        return base+' Security ministry atmosphere, DAIA/community event hints, official folders.'
    return base

def overlay_qr(path, qr_url):
    im=Image.open(path).convert('RGB')
    W,H=im.size
    qr=qrcode.QRCode(version=2, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=2)
    qr.add_data(qr_url); qr.make(fit=True)
    q=qr.make_image(fill_color='black', back_color='white').convert('RGB')
    size=int(W*0.145)
    q=q.resize((size,size), Image.Resampling.NEAREST)
    pad=int(W*0.022)
    x=W-size-pad; y=H-size-int(H*0.035)
    # white backing
    draw=ImageDraw.Draw(im)
    draw.rounded_rectangle([x-8,y-8,x+size+8,y+size+24], radius=10, fill=(245,245,240))
    im.paste(q,(x,y))
    try: font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed-Bold.ttf', int(W*0.022))
    except: font=None
    draw.text((x+size/2, y+size+3), 'ESCANEAR', fill=(0,0,0), font=font, anchor='ma')
    im.save(path, quality=95)

def prompt_for(p):
    name=p['name']; last=name.split()[-1].upper(); amount=money(p.get('total_lobby_ars'), p.get('total_lobby_usd'))
    bullets=short_bullets(p)
    bullets_txt='\n'.join(f'"{b.upper()}"' for b in bullets)
    return f'''Usá la imagen adjunta SOLO como benchmark de calidad y composición. Crear una NUEVA pieza para {name}, vertical 4:5, hiperrealista, calidad OpenAI GPT Image 2, estilo póster/carta coleccionable investigativa.

MISMO PUNCH visual de la referencia: cielo rojo tormentoso, rayos eléctricos, figura central fotorrealista de {name} en traje, iluminación cinematográfica roja, alto contraste, textura glossy de magazine cover, thriller político argentino. {visual_context(name)}

No hacerlo flat, no cartoon, no vector genérico, no Canva, no web card barata. Tiene que parecer una imagen publicitaria cara, hiperrealista y agresiva.

Texto exacto y jerarquía:
Arriba pequeño: "LOBBY TRACKER ARGENTINA 🇦🇷"
Nombre/Apellido grande: "{name.upper()}"
Monto/estado gigante: "{amount}"
Etiqueta: "ISRAEL LOBBY TOTAL"
Bullets abajo, blancos, condensados y legibles, usando estas líneas exactas o resumidas sin inventar:
{bullets_txt}
Footer izquierda: "MAY 2026"
Footer centro: "LOBBYTRACKER.AR"
Abajo derecha: dejar espacio para QR con label "ESCANEAR"

Importante: NO agregar claims nuevos, no nombres extra no listados, no logos de medios, no texto inventado. Si alguna línea es larga, condensarla sin cambiar el sentido.'''

def generate(p):
    s=slug(p['name'])
    if s=='horacio-rodriguez-larreta': return None
    out=OUT/f'{s}-gpt-image2-v1.png'
    if out.exists() and out.stat().st_size>100000:
        overlay_qr(out, p['qr_url'])
        return out
    payload={
      'model':'openai/gpt-5.4-image-2',
      'modalities':['image','text'],
      'image_config':{'aspect_ratio':'4:5','image_size':'1K'},
      'messages':[{'role':'user','content':[
          {'type':'text','text':prompt_for(p)},
          {'type':'image_url','image_url':{'url':'data:image/jpeg;base64,'+STYLE_B64}}
      ]}]
    }
    print('GENERATE', p['name'], flush=True)
    r=requests.post(API,headers={'Authorization':'Bearer '+KEY,'Content-Type':'application/json'},json=payload,timeout=300)
    (pathlib.Path('/tmp')/f'{s}_gpt_image2_response.json').write_text(r.text)
    print('STATUS', p['name'], r.status_code, len(r.text), flush=True)
    if r.status_code>=400:
        print(r.text[:1000], file=sys.stderr); return None
    d=r.json(); imgs=(d.get('choices',[{}])[0].get('message',{}).get('images') or [])
    if not imgs:
        print(json.dumps(d,ensure_ascii=False)[:1000], file=sys.stderr); return None
    url=imgs[0]['image_url']['url']
    data=url.split(',',1)[1] if url.startswith('data:') else requests.get(url,timeout=60).content
    if isinstance(data,str): data=base64.b64decode(data)
    out.write_bytes(data)
    overlay_qr(out, p['qr_url'])
    print('SAVED', out, flush=True)
    return out

if __name__=='__main__':
    ok=[]; fail=[]
    for p in DATA:
        if p['name']=='Horacio Rodríguez Larreta': continue
        res=generate(p)
        if res: ok.append(str(res))
        else: fail.append(p['name'])
    print('OK', json.dumps(ok,ensure_ascii=False,indent=2))
    print('FAIL', fail)
    if fail: sys.exit(1)
