#!/usr/bin/env python3
"""whatsapp_proof_crop.py - turn raw WhatsApp screenshots into clean social-proof images.

What it does, in this order:
  1. Crops each raw screenshot to the rows you give it (--rows) and the columns
     you give it (--cols).
  2. Stitches the crops top to bottom, so a message that took two screens ends
     up as one image.
  3. Removes the yellow highlight that WhatsApp's search leaves on the matched
     word. It recolors the highlighted pixels by brightness, so the text stays
     sharp and no outline is left behind.
  4. Blurs rectangles you list (--blur), for phone numbers and names.
  5. Optionally leaves a strip alone (--keep-bottom, --protect), for example the
     message time, which should stay exactly as captured.

It is made for the dark theme of WhatsApp, and for screenshots taken at the same
size, such as the iPhone Mirroring window. Coordinates are pixels of the
screenshot, the way an image viewer shows them (origin at the top left).

Usage:
  python whatsapp_proof_crop.py raw.png --rows 100:400 --out proof.png

  # one message that spans two screens: one --rows per image, same order
  python whatsapp_proof_crop.py top.png bottom.png --rows 200:600 --rows 100:500 \\
      --blur 20,10,200,40 --keep-bottom 50 --out proof.png

All numbers above are placeholders. Replace them with the pixel positions in
your own screenshots.

Requirements: Python 3.9+, Pillow, numpy (pip install -r requirements.txt)

Only the files you pass in are read. Nothing is uploaded and nothing is stored.
Always look at the result before you publish it.
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path
from typing import List, Tuple

import numpy as np
from PIL import Image, ImageFilter

# The dark-mode search highlight, as it looks in a screenshot (RGB).
DEFAULT_HIGHLIGHT = (151, 110, 56)
# Pure white is the brightest value a character can reach after recoloring.
WHITE = np.array([255.0, 255.0, 255.0])
# Brightness of the highlight color's text, and of the brightest text on it.
TEXT_LUMA_ON_HIGHLIGHT = 253.0

Rect = Tuple[int, int, int, int]


def parse_ints(text: str, count: int, label: str) -> List[int]:
    """Parse 'a,b,c' into exactly `count` integers, or exit with a clear message."""
    try:
        values = [int(part) for part in text.replace(":", ",").split(",")]
    except ValueError:
        sys.exit(f"{label}: expected {count} whole numbers, got {text!r}")
    if len(values) != count:
        sys.exit(f"{label}: expected {count} numbers, got {len(values)} in {text!r}")
    return values


def parse_range(text: str, label: str) -> Tuple[int, int]:
    a, b = parse_ints(text, 2, label)
    if a < 0 or b <= a:
        sys.exit(f"{label}: need 0 <= start < end, got {text!r}")
    return a, b


def parse_rect(text: str, label: str) -> Rect:
    x0, y0, x1, y1 = parse_ints(text, 4, label)
    if x1 <= x0 or y1 <= y0:
        sys.exit(f"{label}: need x0 < x1 and y0 < y1, got {text!r}")
    return x0, y0, x1, y1


def load_rgb(path: Path) -> np.ndarray:
    if not path.is_file():
        sys.exit(f"input not found: {path}")
    return np.asarray(Image.open(path).convert("RGB")).astype(float)


def find_background(img: np.ndarray, highlight_mask: np.ndarray) -> np.ndarray:
    """The most common dark gray outside the highlight is the chat background."""
    luma = img.mean(2)
    candidate = (luma > 45) & (luma < 75) & (np.ptp(img, 2) < 10) & ~highlight_mask
    if not candidate.any():
        sys.exit(
            "could not find the chat background color. Pass it with "
            "--background R,G,B (use a color picker on an empty part of the chat)."
        )
    values, counts = np.unique(img[candidate].astype(int), axis=0, return_counts=True)
    return values[counts.argmax()].astype(float)


def remove_highlight(
    img: np.ndarray,
    highlight: Tuple[int, int, int],
    tolerance: float,
    background: Tuple[int, int, int] | None,
) -> np.ndarray:
    """Recolor the search highlight to the chat background, keeping the text.

    A plain "replace this color" leaves a ring around every letter, because the
    edge pixels are a mix of highlight and text. So we grow the highlight area a
    little, then map each pixel's brightness onto the range between the
    background and white. Dark pixels become background, bright pixels become
    white text, and the in-between edge pixels land in between.
    """
    h = np.array(highlight, dtype=float)
    near = (np.linalg.norm(img.reshape(-1, 3) - h, axis=1) < tolerance).reshape(img.shape[:2])
    if near.sum() < 50:  # no highlight in this image
        return img
    grown = np.asarray(
        Image.fromarray((near * 255).astype(np.uint8)).filter(ImageFilter.MaxFilter(11))
    ) > 0
    luma = img.mean(2)
    bg = np.array(background, dtype=float) if background else find_background(img, grown)
    saturation = np.ptp(img, 2)
    recolor = grown & ((saturation > 6) | (luma < 90))
    t = np.clip((luma - h.mean()) / (TEXT_LUMA_ON_HIGHLIGHT - h.mean()), 0, 1)
    out = img.copy()
    out[recolor] = bg + t[recolor][:, None] * (WHITE - bg)
    return out


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        description="Crop, stitch, un-highlight and blur raw WhatsApp screenshots.",
        epilog="Example: python whatsapp_proof_crop.py raw.png --rows 650:842 --out proof.png",
    )
    p.add_argument("images", nargs="+", type=Path, help="raw screenshots, top part first")
    p.add_argument(
        "--rows", action="append", required=True, metavar="Y0:Y1",
        help="rows to keep from each image, one --rows per image, in the same order",
    )
    p.add_argument("--cols", default="30:620", metavar="X0:X1",
                   help="columns to keep, same for every image (default 30:620)")
    p.add_argument("--blur", action="append", default=[], metavar="X0,Y0,X1,Y1",
                   help="rectangle to blur, in the cropped image (repeatable)")
    p.add_argument("--protect", action="append", default=[], metavar="X0,Y0,X1,Y1",
                   help="rectangle to restore to the original pixels after highlight removal (repeatable)")
    p.add_argument("--keep-bottom", type=int, default=0, metavar="N",
                   help="leave the bottom N rows untouched by highlight removal, e.g. the time")
    p.add_argument("--blur-radius", type=float, default=9, help="blur strength (default 9)")
    p.add_argument("--highlight", default=",".join(map(str, DEFAULT_HIGHLIGHT)), metavar="R,G,B",
                   help="color of the search highlight (default %s)" % ",".join(map(str, DEFAULT_HIGHLIGHT)))
    p.add_argument("--tolerance", type=float, default=30, help="how far from --highlight still counts (default 30)")
    p.add_argument("--background", default=None, metavar="R,G,B",
                   help="chat background color; found automatically when omitted")
    p.add_argument("--no-unhighlight", action="store_true", help="skip highlight removal")
    p.add_argument("--out", type=Path, required=True, help="output PNG path")
    return p


def main(argv: List[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    if len(args.rows) != len(args.images):
        sys.exit(f"{len(args.images)} image(s) but {len(args.rows)} --rows: give one --rows per image")

    x0, x1 = parse_range(args.cols, "--cols")
    highlight = tuple(parse_ints(args.highlight, 3, "--highlight"))
    background = tuple(parse_ints(args.background, 3, "--background")) if args.background else None
    blur_rects = [parse_rect(r, "--blur") for r in args.blur]
    protect_rects = [parse_rect(r, "--protect") for r in args.protect]

    parts = []
    for path, rows in zip(args.images, args.rows):
        y0, y1 = parse_range(rows, "--rows")
        img = load_rgb(path)
        if y1 > img.shape[0] or x1 > img.shape[1]:
            sys.exit(f"{path.name} is {img.shape[1]}x{img.shape[0]}, smaller than the crop {x0}:{x1} x {y0}:{y1}")
        parts.append(img[y0:y1, x0:x1])
    stitched = np.vstack(parts)
    original = stitched.copy()

    if not args.no_unhighlight:
        limit = stitched.shape[0] - max(args.keep_bottom, 0)
        stitched[:limit] = remove_highlight(stitched[:limit], highlight, args.tolerance, background)
    for rx0, ry0, rx1, ry1 in protect_rects:
        stitched[ry0:ry1, rx0:rx1] = original[ry0:ry1, rx0:rx1]

    result = Image.fromarray(stitched.clip(0, 255).astype(np.uint8))
    for rect in blur_rects:
        region = result.crop(rect).filter(ImageFilter.GaussianBlur(args.blur_radius))
        result.paste(region, rect)

    args.out.parent.mkdir(parents=True, exist_ok=True)
    result.save(args.out)
    print(f"{args.out} {result.size[0]}x{result.size[1]}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
