"""Build a Sentrava lens profile from same-resolution checkerboard photographs."""

import argparse
import json
from pathlib import Path

import cv2
import numpy as np


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--cols", type=int, required=True, help="Horizontal inner corners")
    parser.add_argument("--rows", type=int, required=True, help="Vertical inner corners")
    parser.add_argument("--output", type=Path, default=Path("sentrava-camera.json"))
    parser.add_argument("images", nargs="+", type=Path)
    args = parser.parse_args()
    if not (3 <= args.cols <= 30 and 3 <= args.rows <= 30):
        parser.error("Use a pattern with 3–30 inner corners in each direction.")

    pattern = (args.cols, args.rows)
    grid = np.zeros((args.rows * args.cols, 3), dtype=np.float32)
    grid[:, :2] = np.mgrid[0:args.cols, 0:args.rows].T.reshape(-1, 2)
    object_points, image_points = [], []
    size = None
    for file in args.images:
        frame = cv2.imread(str(file), cv2.IMREAD_GRAYSCALE)
        if frame is None:
            print(f"Skipped unreadable image: {file}")
            continue
        dimensions = (frame.shape[1], frame.shape[0])
        if size and dimensions != size:
            print(f"Skipped different image size: {file}")
            continue
        found, corners = cv2.findChessboardCornersSB(frame, pattern)
        if not found:
            print(f"Skipped image without a complete checkerboard: {file}")
            continue
        size = dimensions
        object_points.append(grid)
        image_points.append(corners)

    if len(image_points) < 8:
        parser.error("At least eight usable images of the checkerboard are required.")
    error, matrix, distortion, _, _ = cv2.calibrateCamera(object_points, image_points, size, None, None)
    k1, k2, p1, p2, k3 = [float(value) for value in distortion.ravel()[:5]]
    profile = {
        "version": 1, "width": size[0], "height": size[1],
        "fx": float(matrix[0, 0]), "fy": float(matrix[1, 1]),
        "cx": float(matrix[0, 2]), "cy": float(matrix[1, 2]),
        "k1": k1, "k2": k2, "p1": p1, "p2": p2, "k3": k3,
    }
    try:
        with args.output.open("x", encoding="utf-8") as destination:
            destination.write(json.dumps(profile, indent=2, allow_nan=False) + "\n")
    except FileExistsError:
        parser.error("Choose a new output filename.")
    print(f"Saved {args.output}. Used {len(image_points)} images, RMS reprojection error {error:.3f} px.")


if __name__ == "__main__":
    main()
