"""
Batch v4 dos 10 criativos da Chacara Sonho Verde Top.

REGRAS GLOBAIS aplicadas em TODOS:
  1) Logo CHACARA SONHO VERDE TOP no TOPO, alinhado a ESQUERDA, SEM risquinho embaixo
     - Playfair Black grande + "Sonho Verde Top" italico dourado
     - Removido do rodape (nao pode duplicar)
  2) Badge topo (eyebrow): fundo AMARELO transparente + texto PRETO, maior
  3) Localizacao em 1 LINHA: "NO ALTO DA MONTANHA - VALINHOS-SP - 80 KM DE SP"
     - EXCECAO: 04 mantem 2 linhas (linha1 e linha2 com mesma largura)
  4) Rodape so tem WhatsApp (sem logo)

Layouts:
  - Padrao (foto grande unica): 01, 02, 03, 04, 05, 06, 07, 08
  - Mix (3 fotos composicao profissional): 09, 10
"""
import base64
from pathlib import Path
from playwright.sync_api import sync_playwright

BASE = Path('/opt/mia/workspace/clientes/chacara-sonho-verde')
FOTOS = BASE / 'fotos_originais'
OUT = BASE


def img_to_data_uri(path: Path) -> str:
    b64 = base64.b64encode(path.read_bytes()).decode()
    return f"data:image/jpeg;base64,{b64}"


