#!/usr/bin/env python3
"""Pure-Python 1990s 35mm cel-and-gouache still (`2048 x 1152`) for inbox-birthday:
Fourteen years of correspondence tied with terracotta twine inside a sunlit
archival drawer beside a thermal receipt bundle, brass nib pen, and 2010–2026
timeline card. Zero image models, zero external textures, zero fonts.
"""

from __future__ import annotations

import argparse
import math
from pathlib import Path
from typing import Sequence

import cairo
import cv2
import numpy as np
from PIL import Image


def hex_rgb(code: str) -> np.ndarray:
    code = code.lstrip("#")
    return np.array([int(code[0:2], 16), int(code[2:4], 16), int(code[4:6], 16)], dtype=np.float32) / 255.0


def alpha_composite(dst: np.ndarray, src: np.ndarray, alpha: np.ndarray) -> np.ndarray:
    a = np.clip(alpha, 0.0, 1.0)[..., None]
    return dst * (1.0 - a) + src * a


def screen_blend(dst: np.ndarray, add: np.ndarray) -> np.ndarray:
    return 1.0 - (1.0 - dst) * (1.0 - np.clip(add, 0.0, 1.0))


def fbm_gouache(h: int, w: int, octaves: Sequence[tuple[float, float, float]] = ((70.0, 68.0, 0.45), (26.0, 28.0, 0.32), (10.0, 9.5, 0.16), (4.5, 4.5, 0.07)), seed: int = 101) -> np.ndarray:
    rng = np.random.default_rng(seed)
    acc = np.zeros((h, w), dtype=np.float32)
    wsum = 0.0
    for sx, sy, wt in octaves:
        gh, gw = max(4, int(round(h / sy))), max(4, int(round(w / sx)))
        acc += float(wt) * cv2.resize(rng.standard_normal((gh, gw)).astype(np.float32), (w, h), interpolation=cv2.INTER_CUBIC)
        wsum += float(wt)
    acc /= max(wsum, 1e-6)
    std = float(np.std(acc))
    return ((acc - float(np.mean(acc))) / std if std > 1e-6 else acc).astype(np.float32)


