"""Per-product share images (Open Graph / WhatsApp / Facebook / X previews).

GET /api/og/<slug>.jpg returns a 1200×630 progressive JPEG (~40–70 KB) with the product name, key specs, live price,
condition and warranty. If the product has a real photo, it is shown on the right. Images are cached on disk and
regenerated automatically when the price, name or photo changes.

These cards are for link previews only. They are never used as the product photo in Google Shopping or
schema images, because Google requires real photos of the product.
"""
import hashlib
import io
import os
import re

from django.conf import settings
from django.http import FileResponse, Http404
from PIL import Image, ImageDraw, ImageFont

from .db import get_db

W, H = 1200, 630
FONTS = os.path.join(os.path.dirname(__file__), "assets", "fonts")
NAVY, NAVY2, ORANGE, WHITE, MUTED, GREEN = (16, 33, 63), (27, 50, 96), (255, 107, 44), (255, 255, 255), (200, 210, 229), (18, 164, 108)
COND = {"new": "Brand new", "refurbished": "Refurbished", "ex-uk": "Ex-UK"}


def font(weight, size):
    return ImageFont.truetype(os.path.join(FONTS, f"Inter-{weight}.otf"), size)


def wrap(draw, text, fnt, width, max_lines):
    words, lines, line = text.split(), [], ""
    for w in words:
        test = (line + " " + w).strip()
        if draw.textlength(test, font=fnt) <= width:
            line = test
        else:
            if line:
                lines.append(line)
            line = w
        if len(lines) == max_lines:
            break
    if line and len(lines) < max_lines:
        lines.append(line)
    if len(lines) == max_lines and " ".join(lines) != text:
        while draw.textlength(lines[-1] + "…", font=fnt) > width and " " in lines[-1]:
            lines[-1] = lines[-1].rsplit(" ", 1)[0]
        lines[-1] += "…"
    return lines


def render(p):
    im = Image.new("RGB", (W, H), NAVY)
    d = ImageDraw.Draw(im)
    # background accents
    d.ellipse([820, -260, 1460, 380], fill=NAVY2)
    d.rectangle([0, 0, W, 10], fill=ORANGE)
    photo = _photo(p)
    text_w = 640 if photo else 1040

    # logo
    d.rounded_rectangle([70, 52, 118, 100], radius=11, fill=(32, 50, 84))
    d.text((94, 76), "B", font=font("ExtraBold", 34), fill=ORANGE, anchor="mm")
    d.text((132, 56), settings.SITE_NAME, font=font("ExtraBold", 34), fill=WHITE)

    # product name
    y = 140
    name_font = font("ExtraBold", 54 if len(p["name"]) < 45 else 46 if len(p["name"]) < 80 else 40)
    for line in wrap(d, p["name"], name_font, text_w, 3):
        d.text((70, y), line, font=name_font, fill=WHITE)
        y += name_font.size + 10

    # spec chips
    sp = p.get("specs") or {}
    specs = [sp.get("cpu"), (sp.get("ram") + " RAM") if sp.get("ram") else None, sp.get("storage"), sp.get("gpu")]
    specs = [s for s in specs if s][:3]
    y += 14
    x = 70
    chip = font("SemiBold", 24)
    for s in specs:
        s = re.sub(r"\s*\(.*?\)", "", s)
        tw = d.textlength(s, font=chip)
        if x + tw + 32 > 70 + text_w:
            break
        d.rounded_rectangle([x, y, x + tw + 32, y + 44], radius=22, fill=NAVY2)
        d.text((x + 16, y + 8), s, font=chip, fill=MUTED)
        x += tw + 44

    # price + badges
    d.text((70, H - 175), f"KES {int(p['price']):,}", font=font("ExtraBold", 72), fill=ORANGE)
    badge = font("SemiBold", 24)
    bx = 70
    for label, color in ((COND.get(p["condition"], "New"), GREEN if p["condition"] == "new" else NAVY2),
                         (f"{p['warranty_months']}-month warranty" if p.get("warranty_months") else None, NAVY2),
                         ("Pay with M-Pesa", NAVY2)):
        if not label:
            continue
        tw = d.textlength(label, font=badge)
        d.rounded_rectangle([bx, H - 82, bx + tw + 28, H - 40], radius=8, fill=color)
        d.text((bx + 14, H - 75), label, font=badge, fill=WHITE)
        bx += tw + 40

    if photo:
        panel = Image.new("RGB", (430, 430), WHITE)
        photo.thumbnail((390, 390))
        panel.paste(photo, ((430 - photo.width) // 2, (430 - photo.height) // 2))
        mask = Image.new("L", panel.size, 0)
        ImageDraw.Draw(mask).rounded_rectangle([0, 0, 430, 430], radius=24, fill=255)
        im.paste(panel, (W - 430 - 60, 120), mask)
    else:
        d.text((W - 70 - d.textlength(_host(), font=font("Regular", 26)), H - 75), _host(), font=font("Regular", 26), fill=MUTED)
    return im


def _host():
    return settings.SITE_URL.split("//", 1)[-1].rstrip("/")


def _photo(p):
    if not p.get("images"):
        return None
    url = p["images"][0]
    if not url.startswith(settings.MEDIA_URL):
        return None
    path = os.path.join(settings.MEDIA_ROOT, url[len(settings.MEDIA_URL):])
    try:
        return Image.open(path).convert("RGB")
    except OSError:
        return None


def og_image(request, slug):
    p = get_db().products.find_one({"slug": slug, "active": True},
                                   {"name": 1, "price": 1, "specs": 1, "condition": 1, "warranty_months": 1, "images": 1})
    if not p:
        raise Http404
    key = hashlib.md5(f"{p['name']}|{p['price']}|{p.get('images', [''])[:1]}|{settings.SITE_NAME}|v2".encode()).hexdigest()[:10]
    folder = os.path.join(settings.MEDIA_ROOT, "og")
    os.makedirs(folder, exist_ok=True)
    path = os.path.join(folder, f"{slug}-{key}.jpg")
    if not os.path.exists(path):
        for old in os.listdir(folder):  # remove stale versions of this product's card
            if old.startswith(slug + "-") and old.endswith(".jpg"):
                os.remove(os.path.join(folder, old))
        buf = io.BytesIO()
        render(p).save(buf, "JPEG", quality=80, optimize=True, progressive=True)
        with open(path, "wb") as f:
            f.write(buf.getvalue())
    resp = FileResponse(open(path, "rb"), content_type="image/jpeg")
    resp["Cache-Control"] = "public, max-age=86400"
    return resp
