#!/usr/bin/env python3
"""Builds the made-up pictures used by the demo school (api/_core/demo_assets).
Drawn illustrations of made-up people - not photos of anyone, so no real child or adult is shown.
They are placeholders: real-looking AI portraits can be dropped into the same folder with the same file names later.

  python3 tools/demo_assets_build.py        (needs Pillow)

Output (all JPEG):
  photos/c<age group 0-3><m|f><1-6>.jpg   48 student portraits (0 = 3-5 yrs, 1 = 6-8, 2 = 9-11, 3 = 12-14)
  photos/s<m|f><1-6>.jpg                  12 staff portraits
  docs/*.jpg                              sample documents, each stamped "DEMO SAMPLE - Not a real document"
"""
import os, random
from PIL import Image, ImageDraw, ImageFont, ImageFilter

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'api', '_core', 'demo_assets')
SS = 4            # drawing at 4x, then reduced: smooth edges
SIZE = 120

SKIN = [(246, 214, 189), (236, 190, 154), (224, 172, 131), (198, 140, 98), (168, 112, 76), (141, 92, 62)]
HAIR = [(30, 24, 22), (52, 36, 28), (78, 52, 34), (20, 20, 24), (96, 64, 40), (40, 30, 30)]
BG = [(214, 234, 226), (221, 232, 245), (240, 226, 214), (228, 224, 242), (245, 236, 205), (216, 238, 238)]
SHIRT = [(255, 255, 255), (232, 241, 250), (255, 255, 255), (226, 238, 246), (255, 255, 255), (236, 242, 236)]
TIE = [(0, 94, 70), (24, 56, 110), (0, 94, 70), (120, 28, 40), (24, 56, 110), (0, 94, 70)]


def ell(d, cx, cy, rx, ry, fill):
    d.ellipse([(cx - rx) * SS, (cy - ry) * SS, (cx + rx) * SS, (cy + ry) * SS], fill=fill)