# ============================================================
# CSS COMUM (logo topo, badge amarelo, localizacao 1 linha, rodape sem logo)
# ============================================================
CSS_COMUM = """
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { margin: 0; overflow: hidden; background: #0d1f14; font-family: 'Inter', sans-serif; }
  .canvas {
    width: 1080px; height: 1350px; position: relative; overflow: hidden;
    background: #0d1f14;
  }

  /* BADGE TOPO - fundo AMARELO transparente + texto PRETO */
  .top-badge {
    position: absolute; top: 36px; left: 50%; transform: translateX(-50%);
    display: flex; align-items: center; gap: 10px;
    padding: 12px 26px;
    background: rgba(255,193,7,0.92);
    border: 1px solid rgba(255,193,7,1);
    border-radius: 100px;
    color: #0d1f14;
    font-family: 'Inter', sans-serif;
    font-size: 17px; font-weight: 700; letter-spacing: 2.4px; text-transform: uppercase;
    z-index: 5;
    white-space: nowrap;
    box-shadow: 0 6px 24px rgba(0,0,0,0.35);
  }
  .top-badge::before {
    content: ''; width: 6px; height: 6px; background: #0d1f14; border-radius: 50%;
  }

  /* CONTENT area inferior */
  .content {
    position: absolute; bottom: 0; left: 0; width: 100%; height: 780px;
    padding: 0 70px 38px 70px;
    display: flex; flex-direction: column; justify-content: flex-end;
    background: linear-gradient(180deg, transparent 0%, #0d1f14 28%, #0d1f14 100%);
    z-index: 2;
  }

  /* LOGO NO TOPO da area de conteudo - alinhado ESQUERDA - SEM risquinho */
  .brand-topo {
    text-align: left;
    margin-bottom: 24px;
  }
  .brand-topo .logo {
    font-family: 'Playfair Display', serif;
    font-size: 40px; font-weight: 900; color: #f8f6f0;
    line-height: 1.0; letter-spacing: -0.8px;
    text-transform: uppercase;
  }
  .brand-topo .logo em {
    color: #ffc107; font-style: italic; font-weight: 900;
    text-transform: none;
    display: block;
    font-size: 42px;
    margin-top: 2px;
    letter-spacing: -1px;
  }

  .headline {
    font-family: 'Playfair Display', serif;
    font-weight: 900;
    font-size: 62px;
    line-height: 1.02;
    color: #f8f6f0;
    letter-spacing: -1.6px;
    margin-bottom: 26px;
    text-shadow: 0 6px 30px rgba(0,0,0,0.5);
  }
  .headline em {
    font-style: italic; font-weight: 400;
    color: #ffc107;
  }

  /* LOCALIZACAO 1 linha (padrao) */
  .location-1l {
    display: flex; align-items: center; gap: 14px;
    margin-bottom: 24px;
    padding-bottom: 22px;
    border-bottom: 1px solid rgba(255,193,7,0.25);
  }
  .location-1l .pin {
    display: inline-flex; align-items: center; justify-content: center;
    width: 36px; height: 36px; flex-shrink: 0;
    background: #ffc107; border-radius: 50%;
    box-shadow: 0 4px 16px rgba(255,193,7,0.35);
  }
  .location-1l .pin svg { width: 18px; height: 18px; }
  .location-1l .text {
    font-family: 'Inter', sans-serif;
    font-weight: 800;
    font-size: 20px;
    line-height: 1.1;
    letter-spacing: 1px;
    text-transform: uppercase;
    color: #f8f6f0;
  }
  .location-1l .text .highlight { color: #ffc107; }
  .location-1l .text .sep { color: rgba(255,193,7,0.5); margin: 0 6px; }

  /* LOCALIZACAO 2 linhas (exclusivo criativo 04) */
  .location-2l {
    display: flex; align-items: center; gap: 18px;
    margin-bottom: 24px;
    padding-bottom: 22px;
    border-bottom: 1px solid rgba(255,193,7,0.25);
  }
  .location-2l .pin {
    display: inline-flex; align-items: center; justify-content: center;
    width: 44px; height: 44px; flex-shrink: 0;
    background: #ffc107; border-radius: 50%;
    box-shadow: 0 4px 20px rgba(255,193,7,0.35);
  }
  .location-2l .pin svg { width: 22px; height: 22px; }
  .location-2l .text {
    font-family: 'Inter', sans-serif;
    font-weight: 800;
    line-height: 1.1;
    letter-spacing: 0.8px;
    text-transform: uppercase;
  }
  .location-2l .text .l1 {
    color: #ffc107; display: block;
    font-size: 22px;
    letter-spacing: 2px;
  }
  .location-2l .text .l2 {
    color: #f8f6f0; display: block;
    font-size: 22px;
    font-weight: 700;
    letter-spacing: 0.6px;
    margin-top: 3px;
  }

  .sub {
    font-family: 'Inter', sans-serif;
    font-weight: 400;
    line-height: 1.45;
    color: #d8e0d3;
    margin-bottom: 30px;
    max-width: 860px;
  }
  .sub strong { color: #f8f6f0; font-weight: 600; }

  /* CTA row - so CTA esquerda + whatsapp direita (SEM logo) */
  .cta-row {
    display: flex; align-items: center; justify-content: space-between;
    padding-top: 24px;
    border-top: 1px solid rgba(255,255,255,0.15);
    gap: 20px;
  }
  .cta {
    display: inline-flex; align-items: center; gap: 12px;
    padding: 18px 30px;
    background: #ffc107;
    color: #0d1f14;
    font-family: 'Inter', sans-serif;
    font-weight: 700; font-size: 15px;
    letter-spacing: 1.2px; text-transform: uppercase;
    border-radius: 100px;
    box-shadow: 0 10px 30px rgba(255,193,7,0.25);
    white-space: nowrap;
  }
  .cta .arrow {
    display: inline-flex; width: 22px; height: 22px; border-radius: 50%;
    background: #0d1f14; color: #ffc107; align-items: center; justify-content: center;
    font-size: 14px;
  }

  .whats {
    display: flex; align-items: center; gap: 10px;
    font-family: 'Inter', sans-serif;
    color: #f8f6f0;
  }
  .whats .wa-icon {
    width: 32px; height: 32px; background: #25D366; border-radius: 50%;
    display: inline-flex; align-items: center; justify-content: center;
  }
  .whats .wa-icon svg { width: 20px; height: 20px; }
  .whats .num {
    font-size: 20px; font-weight: 800; color: #f8f6f0;
    letter-spacing: 0.4px;
  }
"""

