"""
brand_service.py — the brand assets (logo, watermark, 10x15 card template) and the watermark itself.

Two levels (client 2026-10-28: "the branding must follow the school in use"): the DEFAULT one (Meeconic's, every
school) and, optionally, a school's own. A school uses its own file or setting where it has one and the default
everywhere else, asset by asset: `resolve(kind, school_id)` is the only place that decides. Every function takes
`school_id=None`; None is the default level, so callers that pass nothing get exactly what they always got.
Files of a school live in ASSETS_DIR/schools/{school}/ (next to its crest), its watermark settings in app_kv
"brand_watermark:{school}". The public logo URL carries `school=` only when the school has its own logo.

The client sends these later; until then every one of them has a built-in PLACEHOLDER so the site works and looks
finished: the text logo "MEECONIC", a tiled text watermark "MEECONIC", the built-in card design. The operator
uploads the real file in Settings → Branding and it is used from the next request on (no redeploy):

    ASSETS_DIR/logo.png             shown in the portal/admin header and on the card
    ASSETS_DIR/watermark.png        stamped on every photo a family sees before paying (tiled or centred)
    ASSETS_DIR/card_template.png    background of the 10x15 sheet (1200x1800), see card_service
    ASSETS_DIR/card_template.json   where the QR, code, photos and class go on that background

Watermark (client request: "a watermark on all photos displayed on the website, originals, sibling photos and
AI photos"): it is the LAST stage of every pre-payment preview (media_service.render_preview), on top of the
face protection or the reduced copy, so no preview path can skip it. The admin's own thumbnails stay clean (staff
only, signed) and a PAID download is the untouched original. The stamped file's name carries a fingerprint of the
watermark settings + asset + base preview: changing the watermark changes what is served, like protection_service.
"""
import hashlib
import io
import json
import logging
import re
from functools import lru_cache
from pathlib import Path
from typing import Optional

from PIL import Image, ImageDraw, ImageFont, ImageOps

from core import config
from core.db import get_db

logger = logging.getLogger("meeconic.brand")

KINDS = {"logo", "watermark", "card_template"}
MAX_UPLOAD_BYTES = 8 * 1024 * 1024
CARD_SIZE = (1200, 1800)
_KV_KEY = "brand_watermark"
_FONT = Path(__file__).resolve().parent.parent / "fonts" / "Inter-Bold.ttf"

# Placeholder until the client says how the watermark must look (they were asked). Tiled diagonal text: covers the
# face area whatever the framing, and stays readable on light and dark photos (white with a dark outline).
DEFAULT_WATERMARK = {"enabled": True, "mode": "tile", "opacity": 32, "scale": 18, "text": "MEECONIC"}


class BrandError(ValueError):
    pass


def _dir(school_id: Optional[str] = None) -> Path:
    if not school_id:
        return config.ASSETS_DIR
    if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}", school_id):     # it becomes a folder name (public route)
        raise BrandError("Unknown school.")
    return config.ASSETS_DIR / "schools" / school_id


def asset_path(kind: str, school_id: Optional[str] = None) -> Path:
    """The file of THAT level (what an upload writes and a reset removes), whether it exists or not."""
    if kind not in KINDS:
        raise BrandError("Unknown asset.")
    return _dir(school_id) / f"{kind}.png"


def resolve(kind: str, school_id: Optional[str] = None) -> Path:
    """The file in use for a school: its own when it has one, else the default one (which may not exist either)."""
    own = asset_path(kind, school_id)
    return own if school_id and own.is_file() else asset_path(kind)


def own(kind: str, school_id: Optional[str] = None) -> bool:
    return asset_path(kind, school_id).is_file()


def template_zones_path(school_id: Optional[str] = None) -> Path:
    return _dir(school_id) / "card_template.json"


def has(kind: str, school_id: Optional[str] = None) -> bool:
    return resolve(kind, school_id).is_file()


def version(kind: str, school_id: Optional[str] = None) -> int:
    try:
        return int(resolve(kind, school_id).stat().st_mtime)
    except OSError:
        return 0


