from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import math, json

ROOT=Path(__file__).resolve().parents[1]
FONT_PATH='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
FONT_BOLD='/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'
MONO='/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf'

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

def base_canvas(size=(1600,1000),seed=0):
    w,h=size
    im=Image.new('RGB',size,(8,9,11)); d=ImageDraw.Draw(im)
    # layered neutral grid and subtle red registration lines
    for x in range(0,w,80): d.line((x,0,x,h),fill=(20,22,25),width=1)
    for y in range(0,h,80): d.line((0,y,w,y),fill=(20,22,25),width=1)
    # quiet atmosphere
    for i in range(8):
        cx=(seed*137+i*211)%w; cy=(seed*97+i*149)%h; r=130+(i%3)*70
        overlay=Image.new('RGBA',size,(0,0,0,0)); od=ImageDraw.Draw(overlay)
        od.ellipse((cx-r,cy-r,cx+r,cy+r),fill=(255,255,255,6))
        im=Image.alpha_composite(im.convert('RGBA'),overlay.filter(ImageFilter.GaussianBlur(45))).convert('RGB')
    return im

def draw_window(d,box,label,accent=False):
    x0,y0,x1,y1=box
    d.rounded_rectangle(box,radius=20,fill=(13,15,18),outline=(78,82,88),width=2)
    d.line((x0,y0+58,x1,y0+58),fill=(52,56,62),width=1)
    d.text((x0+24,y0+18),label,font=font(MONO,18),fill=(220,222,224))
    if accent:
        d.rectangle((x1-94,y0+19,x1-24,y0+38),fill=(224,0,27))
    for i in range(3):
        d.ellipse((x1-28-i*24,y0+24,x1-18-i*24,y0+34),fill=(112,116,122))

def project_image(path,title,variant):
    im=base_canvas(seed=variant); d=ImageDraw.Draw(im)
    draw_window(d,(120,100,1480,900),f'PLACEHOLDER  {title}',accent=(variant%2==0))
    if variant==1:
        d.rectangle((190,220,650,780),fill=(22,24,28),outline=(96,100,108),width=2)
        for i,w in enumerate([340,270,390,220,310]): d.rectangle((230,270+i*86,230+w,292+i*86),fill=(194,196,200) if i==0 else (104,108,114))
        d.rectangle((730,220,1400,480),fill=(18,20,23),outline=(78,82,88),width=2)
        pts=[]
        for i in range(12): pts.append((780+i*48,420-int((math.sin(i*.7)+1)*60)-i*3))
        d.line(pts,fill=(224,0,27),width=5)
        for p in pts: d.ellipse((p[0]-5,p[1]-5,p[0]+5,p[1]+5),fill=(240,240,240))
        d.rectangle((730,540,1400,780),fill=(18,20,23),outline=(78,82,88),width=2)
        for r in range(3):
            d.rectangle((780,585+r*58,1010,610+r*58),fill=(180,182,186))
            d.rectangle((1040,585+r*58,1330,610+r*58),fill=(68,72,78))
    elif variant==2:
        for i in range(4):
            x=190+i*285
            d.rounded_rectangle((x,235,x+230,690),radius=12,fill=(20+i*3,22+i*3,25+i*3),outline=(94,98,104),width=2)
            d.rectangle((x+28,285,x+202,470),fill=(36,39,44))
            d.text((x+28,515),f'0{i+1}',font=font(FONT_BOLD,44),fill=(236,236,236))
            for j in range(3): d.rectangle((x+28,585+j*34,x+155-j*15,598+j*34),fill=(100,104,110))
        d.line((190,750,1315,750),fill=(224,0,27),width=4)
    elif variant==3:
        d.rectangle((190,220,720,790),fill=(245,245,243),outline=(120,124,128),width=2)
        d.text((235,270),'A',font=font(FONT_BOLD,150),fill=(8,9,11))
        d.text((430,300),'あ',font=font(FONT_BOLD,116),fill=(8,9,11))
        for i in range(7): d.rectangle((240,500+i*34,620-(i%3)*70,513+i*34),fill=(38,40,43))
        d.rectangle((790,220,1400,790),fill=(17,19,22),outline=(92,96,102),width=2)
        for i in range(5):
            y=285+i*92
            d.text((840,y),['DATE','TITLE','IMAGE','SHARE','COMMENTS'][i],font=font(MONO,18),fill=(214,216,220))
            d.rectangle((1040,y,1320,y+22),fill=(82+i*12,86+i*12,92+i*12))
    else:
        d.rectangle((190,220,1400,360),fill=(16,18,21),outline=(84,88,94),width=2)
        for i in range(5):
            x=240+i*220
            d.ellipse((x,270,x+44,314),outline=(230,230,230),width=3)
            if i<4:d.line((x+44,292,x+210,292),fill=(90,94,100),width=2)
        for r in range(3):
            y=440+r*105
            d.rounded_rectangle((210,y,1380,y+72),radius=10,fill=(18+r*3,20+r*3,23+r*3),outline=(80,84,90),width=2)
            d.text((250,y+23),f'SERVICE PATH {r+1}',font=font(MONO,20),fill=(215,217,220))
            d.rectangle((1120,y+22,1325,y+50),fill=(224,0,27) if r==0 else (190,192,196))
    im.save(path,quality=94)

