"""Cardurile sociale și favicon-ul, desenate din aceleași date ca pagina.

Coloana din card e stratigrafia adevărată: grosimea fiecărei benzi e proporția
de tipuri a stratului, luată din content/data/strata.json.

Ieșiri: public/assets/og.png, og-en.png, facebook.png, facebook-en.png,
favicon.svg
"""
import json, os, sys

from PIL import Image, ImageDraw, ImageFont

HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "..", "content", "data")
OUT = os.path.join(HERE, "..", "public", "assets")
sys.path.insert(0, HERE)

W, H = 1200, 630
PAPER = (247, 244, 238)
INK = (26, 23, 18)
INK2 = (87, 79, 67)
INK3 = (131, 122, 107)
RULE = (221, 214, 200)
ACCENT = (42, 94, 168)
SED = [(201, 177, 138), (189, 168, 127), (177, 157, 117), (165, 146, 108)]

SERIF = "/System/Library/Fonts/Supplemental/Georgia.ttf"
SERIF_B = "/System/Library/Fonts/Supplemental/Georgia Bold.ttf"
SERIF_I = "/System/Library/Fonts/Supplemental/Georgia Italic.ttf"
SANS = "/System/Library/Fonts/Supplemental/Arial.ttf"

ORDER = [
    "substrat", "latina", "slava", "slavona", "maghiara", "greaca", "turca",
    "vecini", "germana", "latina_savanta", "italiana", "franceza", "engleza",
    "interna", "necunoscut",
]

TEXT = {
    "ro": {
        "kicker": "STRATIGRAFIE",
        "title": ["Straturile", "unui cuvânt"],
        "sub": "Cine a lăsat fiecare cuvânt din română, și când",
        "foot": "straturi.mariuscomper.uk",
        "dictionary": "DICȚIONAR",
        "speech": "VORBIRE",
        "french": "Franceză",
        "latin": "Latină",
        "claim": ["Franceza a umplut dicționarul.", "Latina ține propoziția în picioare."],
        "note": "Procente din cuvintele acoperite de clasificare.",
    },
    "en": {
        "kicker": "STRATIGRAPHY",
        "title": ["The Layers", "of a Word"],
        "sub": "Who left every Romanian word, and when",
        "foot": "straturi.mariuscomper.uk",
        "dictionary": "DICTIONARY",
        "speech": "SPEECH",
        "french": "French",
        "latin": "Latin",
        "claim": ["French filled the dictionary.", "Latin holds the sentence together."],
        "note": "Percent of words covered by the classification.",
    },
}


def font(path, size):
    return ImageFont.truetype(path, size)


def card(lang, strata, line):
    t = TEXT[lang]
    im = Image.new("RGB", (W, H), PAPER)
    d = ImageDraw.Draw(im)

    # coloana stratigrafică, la stânga
    col_x, col_w = 78, 96
    col_top, col_bot = 96, H - 96
    total = sum(s["types_all"] for s in strata.values())
    y = float(col_bot)
    gap = 3
    usable = (col_bot - col_top) - gap * (len(ORDER) - 1)
    for i, st in enumerate(ORDER):           # de jos în sus, cel mai vechi jos
        h = max(2.0, strata[st]["types_all"] / total * usable)
        d.rectangle([col_x, y - h, col_x + col_w, y], fill=SED[i % 4])
        y -= h + gap

    x = col_x + col_w + 62
    d.text((x, 92), t["kicker"], font=font(SANS, 20), fill=INK3)
    ty = 128
    for row in t["title"]:
        d.text((x, ty), row, font=font(SERIF_B, 74), fill=INK)
        ty += 84
    d.text((x, ty + 10), t["sub"], font=font(SERIF_I, 31), fill=INK2)

    d.line([x, H - 148, W - 70, H - 148], fill=RULE, width=1)
    d.text((x, H - 132), line[0], font=font(SANS, 25), fill=INK)
    d.text((x, H - 98), line[1], font=font(SANS, 25), fill=ACCENT)
    d.text((x, H - 62), t["note"], font=font(SANS, 16), fill=INK3)
    d.text((W - 70, H - 62), t["foot"], anchor="ra",
           font=font(SANS, 16), fill=INK3)
    return im