# SVG do pin (localizacao)
SVG_PIN = '<svg viewBox="0 0 24 24" fill="#0d1f14"><path d="M12 2C7.58 2 4 5.58 4 10c0 5.25 7 12 8 12s8-6.75 8-12c0-4.42-3.58-8-8-8zm0 11a3 3 0 100-6 3 3 0 000 6z"/></svg>'
# SVG do WhatsApp
SVG_WA = '<svg viewBox="0 0 32 32" fill="#fff"><path d="M16 3C8.82 3 3 8.82 3 16c0 2.29.61 4.51 1.77 6.47L3 29l6.71-1.76A12.94 12.94 0 0016 29c7.18 0 13-5.82 13-13S23.18 3 16 3zm0 23.4c-1.98 0-3.9-.53-5.59-1.54l-.4-.24-3.98 1.04 1.06-3.88-.26-.41A10.4 10.4 0 015.6 16C5.6 10.26 10.26 5.6 16 5.6S26.4 10.26 26.4 16 21.74 26.4 16 26.4zm5.7-7.79c-.31-.16-1.84-.91-2.13-1.02-.29-.11-.5-.16-.7.16-.21.31-.8 1.02-.99 1.23-.18.21-.36.24-.67.08-.31-.16-1.32-.49-2.51-1.55-.93-.83-1.55-1.85-1.74-2.16-.18-.31-.02-.48.14-.63.14-.14.31-.36.47-.55.16-.18.21-.31.31-.52.11-.21.05-.39-.03-.55-.08-.16-.7-1.7-.96-2.32-.25-.6-.5-.52-.7-.53l-.6-.01c-.21 0-.55.08-.83.39-.28.31-1.09 1.07-1.09 2.6s1.12 3.02 1.27 3.23c.16.21 2.2 3.36 5.34 4.71.75.32 1.33.51 1.78.66.75.24 1.43.21 1.97.13.6-.09 1.84-.75 2.1-1.48.26-.72.26-1.34.18-1.48-.08-.13-.28-.21-.6-.36z"/></svg>'


# ============================================================
# LAYOUT PADRAO - uma foto grande + conteudo embaixo
# ============================================================
def build_html_padrao(
    foto_path: Path,
    badge: str,
    headline_html: str,
    sub_html: str,
    cta: str,
    location_html: str,  # ja renderizado (1 ou 2 linhas)
    sub_size: int = 22,
    hero_h: int = 640,
    content_h: int = 860,
) -> str:
    foto_uri = img_to_data_uri(foto_path)
    return f"""
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400;1,900&family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
{CSS_COMUM}
  .hero {{
    position: absolute; top: 0; left: 0; width: 100%; height: {hero_h}px;
    background-image: url('{foto_uri}');
    background-size: cover; background-position: center;
    filter: brightness(0.82) contrast(1.05) saturate(1.05);
  }}
  .hero-overlay {{
    position: absolute; top: 0; left: 0; width: 100%; height: {hero_h}px;
    background:
      linear-gradient(180deg, rgba(13,31,20,0.55) 0%, rgba(13,31,20,0.1) 25%, rgba(13,31,20,0.28) 55%, rgba(13,31,20,0.95) 92%, #0d1f14 100%);
  }}
  .content {{
    height: {content_h}px;
  }}
  .sub {{ font-size: {sub_size}px; }}
</style>
</head>
<body>
<div class="canvas">
  <div class="hero"></div>
  <div class="hero-overlay"></div>

  <div class="top-badge">{badge}</div>

  <div class="content">
    <div class="brand-topo">
      <div class="logo">Chácara<em>Sonho Verde Top</em></div>
    </div>

    <h1 class="headline">{headline_html}</h1>

    {location_html}

    <p class="sub">{sub_html}</p>

    <div class="cta-row">
      <div class="cta">
        {cta}
        <span class="arrow">&rarr;</span>
      </div>
      <div class="whats">
        <span class="wa-icon">{SVG_WA}</span>
        <span class="num">(11) 94192-3232</span>
      </div>
    </div>
  </div>
</div>
</body>
</html>
"""