def post_image(path,title,variant):
    im=base_canvas(seed=20+variant); d=ImageDraw.Draw(im)
    d.text((110,90),f'EDITORIAL PLACEHOLDER  0{variant}',font=font(MONO,21),fill=(210,212,216))
    if variant==1:
        for i in range(5):
            off=i*48
            d.rounded_rectangle((250+off,210+off,1250-off,790-off),radius=20,fill=(12+i*8,14+i*8,17+i*8),outline=(86+i*16,90+i*16,96+i*16),width=2)
        d.line((360,650,1180,360),fill=(224,0,27),width=5)
    elif variant==2:
        d.rectangle((180,180,870,820),fill=(240,240,238),outline=(100,104,108),width=2)
        d.text((240,240),'EVIDENCE',font=font(FONT_BOLD,72),fill=(10,11,13))
        for i in range(8): d.rectangle((245,370+i*44,720-(i%3)*65,386+i*44),fill=(38,40,44))
        for x,y in [(1060,270),(1220,430),(1010,620)]:
            d.ellipse((x-70,y-70,x+70,y+70),outline=(224,0,27),width=8)
            d.line((x-35,y,x+35,y),fill=(230,230,230),width=4)
            d.line((x,y-35,x,y+35),fill=(230,230,230),width=4)
    else:
        d.rounded_rectangle((170,170,1430,830),radius=24,fill=(16,18,21),outline=(100,104,110),width=2)
        d.text((240,260),'EN',font=font(FONT_BOLD,116),fill=(245,245,245))
        d.text((530,260),'日本語',font=font(FONT_BOLD,90),fill=(245,245,245))
        for i in range(6):
            y=470+i*48
            d.rectangle((245,y,620-(i%2)*80,y+16),fill=(140,144,150))
            d.rectangle((760,y,1260-(i%3)*70,y+16),fill=(86,90,96))
        d.line((690,230,690,760),fill=(224,0,27),width=4)
    d.text((110,900),title.upper(),font=font(FONT_BOLD,42),fill=(238,238,238))
    im.save(path,quality=95)

def cover_resize(im,size,focal=(.5,.5)):
    tw,th=size; sw,sh=im.size
    scale=max(tw/sw,th/sh); nw,nh=round(sw*scale),round(sh*scale)
    im=im.resize((nw,nh),Image.Resampling.LANCZOS)
    fx,fy=focal
    left=max(0,min(nw-tw,round(fx*nw-tw/2))); top=max(0,min(nh-th,round(fy*nh-th/2)))
    return im.crop((left,top,left+tw,top+th))

