"""FA SoccerRating expanded Web Push artwork v2.
Presentation only. Preserves verified match content and uses only existing saved crests.
No external image requests; no state changes to match/queue/strategy databases.
"""
from __future__ import annotations

from pathlib import Path
import os
import re

def render_match_alert(result, *, logo_lookup, logo_dir, base, log=None):
    """Return existing-format PNG URL for first fixture in alert, or None."""
    fixtures = result.get("notificationFixtures") if isinstance(result, dict) else None
    alert_id = result.get("alertId") if isinstance(result, dict) else None
    if (not isinstance(fixtures, list) or not fixtures
            or not re.fullmatch(r"[a-f0-9]{32}", str(alert_id or ""))):
        return None
    try:
        from PIL import Image, ImageDraw, ImageFont, ImageOps
        item=fixtures[0]
        teams=[str(item["home"]).strip(),str(item["away"]).strip()]
        if not all(teams):
            return None
        logos=logo_lookup()
        W,H=1024,620
        img=Image.new("RGB",(W,H),"#f7fbff")
        d=ImageDraw.Draw(img)
        fonts=Path(os.environ.get("WINDIR","C:/Windows"))/"Fonts"
        bold=fonts/"segoeuib.ttf"
        regular=fonts/"segoeui.ttf"
        if not bold.exists():bold=Path("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf")
        if not regular.exists():regular=Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf")
        def font(size,heavy=False):
            fn=bold if heavy else regular
            return ImageFont.truetype(str(fn),size) if fn.exists() else ImageFont.load_default()
        def tw(t,f): return d.textbbox((0,0),str(t),font=f)[2]
        def fit(s,limit,size,minsize=15,heavy=True):
            s=str(s or "").strip()
            while size>minsize and tw(s,font(size,heavy))>limit:size-=1
            while len(s)>4 and tw(s,font(size,heavy))>limit:
                s=s[:-4].rstrip()+"…"
            return s,font(size,heavy)
        def text_center(text,cx,y,f,fill):
            d.text((int(cx-tw(text,f)/2),int(y)),text,font=f,fill=fill)
        def blend(a,b,t):
            a=tuple(int(a[i:i+2],16) for i in (1,3,5))
            b=tuple(int(b[i:i+2],16) for i in (1,3,5))
            return tuple(round(a[k]*(1-t)+b[k]*t) for k in range(3))
        # Clip premium navy hero to rounded bounds rather than faking a team crest.
        mask=Image.new("L",(W,H),0)
        md=ImageDraw.Draw(mask)
        md.rounded_rectangle((3,3,1020,326),radius=26,fill=255)
        hero=Image.new("RGB",(W,H),"#0a2b60")
        hd=ImageDraw.Draw(hero)
        for y in range(3,327):
            t=(y-3)/324
            hd.line((3,y,1020,y),fill=blend("#07377c","#041d47",t),width=1)
        hd.ellipse((-215,80,530,530),outline="#104b9b",width=16)
        hd.ellipse((740,-300,1290,280),outline="#19539f",width=27)
        hd.arc((400,-190,1340,370),188,350,fill="#174f94",width=9)
        img.paste(hero,(0,0),mask)
        d=ImageDraw.Draw(img)
        d.rounded_rectangle((2,2,1021,618),radius=27,outline="#d8e6fa",width=3)
        # Header inside expanded picture, native header remains readable when collapsed.
        d.text((30,21),"SOCCERRATING  /  MATCH ALERT",font=font(22,True),fill="#f5fbff")
        multiple=len(fixtures)>1
        label=(f"{len(fixtures)} NEW FIXTURES" if multiple else
               "RESTORED PICK" if result.get("restored") else "NEW PICK")
        label,f_label=fit(label,280,19,13,True)
        d.rounded_rectangle((756,18,993,59),radius=18,fill="#1559af",outline="#3d82d1",width=2)
        text_center(label,875,28,f_label,"#fdfefe")
        # Use ONLY the existing approved local crest library. Otherwise initials.
        def norm(t): return re.sub(r"\s+"," ",str(t or "").strip()).casefold()
        for i,team in enumerate(teams):
            cx=260 if i==0 else 764
            d.rounded_rectangle((cx-93,71,cx+93,257),radius=27,
                                fill="#164982",outline="#4a86cf",width=2)
            record=logos.get(norm(team)) if isinstance(logos,dict) else None
            file_name=str((record or {}).get("url") or "").rsplit("/",1)[-1]
            candidate=Path(logo_dir)/file_name
            allowed=bool(re.fullmatch(r"[a-f0-9]{16}\.(png|jpg|webp|gif)",file_name))
            used=False
            if allowed and candidate.is_file():
                try:
                    with Image.open(candidate) as raw:
                        if raw.width>4096 or raw.height>4096:raise ValueError("Logo exceeds safe limits")
                        overlay=ImageOps.contain(raw.convert("RGBA"),(155,156))
                        img.paste(overlay,(cx-overlay.width//2,164-overlay.height//2),overlay)
                        used=True
                except (OSError,ValueError):pass
            if not used:
                letters="".join(x[0] for x in team.split()[:2] if x).upper() or "?"
                letters,let_font=fit(letters,120,72,32,True)
                text_center(letters,cx,122,let_font,"#e2efff")
            name,name_font=fit(team,450,27,18,True)
            text_center(name,cx,272,name_font,"#ffffff")
        d.rounded_rectangle((475,163,549,237),radius=37,
                            fill="#1f5eab",outline="#6da2e8",width=2)
        text_center("VS",512,182,font(29,True),"#ffffff")
        # Original fixture date, source strategy and sheet, no invented kickoff.
        d.rounded_rectangle((18,348,1006,410),radius=18,fill="#e8f2ff")
        meta=f"{item['match_date']}   |   STRATEGY {item['strategy']}   |   SHEET {item['sheet']}"
        meta,meta_font=fit(meta,950,26,18,True)
        text_center(meta,512,363,meta_font,"#173e78")
        cells=[
            ("HOME",item["home_odds"],"#dceaff","#0d2c62"),
            ("DRAW",item["draw_odds"],"#ffe8bc","#54320b"),
            ("AWAY",item["away_odds"],"#e8dcff","#38236d"),
        ]
        for idx,(title,odd,bg,ink) in enumerate(cells):
            left=18+idx*335
            d.rounded_rectangle((left,426,left+321,531),radius=19,fill=bg)
            d.text((left+19,442),title,font=font(21,True),fill=ink)
            val=f"{float(odd):.2f}"
            val_font=font(39,True)
            d.text((left+302-tw(val,val_font),465),val,font=val_font,fill=ink)
        d.rounded_rectangle((18,546,1006,606),radius=24,fill="#dcecff")
        action=("TAP TO OPEN REVIEW QUEUE" if multiple else
                "TAP NOTIFICATION TO REVIEW THIS FIXTURE")
        text_center(action,505,562,font(21,True),"#163f81")
        # Render a bounded, idempotent alert image; never change match data.
        out=Path(base)/"soccerrating_push_images"
        out.mkdir(parents=True,exist_ok=True)
        target=out/(alert_id+".png")
        tmp=out/(alert_id+".tmp.png")
        img.save(tmp,"PNG",optimize=True)
        os.replace(tmp,target)
        return "/soccerrating-push-images/"+alert_id+".png"
    except Exception as exc:
        if log:
            log("SoccerRating v2 image unavailable; text-only fallback: "+repr(exc)[:160])
        return None