# ============================================================
# HELPERS pra localizacao
# ============================================================
def loc_1_linha() -> str:
    """Padrao: NO ALTO DA MONTANHA - VALINHOS-SP - 80 KM DE SP"""
    return f"""
    <div class="location-1l">
      <span class="pin">{SVG_PIN}</span>
      <div class="text">
        <span class="highlight">No alto da montanha</span><span class="sep">·</span>Valinhos-SP<span class="sep">·</span>80 km de SP
      </div>
    </div>
    """


def loc_2_linhas_04() -> str:
    """Exclusivo criativo 04 - 2 linhas com larguras equivalentes"""
    return f"""
    <div class="location-2l">
      <span class="pin">{SVG_PIN}</span>
      <div class="text">
        <span class="l1">Valinhos-SP · 80 km de SP</span>
        <span class="l2">Casamento no alto da montanha</span>
      </div>
    </div>
    """


# ============================================================
# LAYOUT MIX PROFISSIONAL (09 e 10)
# Grid assimetrico: 1 foto GRANDE esquerda + 2 empilhadas direita
# com frames dourados e sombras suaves
# ============================================================
def build_html_mix_pro(
    foto_main: Path,
    foto_top: Path,
    foto_bottom: Path,
    badge: str,
    headline_html: str,
    sub_html: str,
    cta: str,
    location_html: str,
    sub_size: int = 22,
) -> str:
    uri_main = img_to_data_uri(foto_main)
    uri_top = img_to_data_uri(foto_top)
    uri_bottom = img_to_data_uri(foto_bottom)

    return f"""
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400;1,900&family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
{CSS_COMUM}
  /* MIX PRO: grid assimetrico com frames dourados */
  .mix-wrap {{
    position: absolute; top: 0; left: 0; width: 100%; height: 620px;
    background: #0d1f14;
    padding: 30px 30px 0 30px;
    overflow: hidden;
  }}
  .mix-grid {{
    width: 100%; height: 100%;
    display: grid;
    grid-template-columns: 1.35fr 1fr;
    grid-template-rows: 1fr 1fr;
    gap: 12px;
  }}
  .mix-cell {{
    background-size: cover; background-position: center;
    border-radius: 14px;
    box-shadow: 0 10px 34px rgba(0,0,0,0.55), 0 0 0 1.5px rgba(255,193,7,0.35) inset;
    filter: brightness(0.88) contrast(1.05) saturate(1.08);
    overflow: hidden;
    position: relative;
  }}
  .mix-main {{
    grid-row: 1 / 3; grid-column: 1 / 2;
    background-image: url('{uri_main}');
  }}
  .mix-top {{
    grid-row: 1 / 2; grid-column: 2 / 3;
    background-image: url('{uri_top}');
  }}
  .mix-bottom {{
    grid-row: 2 / 3; grid-column: 2 / 3;
    background-image: url('{uri_bottom}');
  }}
  /* Fade escuro por cima do mix inteiro na parte inferior pra emendar com o content */
  .mix-fade {{
    position: absolute; left: 0; bottom: 0; width: 100%; height: 90px;
    background: linear-gradient(180deg, transparent 0%, #0d1f14 100%);
    pointer-events: none; z-index: 3;
  }}

  .content {{
    height: 730px;
  }}
  .sub {{ font-size: {sub_size}px; }}
</style>
</head>
<body>
<div class="canvas">
  <div class="mix-wrap">
    <div class="mix-grid">
      <div class="mix-cell mix-main"></div>
      <div class="mix-cell mix-top"></div>
      <div class="mix-cell mix-bottom"></div>
    </div>
    <div class="mix-fade"></div>
  </div>

  <div class="top-badge">{badge}</div>

  <div class="content">
    <div class="brand-topo">
      <div class="logo">Chácara<em>Sonho Verde Top</em></div>
    </div>

    <h1 class="headline">{headline_html}</h1>

    {location_html}

    <p class="sub">{sub_html}</p>

    <div class="cta-row">
      <div class="cta">
        {cta}
        <span class="arrow">&rarr;</span>
      </div>
      <div class="whats">
        <span class="wa-icon">{SVG_WA}</span>
        <span class="num">(11) 94192-3232</span>
      </div>
    </div>
  </div>
</div>
</body>
</html>
"""