def person(seed, age, female, adult=False):
    r = random.Random(seed)
    W = SIZE * SS
    img = Image.new('RGB', (W, W), BG[r.randrange(len(BG))])
    d = ImageDraw.Draw(img)
    skin = SKIN[r.randrange(len(SKIN))]
    hair = HAIR[r.randrange(len(HAIR))]
    shirt = SHIRT[r.randrange(len(SHIRT))]
    tie = TIE[r.randrange(len(TIE))]
    # younger = bigger head, narrower shoulders
    k = {0: 1.0, 1: 0.94, 2: 0.9, 3: 0.86}.get(age, 0.88)
    if adult: k = 0.82
    cx = SIZE / 2
    hr_x, hr_y = 31 * k + 4, 36 * k + 5          # head radii
    hy = 66 if not adult else 62                  # head centre
    sh_w = 48 + (6 if adult else 0) + (3 - age if not adult else 0) * -2
    # shoulders / uniform
    d.pieslice([(cx - sh_w - 10) * SS, 112 * SS, (cx + sh_w + 10) * SS, 215 * SS], 180, 360, fill=shirt)
    d.rectangle([(cx - 11) * SS, (hy + hr_y - 6) * SS, (cx + 11) * SS, 116 * SS], fill=tuple(int(c * 0.93) for c in skin))
    if female and r.random() < 0.5 or adult and female and r.random() < 0.35:
        # tunic with a scarf over the shoulders
        d.pieslice([(cx - sh_w - 10) * SS, 112 * SS, (cx + sh_w + 10) * SS, 215 * SS], 180, 360, fill=(0, 94, 70) if r.random() < 0.6 else (24, 56, 110))
        d.polygon([((cx - 22) * SS, 113 * SS), ((cx + 22) * SS, 113 * SS), (cx * SS, 134 * SS)], fill=shirt)
    else:
        d.polygon([((cx - 9) * SS, 112 * SS), ((cx + 9) * SS, 112 * SS), (cx * SS, 126 * SS)], fill=shirt)
        d.polygon([((cx - 3) * SS, 118 * SS), ((cx + 3) * SS, 118 * SS), ((cx + 2) * SS, 142 * SS), ((cx - 2) * SS, 142 * SS)], fill=tie)
    # hair behind
    style = r.randrange(3)
    if female:
        if style == 0:     # long hair
            d.rounded_rectangle([(cx - hr_x - 6) * SS, (hy - hr_y * 0.6) * SS, (cx + hr_x + 6) * SS, (hy + hr_y + 28) * SS], radius=20 * SS, fill=hair)
        elif style == 1:   # two plaits
            for sx in (-1, 1):
                ell(d, cx + sx * (hr_x + 4), hy + hr_y * 0.7, 6, 20, hair)
                ell(d, cx + sx * (hr_x + 6), hy + hr_y * 1.25, 5, 5, tie)
        else:              # bun
            ell(d, cx, hy - hr_y - 4, 12, 10, hair)
    # ears + head
    ell(d, cx - hr_x, hy + 2, 5, 7, skin); ell(d, cx + hr_x, hy + 2, 5, 7, skin)
    ell(d, cx, hy, hr_x, hr_y, skin)
    # hair front
    if female:
        d.pieslice([(cx - hr_x - 3) * SS, (hy - hr_y - 4) * SS, (cx + hr_x + 3) * SS, (hy + hr_y * 0.35) * SS], 180, 360, fill=hair)
        if style != 2: d.polygon([((cx - hr_x) * SS, (hy - 4) * SS), ((cx - 4) * SS, (hy - hr_y * 0.75) * SS), ((cx + 8) * SS, (hy - 4) * SS), ((cx + hr_x * 0.4) * SS, (hy - hr_y * 0.5) * SS)], fill=skin) if False else None
    else:
        d.pieslice([(cx - hr_x - 2) * SS, (hy - hr_y - 5) * SS, (cx + hr_x + 2) * SS, (hy + hr_y * 0.25) * SS], 180, 360, fill=hair)
        if style == 2: ell(d, cx + 6, hy - hr_y - 1, 14, 6, hair)
        if adult and r.random() < 0.45:   # moustache
            d.arc([(cx - 10) * SS, (hy + 12) * SS, (cx + 10) * SS, (hy + 22) * SS], 200, 340, fill=hair, width=3 * SS)
    # face
    ey = hy - 1
    for sx in (-1, 1):
        ell(d, cx + sx * 12 * k - sx * 0, ey, 4.2, 4.8, (255, 255, 255))
        ell(d, cx + sx * 12 * k, ey + 0.5, 2.8, 3.2, (38, 26, 22))
        ell(d, cx + sx * 12 * k + 1, ey - 1, 0.9, 0.9, (255, 255, 255))
        d.arc([(cx + sx * 12 * k - 6) * SS, (ey - 11) * SS, (cx + sx * 12 * k + 6) * SS, (ey - 3) * SS], 200, 340, fill=hair, width=int(1.6 * SS))
    d.arc([(cx - 3) * SS, (hy + 2) * SS, (cx + 3) * SS, (hy + 12) * SS], 20, 160, fill=tuple(int(c * 0.78) for c in skin), width=int(1.4 * SS))
    d.arc([(cx - 10) * SS, (hy + 8) * SS, (cx + 10) * SS, (hy + 24) * SS], 25, 155, fill=(150, 62, 58), width=int(2.2 * SS))
    for sx in (-1, 1): ell(d, cx + sx * 19 * k, hy + 9, 5, 3.2, tuple(min(255, int(c * 1.04) + 10) if i == 0 else int(c * 0.92) for i, c in enumerate(skin)))
    img = img.resize((SIZE, SIZE), Image.LANCZOS)
    return img


def font(sz, bold=False):
    for p in ('/usr/share/fonts/truetype/dejavu/DejaVuSans%s.ttf' % ('-Bold' if bold else ''),):
        if os.path.exists(p): return ImageFont.truetype(p, sz)
    return ImageFont.load_default()


