"""Create an input PNG, a rectangular mask, and the first retouched PNG."""

import argparse
from pathlib import Path

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

from make_input import HEIGHT, WIDTH, sample_rgb

DEFAULT_ROI = (150, 90, 132, 104)


def rectangular_mask(roi: tuple[int, int, int, int]) -> np.ndarray:
    x, y, width, height = roi
    mask = np.zeros((HEIGHT, WIDTH), dtype=np.uint8)
    # OpenCV includes both corners, so the far corner is one pixel inside.
    cv.rectangle(mask, (x, y), (x + width - 1, y + height - 1), 255, cv.FILLED)
    return mask


def blend_brightness(
    rgb: np.ndarray, mask: np.ndarray, lift: int, strength: float
) -> np.ndarray:
    source = rgb.astype(np.float32) / 255
    candidate = np.clip(source + lift / 255, 0, 1)
    coverage = mask.astype(np.float32) / 255
    weight = (coverage * strength)[..., None]
    blended = source + (candidate - source) * weight
    return np.rint(blended * 255).astype(np.uint8)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out", type=Path, default=Path("out"))
    parser.add_argument("--roi", type=int, nargs=4, default=DEFAULT_ROI,
                        metavar=("X", "Y", "WIDTH", "HEIGHT"))
    parser.add_argument("--lift", type=int, default=40,
                        help="add this many 8-bit levels at full strength (0–255)")
    parser.add_argument("--strength", type=float, default=1.0,
                        help="scale the correction from 0 to 1")
    args = parser.parse_args()

    x, y, width, height = args.roi
    if (x < 0 or y < 0 or width <= 0 or height <= 0
            or x + width > WIDTH or y + height > HEIGHT):
        parser.error(f"--roi must fit inside the {WIDTH} x {HEIGHT} input")
    if not 0 <= args.lift <= 255:
        parser.error("--lift must be between 0 and 255")
    if not 0 <= args.strength <= 1:
        parser.error("--strength must be between 0 and 1")

    args.out.mkdir(parents=True, exist_ok=True)
    input_path = args.out / "input.png"
    Image.fromarray(sample_rgb()).save(input_path)
    with Image.open(input_path) as image:
        rgb = np.array(image.convert("RGB"), dtype=np.uint8)

    mask = rectangular_mask(tuple(args.roi))
    result = blend_brightness(rgb, mask, args.lift, args.strength)
    Image.fromarray(mask).save(args.out / "mask.png")
    Image.fromarray(result).save(args.out / "output.png")
    print(f"Wrote input.png, mask.png, and output.png to {args.out}")


if __name__ == "__main__":
    main()