# ============================================================
# RENDER
# ============================================================
def render_one(html: str, dest: Path, w: int = 1080, h: int = 1350):
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(viewport={"width": w, "height": h}, device_scale_factor=1)
        page.set_content(html, wait_until="networkidle")
        page.wait_for_timeout(700)
        page.screenshot(path=str(dest), clip={"x": 0, "y": 0, "width": w, "height": h})
        browser.close()
    print(f"[OK] {dest.name}")


# ============================================================
# ESPECIFICACOES DOS 10 CRIATIVOS v4
# ============================================================
def gerar_01():
    # Reuniao de equipe no alto da montanha
    return build_html_padrao(
        foto_path=FOTOS / 'foto_100_treated.jpg',
        badge="Eventos corporativos",
        headline_html="Reunião de equipe<br><em>no alto da montanha</em>",
        sub_html="<strong>Estrutura completa.</strong> Hospedagem para 65 pessoas.",
        cta="Consulte disponibilidade",
        location_html=loc_1_linha(),
        sub_size=24,
        hero_h=620,
        content_h=760,
    )


def gerar_02():
    # Confraternizacao pra 150 pessoas
    return build_html_padrao(
        foto_path=FOTOS / 'foto_39_treated.jpg',
        badge="Confraternização corporativa",
        headline_html="Confraternização pra<br><em>150 pessoas</em>",
        sub_html="<strong>3 cozinhas + churrasqueira + forno de pizza.</strong> Hospedagem para 65 pessoas.",
        cta="Chame no WhatsApp",
        location_html=loc_1_linha(),
        sub_size=24,
    )


def gerar_03():
    # Onde lideres tomam as melhores decisoes
    return build_html_padrao(
        foto_path=FOTOS / 'foto_28_treated.jpg',
        badge="Espaço para eventos empresariais",
        headline_html="Onde líderes tomam as<br><em>melhores decisões</em>",
        sub_html="<strong>Silêncio, natureza e hospedagem inclusa</strong> para 65 pessoas.",
        cta="Verifique a data disponível",
        location_html=loc_1_linha(),
        sub_size=24,
    )


def gerar_04():
    # Cerimonia, festa e hospedagem. Um so lugar. (2 linhas de localizacao)
    return build_html_padrao(
        foto_path=FOTOS / 'foto_06_v4_sem_pessoas.jpg',
        badge="Casamento",
        headline_html="Cerimônia, festa e hospedagem.<br><em>Um só lugar.</em>",
        sub_html="<strong>Seus convidados dormem na chácara.</strong> Hospedagem para 65 pessoas.",
        cta="Consulte disponibilidade",
        location_html=loc_2_linhas_04(),
        sub_size=26,
    )


def gerar_05():
    # Casamento no alto da montanha
    return build_html_padrao(
        foto_path=FOTOS / 'foto_hero_treated.jpg',
        badge="Casamento",
        headline_html="Casamento<br><em>no alto da montanha</em>",
        sub_html="<strong>18 mil m² de reserva privada.</strong> Hospedagem para 65 pessoas.",
        cta="Reserve sua data",
        location_html=loc_1_linha(),
        sub_size=26,
    )


