#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Kartu feed IG The Skin Code — versi FOTO (gaya kreatif yang dikirim Bos 13 Okt 2026),
tapi isinya dari artikel TSC sendiri. 1080x1350, satu gambar = satu post feed.

Pakai aset foto Pexels yang sudah ada di folder ini (tidak mengunduh baru).
Hasil: tsc_ads_sample/feed_foto_<topik>_<gelap|terang>.jpg
"""
import importlib.util
import os
import sys

from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageOps

BASE = "/home/mantapman/.hermes/profiles/atun/workspace"
OUT = f"{BASE}/tsc_ads_sample"
FONT = f"{BASE}/fonts_tsc"

# muat helper dari generator kreatif yang sudah ada (hanya fungsi, bukan eksekusi __main__)
spec = importlib.util.spec_from_file_location("bk", f"{OUT}/buat_kreatif.py")
bk = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bk)

W, H = 1080, 1350
GOLD = (241, 196, 83)
GOLD_LEMBUT = (232, 206, 140)
SLATE_TOP = (40, 50, 68)
SLATE_BOT = (58, 66, 87)
NAVY = (26, 52, 92)
HANDLE = "@theskincode_clinic"
WEB = "www.theskincodeclinic.com"
WA = "WA 0851-1744-4417"


def _lebar(d, teks, font, tracking=0):
    baris = teks.split("\n")
    return max(sum(d.textlength(ch, font=font) for ch in b) + tracking * max(len(b) - 1, 0) for b in baris)


def track_fit(d, xy, teks, font_fn, fill, maks_lebar, tracking=0, spasi=0, ukuran_maks=104):
    """Tulis dengan ukuran font mengecil sampai muat di maks_lebar."""
    size = ukuran_maks
    while size > 24:
        f = font_fn(size)
        if _lebar(d, teks, f, tracking) <= maks_lebar:
            bk.teks_track(d, xy, teks, f, fill, tracking, spasi=spasi)
            return f
        size -= 4
    f = font_fn(24)
    bk.teks_track(d, xy, teks, f, fill, tracking, spasi=spasi)
    return f


def baris_ke(d, teks, font, maks_lebar):
    kata, out, kini = teks.split(), [], ""
    for k in kata:
        coba = f"{kini} {k}".strip()
        if d.textlength(coba, font=font) <= maks_lebar or not kini:
            kini = coba
        else:
            out.append(kini)
            kini = k
    out.append(kini)
    return out


def tempel_logo(c, gaya, x, y, lebar=300):
    """Tempel logo resmi TSC (dari file Bos 14 Okt 2026) — versi putih untuk kartu gelap."""
    f = f"{BASE}/tsc_aset/logo_bos_{'putih' if gaya == 'gelap' else 'navy'}.png"
    lg = Image.open(f).convert("RGBA")
    lg = lg.resize((lebar, round(lg.height * lebar / lg.width)), Image.LANCZOS)
    c.paste(lg, (x, y), lg)


def kartu(foto_path, gaya, judul, aksen, poin, keluhan, keluar):
    c = Image.new("RGB", (W, H), (255, 255, 255))
    KOLOM = 620  # lebar aman kolom teks (foto di kanan)
    if gaya == "gelap":
        c.paste(bk.gradien((W, H), SLATE_TOP, SLATE_BOT), (0, 0))
        lap = Image.new("L", (W, H), 0)
        ImageDraw.Draw(lap).ellipse([160, -140, 1120, 800], fill=70)
        c = Image.composite(Image.new("RGB", (W, H), (120, 142, 178)), c, lap.filter(ImageFilter.GaussianBlur(220)))
        foto = Image.open(foto_path).convert("RGB")
        abu = ImageOps.grayscale(foto)
        model = ImageOps.colorize(abu, black=(20, 26, 38), white=(178, 192, 214))
        model = ImageEnhance.Contrast(model).enhance(0.96)
        bk.tempel_lembut(c, model, (700, 470), (470, 620), blur=120, jari=0.15)
        warna_judul, warna_teks = (255, 255, 255), (238, 241, 246)
    else:
        lap = Image.new("RGB", (W, H), (255, 255, 255))
        dl = ImageDraw.Draw(lap)
        dl.arc([-420, 540, 760, 1300], start=195, end=345, fill=GOLD_LEMBUT, width=4)
        c = Image.blend(c, lap, 0.95)
        foto = Image.open(foto_path).convert("RGB")
        model = ImageEnhance.Brightness(foto).enhance(1.08)
        model = ImageEnhance.Contrast(model).enhance(0.92)
        model = Image.blend(model, Image.new("RGB", model.size, (253, 249, 244)), 0.14)
        bg = sum(model.getpixel((3, 3))) / 3
        skala = min(255.0 / max(bg, 1), 1.26)
        model = model.point(lambda v: min(255, int(v * skala)))
        bk.tempel_lembut(c, model, (790, 470), (440, 590), blur=140, jari=0.09)
        warna_judul, warna_teks = NAVY, (30, 46, 74)

    d = ImageDraw.Draw(c)
    warna_kecil = (236, 239, 245) if gaya == "gelap" else (48, 64, 96)
    warna_kecil2 = (216, 222, 233) if gaya == "gelap" else (74, 92, 128)
    # teks di kartu terang menimpa foto terang -> beri garis luar putih tipis supaya terbaca
    stroke, stroke_fill = (0, None) if gaya == "gelap" else (3, (255, 255, 255, 230))
    bk.teks_track(d, (62, 84), HANDLE, bk.f_sans(30), warna_kecil, 0.5, stroke=stroke, stroke_fill=stroke_fill)
    bk.teks_track(d, (62, 124), WEB, bk.f_sansl(24), warna_kecil2, 0.3, stroke=stroke, stroke_fill=stroke_fill)

    # judul: serif besar (mengecil otomatis kalau perlu) + aksen script emas
    f_judul = track_fit(d, (84, 196), judul, bk.f_serif, warna_judul, KOLOM, 0, spasi=12, ukuran_maks=96)
    y_aksen = 196 + judul.count("\n") * int(f_judul.size * 1.14) + 88
    track_fit(d, (104, y_aksen), aksen, bk.f_script, GOLD, KOLOM + 60, 0, ukuran_maks=112)

    yd = y_aksen + 118
    d.line([(92, yd), (330, yd)], fill=(214, 184, 118), width=3)
    d.polygon([(312, yd - 8), (330, yd), (312, yd + 8)], fill=(214, 184, 118))

    y = yd + 40
    f_ke = bk.f_sans(33) if gaya != "gelap" else bk.f_sansl(34)
    for b in baris_ke(d, keluhan, f_ke, KOLOM):
        bk.teks_track(d, (92, y), b, f_ke, warna_teks, 0, stroke=stroke, stroke_fill=stroke_fill)
        y += 46
    y += 14

    # pilih ukuran poin yang pasti berhenti di atas pil CTA
    yp = H - 320
    y_poin = y
    f_poin = bk.f_sans(30)
    for size in (30, 28, 26, 24):
        f_poin = bk.f_sans(size)
        uji = y_poin
        for p in poin:
            uji += len(baris_ke(d, p, f_poin, KOLOM - 40)) * 44 + 14
        if uji <= yp - 26:
            break

    y = y_poin
    for p in poin:
        for i, b in enumerate(baris_ke(d, p, f_poin, KOLOM - 40)):
            if i == 0:
                d.ellipse([92, y + 12, 106, y + 26], outline=GOLD, width=3)
            bk.teks_track(d, (128, y), b, f_poin, warna_teks, 0, stroke=stroke, stroke_fill=stroke_fill)
            y += 44
        y += 14

    # pil CTA
    isi_pil = (255, 255, 255) if gaya == "gelap" else NAVY
    teks_pil = NAVY if gaya == "gelap" else (255, 255, 255)
    d.rounded_rectangle([(92, yp), (92 + 570, yp + 92)], radius=46, fill=isi_pil)
    bk.teks_track(d, (146, yp + 26), WA, bk.f_sans(36), teks_pil, 1)

    tempel_logo(c, gaya, 92, H - 215, lebar=310)

    c.save(keluar, quality=94)
    print("ok:", keluar, os.path.getsize(keluar) // 1024, "KB")


if __name__ == "__main__":
    kartu(
        foto_path=f"{OUT}/pex_06_19999456.jpg",
        gaya="terang",
        judul="Bekas jerawat\ncekung",
        aksen="tak hilang sendiri",
        keluhan="Cekungannya ada di lapisan kulit yang lebih dalam.",
        poin=["Bukan soal krim yang lebih mahal.",
              "Jenisnya dibedakan dokter.",
              "Tindakan dipilih setelah diperiksa."],
        keluar=f"{OUT}/feed_foto_bekas_jerawat_terang.jpg",
    )
    kartu(
        foto_path=f"{OUT}/pex_09_10209466.jpg",
        gaya="gelap",
        judul="Kulitmu\nbicara",
        aksen="lebih dari terlihat",
        keluhan="Jerawat berulang di tempat yang sama paling sering meninggalkan bekas.",
        poin=["Tangani jerawat aktif lebih dulu.",
              "Hentikan kebiasaan memencet.",
              "Pakai pelindung matahari tiap hari."],
        keluar=f"{OUT}/feed_foto_kulitmu_bicara_gelap.jpg",
    )