def paint_dabs(rgb: np.ndarray, mask: np.ndarray, tooth: np.ndarray, strength: float = 0.04, seed: int = 19) -> np.ndarray:
    h, w, _ = rgb.shape
    m = np.clip(mask.astype(np.float32), 0.0, 1.0)
    if float(m.max()) < 1e-4:
        return rgb.copy()
    mot = fbm_gouache(h, w, seed=seed)
    sh, sw = max(64, h // 4), max(64, w // 4)
    rng = np.random.default_rng(seed + 41)
    dv = np.zeros((sh, sw), np.float32)
    for _ in range(72):
        ang = float(rng.uniform(0, math.pi))
        hx, hy = float(rng.uniform(14, 42)), float(rng.uniform(5, 14))
        cx, cy = float(rng.uniform(0, sw)), float(rng.uniform(0, sh))
        ca, sa = math.cos(ang), math.sin(ang)
        corners = np.array([
            [cx - hx * ca + hy * sa, cy - hx * sa - hy * ca],
            [cx + hx * ca + hy * sa, cy + hx * sa - hy * ca],
            [cx + hx * ca - hy * sa, cy + hx * sa + hy * ca],
            [cx - hx * ca - hy * sa, cy - hx * sa + hy * ca],
        ], np.float32)
        x0, y0 = max(0, int(corners[:, 0].min()) - 8), max(0, int(corners[:, 1].min()) - 8)
        x1, y1 = min(sw, int(corners[:, 0].max()) + 8), min(sh, int(corners[:, 1].max()) + 8)
        if x1 <= x0 or y1 <= y0:
            continue
        dab = np.zeros((y1 - y0, x1 - x0), np.float32)
        cv2.fillConvexPoly(dab, np.round(corners - [[x0, y0]]).astype(np.int32), 1.0, cv2.LINE_AA)
        a = cv2.GaussianBlur(dab, (0, 0), 2.1) * float(rng.uniform(0.18, 0.34))
        dv[y0:y1, x0:x1] = dv[y0:y1, x0:x1] * (1 - a) + float(rng.normal(0, 0.44)) * a
    up = cv2.resize(dv, (w, h), interpolation=cv2.INTER_LINEAR)
    out = rgb.copy()
    delta = strength * (0.55 * mot + 0.45 * up) + 0.014 * tooth
    out[:, :, 0] += m * (delta + 0.35 * strength * mot)
    out[:, :, 1] += m * delta
    out[:, :, 2] += m * (delta - 0.35 * strength * mot)
    return np.clip(out, 0.0, 1.0)


class Camera3D:
    def __init__(self, eye, target, up, fov_deg: float, width: int = 2048, height: int = 1152) -> None:
        self.eye, self.target, self.up = np.asarray(eye, np.float64), np.asarray(target, np.float64), np.asarray(up, np.float64)
        self.width, self.height = width, height
        fwd = self.target - self.eye; fwd /= np.linalg.norm(fwd)
        right = np.cross(fwd, self.up); right /= np.linalg.norm(right)
        down = np.cross(fwd, right); down /= np.linalg.norm(down)
        self.R = np.vstack([right, down, fwd])
        self.f = (width * 0.5) / math.tan(math.radians(fov_deg) * 0.5)
        self.cx, self.cy = width * 0.5, height * 0.5
        self.K = np.array([[self.f, 0.0, self.cx], [0.0, self.f, self.cy], [0.0, 0.0, 1.0]], np.float64)
        yy, xx = np.mgrid[0:height, 0:width].astype(np.float32)
        dxc, dyc = (xx - self.cx) / self.f, (yy - self.cy) / self.f
        rt = self.R.T.astype(np.float32)
        self.rx = rt[0, 0] * dxc + rt[0, 1] * dyc + rt[0, 2]
        self.ry = rt[1, 0] * dxc + rt[1, 1] * dyc + rt[1, 2]
        self.rz = rt[2, 0] * dxc + rt[2, 1] * dyc + rt[2, 2]

    def project(self, pts: np.ndarray) -> np.ndarray:
        arr = np.asarray(pts, np.float64)
        pc = (arr - self.eye[None]) @ self.R.T
        sz = np.where(np.abs(pc[:, 2]) < 1e-6, 1e-6, pc[:, 2])
        return np.column_stack([self.f * (pc[:, 0] / sz) + self.cx, self.f * (pc[:, 1] / sz) + self.cy])

    def warp_plane(self, panel_rgb, p0, e1, e2, span_u, span_v, fog_col):
        uv_h, uv_w, _ = panel_rgb.shape
        e1u, e2u = np.asarray(e1, np.float64), np.asarray(e2, np.float64)
        e1u /= np.linalg.norm(e1u); e2u /= np.linalg.norm(e2u)
        H = self.K @ np.column_stack([self.R @ e1u, self.R @ e2u, self.R @ (p0 - self.eye)]) @ np.array([[span_u / uv_w, 0, 0], [0, span_v / uv_h, 0], [0, 0, 1]])
        pre = np.dstack([panel_rgb.astype(np.float32), np.ones((uv_h, uv_w), np.float32)])
        warped = cv2.warpPerspective(pre, H, (self.width, self.height), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
        n = np.cross(e1u, e2u); n /= np.linalg.norm(n)
        den = self.rx * float(n[0]) + self.ry * float(n[1]) + self.rz * float(n[2])
        zc = (float(np.dot(p0 - self.eye, n)) / np.where(np.abs(den) < 1e-6, 1e-6, den)).astype(np.float32)
        hx, hy, hz = float(self.eye[0]) + zc * self.rx, float(self.eye[1]) + zc * self.ry, float(self.eye[2]) + zc * self.rz
        um = (hx - p0[0]) * e1u[0] + (hy - p0[1]) * e1u[1] + (hz - p0[2]) * e1u[2]
        vm = (hx - p0[0]) * e2u[0] + (hy - p0[1]) * e2u[1] + (hz - p0[2]) * e2u[2]
        a = np.clip(warped[:, :, 3] * ((zc > 0.05) & (um >= -0.004) & (um <= span_u + 0.004) & (vm >= -0.004) & (vm <= span_v + 0.004)), 0.0, 1.0)
        rgb = np.clip(warped[:, :, :3] / np.maximum(a, 1e-5)[:, :, None], 0.0, 1.0)
        ft = np.clip(1.0 - np.exp(-np.maximum(0.0, zc - 2.0) * 0.05), 0.0, 0.35)[:, :, None]
        return rgb * (1 - ft) + fog_col[None, None] * ft, a


class Cairo2x:
    def __init__(self, w: int = 2048, h: int = 1152) -> None:
        self.w, self.h = w, h
        self.surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, w * 2, h * 2)
        self.ctx = cairo.Context(self.surf)
        self.ctx.scale(2.0, 2.0)
        self.ctx.set_antialias(cairo.ANTIALIAS_BEST)
        self.ctx.set_line_cap(cairo.LINE_CAP_ROUND)
        self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)

    def poly(self, pts, rgba, stroke_rgba=None, lw=2.0):
        self.ctx.new_path()
        self.ctx.move_to(float(pts[0, 0]), float(pts[0, 1]))
        for x, y in pts[1:]:
            self.ctx.line_to(float(x), float(y))
        self.ctx.close_path()
        self.ctx.set_source_rgba(*rgba)
        self.ctx.fill_preserve()
        if stroke_rgba:
            self.ctx.set_source_rgba(*stroke_rgba)
            self.ctx.set_line_width(lw)
            self.ctx.stroke()
        else:
            self.ctx.new_path()

    def line(self, pts, rgba, lw=2.0):
        self.ctx.new_path()
        self.ctx.move_to(float(pts[0, 0]), float(pts[0, 1]))
        for x, y in pts[1:]:
            self.ctx.line_to(float(x), float(y))
        self.ctx.set_source_rgba(*rgba)
        self.ctx.set_line_width(lw)
        self.ctx.stroke()

    def finish(self):
        buf = np.frombuffer(self.surf.get_data(), np.uint8).reshape(self.h * 2, self.w * 2, 4)
        pil = Image.fromarray(buf[:, :, [2, 1, 0, 3]], mode="RGBA").resize((self.w, self.h), Image.Resampling.LANCZOS)
        arr = np.asarray(pil, np.float32) / 255.0
        a = np.clip(arr[:, :, 3], 0.0, 1.0)
        return np.clip(arr[:, :, :3] / np.maximum(a, 1e-5)[:, :, None], 0.0, 1.0), a