def gerar_06():
    # Salao para 120. Area externa sem limite.
    return build_html_padrao(
        foto_path=FOTOS / 'foto_piscina_treated.jpg',
        badge="Seu casamento aqui",
        headline_html="Salão para 120.<br><em>Área externa sem limite.</em>",
        sub_html="Seu casamento no <strong>alto da montanha</strong>, no meio da floresta. Hospedagem para 65 pessoas.",
        cta="Chame no WhatsApp",
        location_html=loc_1_linha(),
        sub_size=23,
    )


def gerar_07():
    # Feriado com 65 amigos
    return build_html_padrao(
        foto_path=FOTOS / 'foto_piscina_treated.jpg',
        badge="Feriado prolongado",
        headline_html="Feriado com 65 amigos.<br><em>Sem engarrafamento pra praia.</em>",
        sub_html="<strong>Piscina, sauna e trilha</strong> a 80 km de SP. Hospedagem para 65 pessoas.",
        cta="Consulte disponibilidade",
        location_html=loc_1_linha(),
        sub_size=23,
    )


def gerar_08():
    # INVERTIDO: headline = "Fim de semana, festa, cerimonia..." / sub = "18 mil m²..."
    return build_html_padrao(
        foto_path=FOTOS / 'foto_hero_treated.jpg',  # aerea, diferente do 01 (que usa foto_100)
        badge="Família e amigos",
        headline_html="Fim de semana, festa,<br>cerimônia ou <em>evento empresarial</em>.<br>Escolha como usar.",
        sub_html="<strong>18 mil m² para a família se espalhar.</strong> Hospedagem para 65 pessoas.",
        cta="Faça a sua reserva",
        location_html=loc_1_linha(),
        sub_size=24,
        hero_h=580,
        content_h=820,
    )


def gerar_09():
    # Mix pro - Lazer para adultos e criancas
    return build_html_mix_pro(
        foto_main=FOTOS / 'foto_piscina_treated.jpg',
        foto_top=FOTOS / 'foto_39_treated.jpg',
        foto_bottom=FOTOS / 'foto_hero_treated.jpg',
        badge="Tudo em um lugar",
        headline_html="Lazer para adultos<br>e crianças <em>sem sair pra nada</em>",
        sub_html="<strong>Hospedagem para até 65 pessoas.</strong>",
        cta="Reserve pelo WhatsApp",
        location_html=loc_1_linha(),
        sub_size=26,
    )


def gerar_10():
    # Mix pro - Hospedagem 5 estrelas no coracao da mata
    return build_html_mix_pro(
        foto_main=FOTOS / 'foto_20_treated.jpg',
        foto_top=FOTOS / 'foto_piscina_treated.jpg',
        foto_bottom=FOTOS / 'foto_100_treated.jpg',
        badge="Avaliações verificadas",
        headline_html="Hospedagem <em>5 estrelas</em><br>no coração da mata",
        sub_html="<strong>Avaliações 5 estrelas pelos visitantes.</strong> Hospedagem para 65 pessoas.",
        cta="Conheça a chácara",
        location_html=loc_1_linha(),
        sub_size=24,
    )


# ============================================================
# EXECUCAO
# ============================================================
CRIATIVOS = {
    '01': gerar_01,
    '02': gerar_02,
    '03': gerar_03,
    '04': gerar_04,
    '05': gerar_05,
    '06': gerar_06,
    '07': gerar_07,
    '08': gerar_08,
    '09': gerar_09,
    '10': gerar_10,
}


def render_lote(ids):
    for i in ids:
        html = CRIATIVOS[i]()
        dest = OUT / f'criativo_{i}_v4.png'
        render_one(html, dest)


if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        ids = sys.argv[1:]
    else:
        ids = list(CRIATIVOS.keys())
    render_lote(ids)