def save_asset(kind: str, data: bytes, school_id: Optional[str] = None) -> dict:
    """Validate and store an uploaded asset, re-encoded as PNG (keeps transparency; drops anything but pixels)."""
    if kind not in KINDS:
        raise BrandError("Unknown asset.")
    if not data or len(data) > MAX_UPLOAD_BYTES:
        raise BrandError(f"The file must be an image of at most {MAX_UPLOAD_BYTES // 1048576} MB.")
    try:
        with Image.open(io.BytesIO(data)) as im:
            im = ImageOps.exif_transpose(im)
            im.load()
            img = im.convert("RGBA")
    except Exception:
        raise BrandError("Not a valid image (PNG, JPEG or WebP).")
    if kind == "card_template":
        w, h = img.size
        if abs(w / h - 2 / 3) > 0.02:
            raise BrandError("The card template must be portrait 10x15 (2:3), ideally 1200x1800 px.")
        img = img.convert("RGB").resize(CARD_SIZE, Image.LANCZOS)
    elif kind == "logo":
        img.thumbnail((1200, 400), Image.LANCZOS)
    else:
        img.thumbnail((2000, 2000), Image.LANCZOS)
    path = asset_path(kind, school_id)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(".tmp")
    img.save(tmp, format="PNG", optimize=True)
    tmp.replace(path)
    _tone.cache_clear()
    _watermark_tile.cache_clear()
    logger.info("Brand asset %s replaced for %s (%dx%d)", kind, school_id or "every school", *img.size)
    return status(school_id)


def delete_asset(kind: str, school_id: Optional[str] = None) -> dict:
    """Default level: back to the built-in placeholder. A school: back to the default (its file, and for the
    watermark its own settings too, go)."""
    asset_path(kind, school_id).unlink(missing_ok=True)
    _tone.cache_clear()
    if kind == "card_template":
        template_zones_path(school_id).unlink(missing_ok=True)
    if kind == "watermark" and school_id:
        with get_db() as conn:
            conn.execute("DELETE FROM app_kv WHERE key=?", (_kv_key(school_id),))
            conn.commit()
    _watermark_tile.cache_clear()
    return status(school_id)


# ── The SCHOOL's own logo (its crest), one per school: drawn top-left on its 10x15 sheets like the client's leaflet ──

def crest_path(school_id: str) -> Path:
    if not school_id:
        raise BrandError("Unknown school.")
    return _dir(school_id) / "crest.png"


def save_crest(school_id: str, data: bytes) -> None:
    """Re-encoded as PNG like the other assets (only pixels we produced are ever served or printed)."""
    if not data or len(data) > MAX_UPLOAD_BYTES:
        raise BrandError(f"The file must be an image of at most {MAX_UPLOAD_BYTES // 1048576} MB.")
    try:
        with Image.open(io.BytesIO(data)) as im:
            im = ImageOps.exif_transpose(im)
            im.load()
            img = im.convert("RGBA")
    except Exception:
        raise BrandError("Not a valid image (PNG, JPEG or WebP).")
    img.thumbnail((1000, 1000), Image.LANCZOS)          # printed ~2 cm wide: 1000 px is far more than 305 dpi needs
    path = crest_path(school_id)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(".tmp")
    img.save(tmp, format="PNG", optimize=True)
    tmp.replace(path)
    logger.info("School %s: crest replaced (%dx%d)", school_id, *img.size)


def delete_crest(school_id: str) -> None:
    crest_path(school_id).unlink(missing_ok=True)


def crest_image(school_id: str, max_w: int, max_h: int) -> Optional[Image.Image]:
    """The school's crest fitted in max_w x max_h (RGBA), or None when the school has none."""
    try:
        with Image.open(crest_path(school_id)) as im:
            img = im.convert("RGBA")
    except (OSError, BrandError):
        return None
    img.thumbnail((max_w, max_h), Image.LANCZOS)
    return img


def save_template_zones(zones: dict, school_id: Optional[str] = None) -> None:
    from services import card_service
    clean = card_service.validate_zones(zones)
    path = template_zones_path(school_id)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(clean, indent=2), encoding="utf-8")


def template_zones(school_id: Optional[str] = None) -> Optional[dict]:
    """The school's own positions when it set some, else the default ones."""
    for path in ([template_zones_path(school_id)] if school_id else []) + [template_zones_path()]:
        try:
            return json.loads(path.read_text(encoding="utf-8"))
        except Exception:
            continue
    return None


def logo_url(school_id: Optional[str] = None) -> Optional[str]:
    if not has("logo", school_id):
        return None
    mine = f"&school={school_id}" if school_id and own("logo", school_id) else ""
    return f"/api/brand/logo.png?v={version('logo', school_id)}{mine}"


def public(school_id: Optional[str] = None) -> dict:
    """What the browser needs: the logo URL (versioned) or None (= the built-in text logo)."""
    url = logo_url(school_id)
    return {"logo_url": url, "logo_tone": logo_tone(school_id)} if url else {"logo_url": None}


def status(school_id: Optional[str] = None) -> dict:
    """`custom` = this level has its own (a school: its own file; default level: an uploaded file instead of the
    placeholder)."""
    return {
        "scope": "school" if school_id else "default",
        "logo": {"custom": own("logo", school_id), "url": logo_url(school_id), "tone": logo_tone(school_id)},
        "watermark": {"custom": own("watermark", school_id) or bool(school_id and _saved_watermark(school_id) is not None),
                      "config": get_watermark(school_id)},
        "card_template": {"custom": own("card_template", school_id), "zones": template_zones(school_id)},
    }