def calling_card(src,out,size,title,section,date,focal):
    im=cover_resize(Image.open(src).convert('RGB'),size,focal)
    w,h=size
    overlay=Image.new('RGBA',size,(0,0,0,0)); od=ImageDraw.Draw(overlay)
    od.rectangle((0,0,w,h),fill=(0,0,0,90))
    panel_h=max(170,int(h*.36))
    od.rectangle((0,h-panel_h,w,h),fill=(2,3,4,235))
    od.line((0,h-panel_h,w,h-panel_h),fill=(224,0,27,255),width=max(3,w//400))
    im=Image.alpha_composite(im.convert('RGBA'),overlay)
    d=ImageDraw.Draw(im)
    pad=max(32,w//24)
    small=font(MONO,max(16,w//54)); big=font(FONT_BOLD,max(28,w//28))
    d.text((pad,h-panel_h+pad),f'{section.upper()}   {date}',font=small,fill=(230,232,234))
    # wrap title
    maxw=w-pad*2; words=title.split(); lines=[]; line=''
    for word in words:
        test=(line+' '+word).strip()
        if d.textlength(test,font=big)>maxw and line:
            lines.append(line); line=word
        else: line=test
    if line: lines.append(line)
    y=h-panel_h+pad+small.size+18
    for line in lines[:3]:
        d.text((pad,y),line,font=big,fill=(255,255,255)); y+=big.size+8
    d.text((w-pad- d.textlength('YOUR BRAND',font=small),h-pad-small.size),'YOUR BRAND',font=small,fill=(210,212,216))
    out.parent.mkdir(parents=True,exist_ok=True)
    im.convert('RGB').save(out,quality=95)

# images
place=ROOT/'assets/img/placeholders'; posts_dir=ROOT/'assets/img/posts'
project_image(place/'project-alpha.png','PROJECT ALPHA',1)
project_image(place/'project-beta.png','PROJECT BETA',2)
project_image(place/'project-gamma.png','PROJECT GAMMA',3)
project_image(place/'project-delta.png','PROJECT DELTA',4)
# about
about=base_canvas((1200,1200),44); d=ImageDraw.Draw(about); draw_window(d,(100,100,1100,1100),'ABOUT PORTRAIT OR STUDIO',True)
d.ellipse((330,245,870,785),outline=(210,212,216),width=4)
d.rectangle((280,820,920,925),fill=(25,28,32),outline=(104,108,114),width=2)
for i in range(4): d.rectangle((330,850+i*18,780-i*55,860+i*18),fill=(125,129,135))
about.save(place/'about-placeholder.png',quality=95)
post_image(posts_dir/'post-depth.png','Designing for depth',1)
post_image(posts_dir/'post-evidence.png','Building a useful case study',2)
post_image(posts_dir/'post-localisation.png','Offline localisation',3)
# calling cards
posts=json.loads((ROOT/'content/posts.json').read_text())
for p in posts:
    src=ROOT/p['image']; outdir=ROOT/'assets/img/calling-cards'/p['slug']
    specs={'social-1200x630.png':(1200,630),'square-1200.png':(1200,1200),'landscape-1200x900.png':(1200,900),'wide-1600x900.png':(1600,900)}
    for name,size in specs.items():
        calling_card(src,outdir/name,size,p['title']['en'],p['section']['en'],p['datePublished'],(p['focalPoint']['x'],p['focalPoint']['y']))
# social preview
Image.open(ROOT/'assets/img/calling-cards/designing-for-depth/social-1200x630.png').save(ROOT/'assets/img/social-preview.png')
# touch icon
icon=Image.new('RGB',(180,180),(2,3,4)); d=ImageDraw.Draw(icon); d.rectangle((35,35,145,145),outline=(224,0,27),width=9); d.text((63,62),'Y',font=font(FONT_BOLD,60),fill=(255,255,255)); icon.save(ROOT/'assets/img/apple-touch-icon.png')
print('Generated placeholder and calling-card images.')