def facebook_card(lang, values):
    """Card 4:5 pentru feed, construit în jurul inversiunii centrale."""
    t = TEXT[lang]
    w, h = 1080, 1350
    im = Image.new("RGB", (w, h), PAPER)
    d = ImageDraw.Draw(im)

    d.text((72, 66), t["kicker"], font=font(SANS, 24), fill=INK3)
    d.text((72, 112), t["title"][0], font=font(SERIF_B, 86), fill=INK)
    d.text((72, 202), t["title"][1], font=font(SERIF_B, 86), fill=INK)
    d.line([72, 326, w - 72, 326], fill=RULE, width=2)

    panels = [
        (t["dictionary"], values["fr_t"], values["la_t"]),
        (t["speech"], values["fr_s"], values["la_s"]),
    ]
    y = 372
    for label, french, latin in panels:
        d.text((72, y), label, font=font(SANS, 25), fill=INK3)
        d.text((72, y + 54), t["french"], font=font(SERIF_B, 43), fill=INK)
        d.text((w - 72, y + 43), french, anchor="ra",
               font=font(SANS, 64), fill=INK)
        d.text((72, y + 132), t["latin"], font=font(SERIF_B, 43), fill=ACCENT)
        d.text((w - 72, y + 121), latin, anchor="ra",
               font=font(SANS, 64), fill=ACCENT)
        y += 260
        d.line([72, y - 34, w - 72, y - 34], fill=RULE, width=2)

    d.text((72, 922), t["claim"][0], font=font(SERIF_B, 49), fill=INK)
    d.text((72, 990), t["claim"][1], font=font(SERIF_B, 49), fill=ACCENT)
    d.text((72, h - 136), t["note"], font=font(SANS, 23), fill=INK3)
    d.text((72, h - 92), t["foot"], font=font(SANS, 27), fill=INK3)
    return im


def favicon(strata):
    total = sum(s["types_all"] for s in strata.values())
    y, gap, usable = 30.0, 0.7, 28.0
    rows = []
    for i, st in enumerate(ORDER):
        h = max(0.5, strata[st]["types_all"] / total * usable)
        rows.append((y - h, h, SED[i % 4]))
        y -= h + gap
    bands = "\n".join(
        f'  <rect x="4" y="{yy:.2f}" width="24" height="{h:.2f}" fill="rgb{c}"/>'
        for yy, h, c in rows)
    return f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
  <rect width="32" height="32" rx="4" fill="#f7f4ee"/>
{bands}
</svg>
'''


def main():
    strata = {s["id"]: s for s in json.load(
        open(os.path.join(DATA, "strata.json"), encoding="utf8"))}
    meta = json.load(open(os.path.join(DATA, "meta.json"), encoding="utf8"))
    ser = meta["series"]
    tot_types = sum(s["types_all"] for s in strata.values())
    fr_t = strata["franceza"]["types_all"] / tot_types * 100
    la_t = strata["latina"]["types_all"] / tot_types * 100
    sp = ser["vorbit"]
    fr_s = sp["per"]["franceza"] / sp["assigned"] * 100
    la_s = sp["per"]["latina"] / sp["assigned"] * 100
    # virgula zecimală se pune la cifră, nu la sfârșitul propoziției
    ro = lambda v: f"{v:.1f}".replace(".", ",")
    lines = {
        "ro": (f"Dicționar: franceză {ro(fr_t)}%, latină {ro(la_t)}%.",
               f"Vorbire: franceză {ro(fr_s)}%, latină {ro(la_s)}%."),
        "en": (f"Dictionary: French {fr_t:.1f}%, Latin {la_t:.1f}%.",
               f"Speech: French {fr_s:.1f}%, Latin {la_s:.1f}%."),
    }
    for lang, name in (("ro", "og.png"), ("en", "og-en.png")):
        im = card(lang, strata, lines[lang])
        im.save(os.path.join(OUT, name), optimize=True)
        print(f"  {name}: {os.path.getsize(os.path.join(OUT, name)):,} octeți")
    values = {
        "ro": {"fr_t": f"{ro(fr_t)}%", "la_t": f"{ro(la_t)}%",
               "fr_s": f"{ro(fr_s)}%", "la_s": f"{ro(la_s)}%"},
        "en": {"fr_t": f"{fr_t:.1f}%", "la_t": f"{la_t:.1f}%",
               "fr_s": f"{fr_s:.1f}%", "la_s": f"{la_s:.1f}%"},
    }
    for lang, name in (("ro", "facebook.png"), ("en", "facebook-en.png")):
        im = facebook_card(lang, values[lang])
        im.save(os.path.join(OUT, name), optimize=True)
        print(f"  {name}: {os.path.getsize(os.path.join(OUT, name)):,} octeți")
    with open(os.path.join(OUT, "favicon.svg"), "w", encoding="utf8") as f:
        f.write(favicon(strata))
    print("  favicon.svg")


if __name__ == "__main__":
    main()