# ── Watermark settings (the default one, or a school's own) ──────────────────────────────────────────

def _kv_key(school_id: Optional[str]) -> str:
    return f"{_KV_KEY}:{school_id}" if school_id else _KV_KEY


def _saved_watermark(school_id: Optional[str]) -> Optional[dict]:
    try:
        with get_db() as conn:
            row = conn.execute("SELECT value FROM app_kv WHERE key=?", (_kv_key(school_id),)).fetchone()
        return json.loads(row["value"]) if row else None
    except Exception as exc:
        logger.warning("Watermark settings unreadable, using the defaults: %s", exc)
        return None


def get_watermark(school_id: Optional[str] = None) -> dict:
    saved = (_saved_watermark(school_id) if school_id else None)
    if saved is None:
        saved = _saved_watermark(None) or {}
    return {**DEFAULT_WATERMARK, **{k: v for k, v in saved.items() if k in DEFAULT_WATERMARK}}


def set_watermark(patch: dict, school_id: Optional[str] = None) -> dict:
    cur = get_watermark(school_id)
    for k, v in patch.items():
        if k not in DEFAULT_WATERMARK:
            raise BrandError(f"Unknown watermark setting: {k}")
        cur[k] = v
    if cur["mode"] not in ("tile", "center", "corner"):
        raise BrandError("mode must be tile, center or corner.")
    try:
        cur["opacity"] = int(cur["opacity"])
        cur["scale"] = int(cur["scale"])
    except (TypeError, ValueError):
        raise BrandError("opacity and scale must be numbers.")
    if not 5 <= cur["opacity"] <= 90 or not 5 <= cur["scale"] <= 80:
        raise BrandError("opacity must be 5–90 % and scale 5–80 %.")
    cur["enabled"] = bool(cur["enabled"])
    cur["text"] = " ".join(str(cur["text"] or "").split())[:40] or DEFAULT_WATERMARK["text"]
    with get_db() as conn:
        conn.execute("INSERT OR REPLACE INTO app_kv (key, value) VALUES (?,?)", (_kv_key(school_id), json.dumps(cur)))
        conn.commit()
    _watermark_tile.cache_clear()
    return cur


def watermark_fingerprint(cfg: dict, school_id: Optional[str] = None) -> str:
    raw = json.dumps(cfg, sort_keys=True) + f"|{version('watermark', school_id)}"
    if school_id and own("watermark", school_id):        # two schools' images can share settings and a second
        raw += f"|{school_id}"                             # (the default level keeps its old fingerprints: no re-stamp)
    return hashlib.sha1(raw.encode()).hexdigest()[:8]


