#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""9 cover carousel 3-slide untuk feed Instagram The Skin Code Clinic.

Latar berselang-seling tiga corak (putih · biru muda · gelap) dengan pola diagonal,
supaya begitu dipasang di feed, grid 3x3 terlihat berirama.

Output: tsc_cover9/tsc_cover_01..09.jpg (1080x1350) + tsc_cover9/grid_3x3.jpg (mockup feed)
"""
import os
import sys

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from PIL import Image, ImageDraw
import tsc_feed_lib as L

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tsc_cover9"
os.makedirs(OUT, exist_ok=True)

W, H, M = L.W, L.H, L.MARGIN
TERANG = "#F7F8FA"
BIRU_MUDA = "#DCE8F8"
NAVY = L.NAVY
GELAP_ATAS, GELAP_BAWAH = "#2F3A4E", "#1B2436"

# tiga corak, urutannya mengikuti diagonal grid 3x3: (baris + kolom) % 3
CORAK = ("terang", "biru", "gelap")

TOPIK = [
    dict(kicker="Edukasi kulit", judul="Bekas jerawat cekung",
         sub="Bukan soal krim yang lebih mahal."),
    dict(kicker="Kulit dewasa", judul="Jerawat hormonal",
         sub="Bukan sekadar salah pilih produk."),
    dict(kicker="Perawatan dasar", judul="Kulit sensitif",
         sub="Kenali pemicunya sebelum ganti produk."),
    dict(kicker="Kapan harus periksa", judul="Tahi lalat",
         sub="Tanda yang perlu dilihat dokter."),
    dict(kicker="Penularan", judul="Kutil kulit",
         sub="Bedanya dengan kutil kelamin."),
    dict(kicker="Tindakan klinik", judul="Hapus tato",
         sub="Apa saja yang menentukan hasilnya."),
    dict(kicker="Pertolongan awal", judul="Perawatan luka",
         sub="Supaya tidak meninggalkan bekas."),
    dict(kicker="Rutinitas harian", judul="Kulit berminyak",
         sub="Rutinitas yang tidak bikin makin berminyak."),
    dict(kicker="Kapan ke dokter", judul="Gatal berkepanjangan",
         sub="Kalau tidak kunjung sembuh, ada yang perlu dicari."),
]


def _corak_latar(corak, d):
    if corak == "gelap":
        return L.gradasi(GELAP_ATAS, GELAP_BAWAH), "#FFFFFF", "#C8D4E6", "#8FA0B8", True
    if corak == "biru":
        im = Image.new("RGB", (W, H), BIRU_MUDA)
        L.lengkung(ImageDraw.Draw(im), warna="#FFFFFF", tebal=4)
        return im, NAVY, "#33477A", "#5A6B85", False
    im = Image.new("RGB", (W, H), TERANG)
    L.lengkung(ImageDraw.Draw(im))
    return im, NAVY, L.ABU_LEMBUT, "#8A98AE", False


def corak_untuk(nomor):
    """Pola diagonal grid 3x3: (baris + kolom) % 3 supaya tiap baris & kolom berselang-seling."""
    r, c = divmod(nomor - 1, 3)
    return CORAK[(r + c) % 3]


def cover(data, nomor):
    corak = corak_untuk(nomor)
    im, warna_judul, warna_sub, warna_kecil, putih = _corak_latar(corak, None)
    d = ImageDraw.Draw(im)
    d.im = im

    lg = L.logo(navy=not putih, lebar=205)
    im.paste(lg, (M, 76), lg)

    d.text((M, 76 + lg.height + 16), data["kicker"].upper(),
           font=L.font("Poppins-SemiBold", 23), fill="#C9D6E8" if putih else L.ABU_LEMBUT)

    y = 380
    f_judul = L.font("Playfair-Bold", 104)
    while L.tinggi_teks(d, data["judul"], f_judul, L.LEBAR - 40, 8) > 400 and f_judul.size > 56:
        f_judul = L.font("Playfair-Bold", f_judul.size - 4)
    y = L.tulis(d, data["judul"], f_judul, M, y, L.LEBAR - 40, warna_judul, spasi=8)

    d.line([(M, y + 34), (M + 150, y + 34)], fill=L.BIRU_MUDA if not putih else "#3C4C68", width=5)
    y += 92
    y = L.tulis(d, data["sub"], L.font("Poppins-Light", 38), M, y, L.LEBAR - 120, warna_sub, spasi=10)

    # penanda carousel 3 slide
    f_tag = L.font("Poppins-SemiBold", 28)
    tag = "1/3  ·  GESER"
    tw = d.textlength(tag, font=f_tag)
    d.rounded_rectangle([(M, H - 250), (M + tw + 76, H - 250 + 74)], radius=37,
                        fill="#FFFFFF" if putih else NAVY)
    d.text((M + 38, H - 250 + 20), tag, font=f_tag, fill=NAVY if putih else "#FFFFFF")

    L._kaki(d, putih=putih)

    # nomor urut feed (bukan nomor slide) di kanan atas
    f_no = L.font("Poppins-Regular", 26)
    no = f"{nomor:02d}"
    d.text((W - M - d.textlength(no, font=f_no), 120), no, font=f_no,
           fill="#8FA0B8" if putih else "#93A3B8")
    return im


def grid_mockup(files, keluar, cell=420, gap=10, judul="9 cover carousel The Skin Code · pola latar selang-seling"):
    baris = (len(files) + 2) // 3
    k = Image.new("RGB", (3 * cell + 4 * gap, 118 + baris * cell + (baris + 1) * gap), "#FFFFFF")
    d = ImageDraw.Draw(k)
    f = L.font("Poppins-SemiBold", 34)
    while d.textlength(judul, font=f) > k.width - 2 * (gap + 8) and f.size > 20:
        f = L.font("Poppins-SemiBold", f.size - 2)
    d.text((gap + 8, 40), judul, font=f, fill=NAVY)
    for i, p in enumerate(files):
        im = Image.open(p).convert("RGB")
        s = min(im.size)
        kiri = (im.size[0] - s) // 2
        im = im.crop((kiri, 0, kiri + s, s)).resize((cell, cell), Image.LANCZOS)
        r, c = divmod(i, 3)
        k.paste(im, (gap + c * (cell + gap), 118 + gap + r * (cell + gap)))
    k.save(keluar, quality=92)
    print("ok:", keluar, k.size)


if __name__ == "__main__":
    berkas = []
    for i, t in enumerate(TOPIK, 1):
        p = f"{OUT}/tsc_cover_{i:02d}.jpg"
        cover(t, i).save(p, quality=93)
        berkas.append(p)
        print("ok:", p, "corak", corak_untuk(i))
    grid_mockup(berkas, f"{OUT}/grid_3x3.jpg")