def doc(name, title, rows, extra=None):
    W, H = 420, 594
    img = Image.new('RGB', (W, H), (252, 252, 249))
    d = ImageDraw.Draw(img)
    d.rectangle([14, 14, W - 15, H - 15], outline=(0, 94, 70), width=3)
    d.rectangle([22, 22, W - 23, 78], fill=(0, 94, 70))
    d.text((W // 2, 40), 'DEMO SCHOOL', font=font(17, True), fill=(255, 255, 255), anchor='mm')
    d.text((W // 2, 62), title, font=font(14), fill=(220, 240, 232), anchor='mm')
    y = 112
    for k, v in rows:
        d.text((40, y), k, font=font(12), fill=(110, 120, 116))
        d.text((190, y), v, font=font(13, True), fill=(30, 40, 36))
        d.line([40, y + 22, W - 40, y + 22], fill=(226, 232, 229), width=1)
        y += 40
    if extra:
        for line in extra:
            d.text((40, y), line, font=font(12), fill=(70, 80, 76)); y += 20
    # stamp
    st = Image.new('RGBA', (W, H), (0, 0, 0, 0))
    sd = ImageDraw.Draw(st)
    sd.text((W // 2, H // 2 + 40), 'DEMO SAMPLE', font=font(46, True), fill=(200, 40, 40, 70), anchor='mm')
    sd.text((W // 2, H // 2 + 86), 'Not a real document', font=font(22, True), fill=(200, 40, 40, 70), anchor='mm')
    st = st.rotate(24, resample=Image.BICUBIC)
    img.paste(st, (0, 0), st)
    d = ImageDraw.Draw(img)
    d.text((W // 2, H - 38), 'DEMO SAMPLE - Not a real document. Made-up details.', font=font(10), fill=(160, 40, 40), anchor='mm')
    img.save(os.path.join(OUT, 'docs', name), 'JPEG', quality=62, optimize=True)


def logo():
    W = 96 * SS
    img = Image.new('RGBA', (W, W), (0, 0, 0, 0))
    d = ImageDraw.Draw(img)
    d.ellipse([4 * SS, 4 * SS, 92 * SS, 92 * SS], fill=(0, 122, 85))
    d.ellipse([10 * SS, 10 * SS, 86 * SS, 86 * SS], outline=(255, 255, 255), width=2 * SS)
    d.polygon([(48 * SS, 26 * SS), (74 * SS, 40 * SS), (48 * SS, 54 * SS), (22 * SS, 40 * SS)], fill=(255, 255, 255))
    d.rectangle([34 * SS, 48 * SS, 62 * SS, 62 * SS], fill=(255, 255, 255))
    d.polygon([(30 * SS, 62 * SS), (66 * SS, 62 * SS), (48 * SS, 70 * SS)], fill=(0, 122, 85))
    d.rectangle([72 * SS, 40 * SS, 74 * SS, 62 * SS], fill=(255, 214, 90))
    img.resize((96, 96), Image.LANCZOS).save(os.path.join(OUT, 'logo.png'), 'PNG', optimize=True)


def main():
    os.makedirs(os.path.join(OUT, 'photos'), exist_ok=True)
    os.makedirs(os.path.join(OUT, 'docs'), exist_ok=True)
    n = 0
    for g in range(4):
        for sx in 'mf':
            for k in range(1, 7):
                person(1000 + g * 100 + (50 if sx == 'f' else 0) + k, g, sx == 'f').save(os.path.join(OUT, 'photos', 'c%d%s%d.jpg' % (g, sx, k)), 'JPEG', quality=62, optimize=True); n += 1
    for sx in 'mf':
        for k in range(1, 7):
            person(5000 + (50 if sx == 'f' else 0) + k, 3, sx == 'f', adult=True).save(os.path.join(OUT, 'photos', 's%s%d.jpg' % (sx, k)), 'JPEG', quality=62, optimize=True); n += 1
    doc('birth.jpg', 'Birth Certificate (sample)', [('Child name', 'Sample Student'), ('Date of birth', '01-01-2018'), ('Place of birth', 'Sample City'), ('Father name', 'Sample Father'), ('Mother name', 'Sample Mother'), ('Registration no.', '0000-000000-0')])
    doc('result.jpg', 'Previous Result Card (sample)', [('Student', 'Sample Student'), ('Class', 'Grade 3'), ('English', '78 / 100'), ('Urdu', '82 / 100'), ('Mathematics', '90 / 100'), ('Result', 'Passed - Grade A')])
    doc('leaving.jpg', 'School Leaving Certificate (sample)', [('Student', 'Sample Student'), ('Last class', 'Grade 2'), ('Date of leaving', '30-03-2026'), ('Conduct', 'Good'), ('Dues', 'Cleared')])
    doc('admission.jpg', 'Admission Form (sample)', [('Student', 'Sample Student'), ('Class applied', 'Grade 1'), ('Father', 'Sample Father'), ('Phone', '0390 0000000'), ('Address', 'Sample address'), ('Date', '01-04-2026')])
    doc('idcopy.jpg', 'Parent ID copy (sample)', [('Name', 'Sample Father'), ('ID no.', '99999-9999999-9'), ('Date of birth', '01-01-1985'), ('Valid to', '01-01-2030')])
    logo()
    print('wrote', n, 'portraits and 5 sample documents to', os.path.abspath(OUT))


if __name__ == '__main__':
    main()