@lru_cache(maxsize=16)
def _watermark_tile(width: int, fp: str, cfg_json: str, mark_file: str = "") -> Image.Image:
    """The mark itself (RGBA, already at its opacity), sized for a photo `width` px wide. `mark_file` = the
    watermark image in use ("" = the text placeholder)."""
    cfg = json.loads(cfg_json)
    target_w = max(40, int(width * cfg["scale"] / 100))
    alpha = cfg["opacity"] / 100
    if mark_file:
        with Image.open(mark_file) as im:
            mark = im.convert("RGBA")
        h = max(1, round(mark.height * target_w / mark.width))
        mark = mark.resize((target_w, h), Image.LANCZOS)
    else:
        text = cfg["text"]
        size = 10
        font = ImageFont.truetype(str(_FONT), size)
        while font.getlength(text) < target_w and size < 400:
            size += 2
            font = ImageFont.truetype(str(_FONT), size)
        stroke = max(1, size // 18)
        l, t, r, b = font.getbbox(text, stroke_width=stroke)
        mark = Image.new("RGBA", (r - l + 4, b - t + 4), (0, 0, 0, 0))
        ImageDraw.Draw(mark).text((2 - l, 2 - t), text, font=font, fill=(255, 255, 255, 255),
                                  stroke_width=stroke, stroke_fill=(20, 24, 40, 255))
    a = mark.getchannel("A").point(lambda v: int(v * alpha))
    mark.putalpha(a)
    return mark


def stamp(img: Image.Image, cfg: Optional[dict] = None, school_id: Optional[str] = None) -> Image.Image:
    """The watermark drawn on a copy of `img` (RGB in, RGB out). Disabled → `img` unchanged."""
    cfg = cfg or get_watermark(school_id)
    if not cfg["enabled"]:
        return img
    base = img.convert("RGBA")
    mark_path = resolve("watermark", school_id)
    mark = _watermark_tile(base.width, watermark_fingerprint(cfg, school_id), json.dumps(cfg, sort_keys=True),
                           str(mark_path) if mark_path.is_file() else "")
    W, H = base.size
    layer = Image.new("RGBA", (W, H), (0, 0, 0, 0))
    if cfg["mode"] == "tile":
        rot = mark.rotate(30, expand=True, resample=Image.BICUBIC)
        step_x, step_y = int(rot.width * 1.35), int(rot.height * 1.6)
        for row, y in enumerate(range(-rot.height, H + rot.height, max(step_y, 1))):
            offset = (step_x // 2) if row % 2 else 0
            for x in range(-rot.width + offset, W + rot.width, max(step_x, 1)):
                # Copied, not blended: pasting with the mark as its own mask applies its alpha twice (the mark
                # came out at a tenth of its opacity). The steps keep tiles apart, so there is nothing to blend.
                layer.paste(rot, (x, y))
    elif cfg["mode"] == "center":
        layer.paste(mark, ((W - mark.width) // 2, (H - mark.height) // 2))
    else:                                   # corner: bottom right, with a margin
        m = max(8, W // 40)
        layer.paste(mark, (W - mark.width - m, H - mark.height - m))
    return Image.alpha_composite(base, layer).convert("RGB")


def stamped_preview(base_preview, original, px: int, school_id: Optional[str] = None):
    """The served preview: `base_preview` (protected or reduced) + the school's watermark, cached next to it. Both
    are `core.storage` keys, and so is the result."""
    from core import storage
    from services import photo_service
    cfg = get_watermark(school_id)
    if not cfg["enabled"]:
        return base_preview
    kind = hashlib.sha1(base_preview.name.encode()).hexdigest()[:2]
    fp = watermark_fingerprint(cfg, school_id) + kind
    dst = photo_service.mirror_path(original, f".m{fp}.{px}.webp")
    try:
        have, base = storage.stat(dst), storage.stat(base_preview)
        if have is not None and base is not None and have.mtime >= base.mtime:
            return dst
        with Image.open(storage.local_path(base_preview)) as im:
            out = stamp(ImageOps.exif_transpose(im).convert("RGB"), cfg, school_id)
        storage.produce(dst, lambda tmp: out.save(tmp, format="WEBP", quality=78))
        prefix, suffix = f"{original.stem}.m", f".{px}.webp"
        for stale in storage.files(dst.parent):                          # older watermark settings
            if stale.key != dst and stale.name.startswith(prefix) and stale.name.endswith(suffix):
                storage.delete(stale.key)
        return dst
    except Exception as exc:
        # Never fall back to a clean preview: a family must not see an unmarked photo because stamping failed.
        logger.error("Watermark failed on %s: %s", base_preview, exc)
        raise


@lru_cache(maxsize=32)
def _tone(path: str, mtime_ns: int) -> str:
    try:
        with Image.open(path) as im:
            logo = im.convert("RGBA")
        logo.thumbnail((200, 200))
        alpha = logo.getchannel("A")
        if alpha.getextrema()[0] >= 250:               # no transparency: it brings its own (usually white) background
            return "dark"
        seen = alpha.point(lambda a: 255 if a > 128 else 0)
        hist = logo.convert("L").histogram(seen)
        if sum(hist[:90]) >= 0.03 * sum(hist):         # real dark ink, even when white boxes make the mean look bright
            return "dark"
        return "light" if sum(i * n for i, n in enumerate(hist)) / sum(hist) >= 170 else "dark"
    except Exception:                                  # unreadable or fully transparent: the safe answer is a plate
        return "dark"


def logo_tone(school_id: Optional[str] = None) -> Optional[str]:
    """"dark" = the logo needs a LIGHT background (dark ink, or opaque); "light" = it needs a DARK one (white ink).
    Headers and the family sheet put a plate behind it when the background they have is the wrong one, so any
    client's logo stays readable."""
    try:
        path = resolve("logo", school_id)
        return _tone(str(path), path.stat().st_mtime_ns)
    except OSError:                                    # no logo, or reset while we were looking
        return None


def logo_image(max_w: int, max_h: int, school_id: Optional[str] = None) -> Optional[Image.Image]:
    """The logo in use fitted in max_w x max_h (RGBA), or None (= the caller draws the text placeholder)."""
    if not has("logo", school_id):
        return None
    try:
        with Image.open(resolve("logo", school_id)) as im:
            logo = im.convert("RGBA")
        scale = min(max_w / logo.width, max_h / logo.height)
        return logo.resize((max(1, int(logo.width * scale)), max(1, int(logo.height * scale))), Image.LANCZOS)
    except Exception as exc:
        logger.warning("Logo unreadable: %s", exc)
        return None