def render(w: int = 2048, h: int = 1152, crops_dir: Path | None = None) -> np.ndarray:
    cam = Camera3D([-0.34, -0.52, 0.70], [0.14, 1.24, 0.14], [0.0, 0.0, 1.0], 46.0, w, h)
    tooth = fbm_gouache(h, w, octaves=((4.0, 4.0, 0.6), (2.0, 2.0, 0.4)), seed=13)

    # 1. Warm plaster attic backdrop + sunlit window wash
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    wall = np.broadcast_to(hex_rgb("#E8E1D3"), (h, w, 3)).copy()
    sun_spot = np.exp(-((xx / w - 0.58) ** 2 / 0.14 + (yy / h - 0.25) ** 2 / 0.18))
    wall = np.clip(wall + sun_spot[:, :, None] * np.array([0.10, 0.08, 0.04], np.float32), 0.0, 1.0)
    canvas = paint_dabs(wall, np.ones((h, w), np.float32), tooth, 0.036, 7)

    # 2. Cedar archival desk + warm sunbeams
    tw, th = 1024, 768
    tbl = np.broadcast_to(hex_rgb("#966343"), (th, tw, 3)).copy()
    tbl = np.clip(tbl + 0.045 * fbm_gouache(th, tw, ((12, 140, 0.65), (5, 44, 0.35)), 41)[:, :, None], 0.0, 1.0)
    tbl_rgb, tbl_a = cam.warp_plane(tbl, np.array([-1.05, 0.10, 0.0]), [1, 0, 0], [0, 1, 0], 2.5, 1.75, hex_rgb("#DFC4A4"))
    canvas = alpha_composite(canvas, paint_dabs(tbl_rgb, tbl_a, tooth, 0.03, 29), tbl_a)

    # 3. 3D Wooden archive tray holding stacked envelopes (background-center-right) & receipt stack
    c = Cairo2x(w, h)
    ink = (0.08, 0.08, 0.07, 0.90)

    def box3d(x0, x1, y0, y1, z0, z1, top_c, front_c, side_c):
        # Soft cast shadow onto z=0.002
        sh = cam.project([[x0 - 0.03, y0 + 0.02, 0.002], [x1 - 0.03, y0 + 0.02, 0.002], [x1 + 0.04, y1 + 0.05, 0.002], [x0 - 0.04, y1 + 0.05, 0.002]])
        c.poly(sh, (0.14, 0.09, 0.06, 0.26))
        # Left visible side (camera at -X)
        c.poly(cam.project([[x0, y0, z0], [x0, y1, z0], [x0, y1, z1], [x0, y0, z1]]), side_c, ink, 1.8)
        # Front face (y0)
        c.poly(cam.project([[x0, y0, z0], [x1, y0, z0], [x1, y0, z1], [x0, y0, z1]]), front_c, ink, 1.8)
        # Top face (z1)
        c.poly(cam.project([[x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]]), top_c, ink, 2.0)

    # Open archival wooden box (center-right) + inner packed letters (89% slate/receipts vs 11% cream/clay personal)
    box3d(0.05, 0.62, 0.76, 1.24, 0.0, 0.14, (0.44, 0.30, 0.21, 1.0), (0.34, 0.22, 0.16, 1.0), (0.26, 0.17, 0.12, 1.0))
    # Layered letter bundles rising slightly above rim (back 2010 -> front 2026)
    for k in range(14):
        yy_off = 0.80 + k * 0.028
        col = (0.73, 0.39, 0.28, 1.0) if k in (1, 8, 12) else ((0.96, 0.94, 0.89, 1.0) if k % 3 == 0 else (0.78, 0.80, 0.81, 1.0))
        tilt = 0.015 * math.sin(k * 0.9)
        pts = cam.project([[0.09 + tilt, yy_off, 0.135], [0.58 + tilt, yy_off, 0.135], [0.58 + tilt, yy_off + 0.014, 0.21 + (k % 2) * 0.015], [0.09 + tilt, yy_off + 0.014, 0.21 + (k % 2) * 0.015]])
        c.poly(pts, col, ink, 1.3)

    # Foreground left stack of machine receipts/ledgers tied with terracotta ribbon
    box3d(-0.46, -0.08, 0.62, 0.94, 0.0, 0.078, (0.97, 0.96, 0.93, 1.0), (0.86, 0.84, 0.78, 1.0), (0.78, 0.76, 0.70, 1.0))
    # Terracotta twine cross-tie over ledger stack
    c.line(cam.project([[-0.27, 0.62, 0.0], [-0.27, 0.62, 0.082], [-0.27, 0.94, 0.082]]), (0.73, 0.39, 0.28, 1.0), 4.5)
    c.line(cam.project([[-0.46, 0.78, 0.082], [-0.08, 0.78, 0.082]]), (0.73, 0.39, 0.28, 1.0), 4.5)

    # Stamped birthday card angled in front of tray ("Nov 6, 2012" red clay bar accent)
    card_pts = cam.project([[-0.02, 0.56, 0.005], [0.36, 0.52, 0.005], [0.40, 0.74, 0.005], [0.02, 0.78, 0.005]])
    c.poly(card_pts, (0.98, 0.97, 0.94, 1.0), ink, 2.0)
    # Volume bars painted onto card
    for bi, bh in enumerate((0.2, 0.28, 0.22, 0.55, 0.62, 0.82, 0.52, 0.90)):
        bx0 = 0.04 + bi * 0.036
        bar = cam.project([[bx0, 0.60, 0.007], [bx0 + 0.022, 0.598, 0.007], [bx0 + 0.024, 0.60 + bh * 0.11, 0.007], [bx0 + 0.002, 0.602 + bh * 0.11, 0.007]])
        c.poly(bar, (0.73, 0.39, 0.28, 0.92), None)
    # Fountain pen
    c.line(cam.project([[0.45, 0.58, 0.012], [0.58, 0.74, 0.012]]), (0.12, 0.12, 0.11, 1.0), 7.0)

    obj_rgb, obj_a = c.finish()
    canvas = alpha_composite(canvas, paint_dabs(obj_rgb, obj_a, tooth, 0.03, 91), obj_a)

    # 35mm finish
    lum = 0.2126 * canvas[:, :, 0] + 0.7152 * canvas[:, :, 1] + 0.0722 * canvas[:, :, 2]
    ht = (np.clip((lum - 0.72) / 0.28, 0, 1) ** 1.3)[:, :, None] * np.array([1.0, 0.90, 0.75], np.float32)[None, None]
    canvas = screen_blend(canvas, 0.16 * cv2.GaussianBlur(ht, (0, 0), 7.0) + 0.14 * cv2.GaussianBlur(ht, (0, 0), 26.0))
    rng = np.random.default_rng(303)
    final = np.clip(0.015 + canvas * 0.97 + rng.standard_normal((h, w)).astype(np.float32)[:, :, None] * 0.012, 0.0, 1.0)

    if crops_dir is not None:
        crops_dir.mkdir(parents=True, exist_ok=True)
        for nm, (cx, cy) in (("box.png", (w * 0.60, h * 0.48)), ("card.png", (w * 0.50, h * 0.76)), ("bundle.png", (w * 0.30, h * 0.68))):
            x0, y0 = int(np.clip(cx - 300, 0, w - 600)), int(np.clip(cy - 225, 0, h - 450))
            Image.fromarray(np.round(final[y0:y0 + 450, x0:x0 + 600] * 255).astype(np.uint8)).save(crops_dir / nm)
    return final


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--out", type=Path, required=True)
    p.add_argument("--crops-dir", type=Path, default=None)
    args = p.parse_args()
    rgb = render(crops_dir=args.crops_dir)
    args.out.parent.mkdir(parents=True, exist_ok=True)
    Image.fromarray(np.round(rgb * 255).astype(np.uint8), "RGB").save(args.out, format="WEBP", quality=90, method=6)
    print("Saved", args.out)


if __name__ == "__main__":
    main()
