#!/usr/bin/env python3
"""Synthetic monocular projection/transform checks; no ROS, camera or fitting.

Run: python3 camera_geometry_check.py [--self-test]
Files are read relative to this script. Standard library only, Python 3.9+.
This deliberately supports only zero-distortion, uncropped monocular images
with identity rectification and P=[K|0]. It is not a general CameraInfo parser.
"""
import argparse
import copy
import csv
import json
import math
from pathlib import Path
import unittest

HERE = Path(__file__).resolve().parent
IDENTITY = [1, 0, 0, 0, 1, 0, 0, 0, 1]


def vector(values, size):
    if len(values) != size:
        raise ValueError(f"Expected {size} values")
    result = [float(value) for value in values]
    if not all(math.isfinite(value) for value in result):
        raise ValueError("All values must be finite")
    return result


def validate_fixture(fixture):
    """Reject configurations this deliberately limited example cannot handle."""
    camera, transform = fixture['camera_info'], fixture['transform']
    k = vector(camera['k'], 9)
    if k[0] <= 0 or k[4] <= 0 or [k[i] for i in [1, 3, 6, 7, 8]] != [0, 0, 0, 0, 1]:
        raise ValueError("Expected calibrated zero-skew pinhole intrinsics")
    for key in ['width', 'height']:
        if type(camera[key]) is not int or camera[key] <= 0:
            raise ValueError("Image dimensions must be positive integers")
    if camera['distortion_model'] != 'plumb_bob' or vector(camera['d'], 5) != [0] * 5:
        raise ValueError("This fixture requires zero plumb_bob distortion")
    if vector(camera['r'], 9) != IDENTITY:
        raise ValueError("Only identity rectification is supported")
    expected_p = [k[0], 0, k[2], 0, 0, k[4], k[5], 0, 0, 0, 1, 0]
    if vector(camera['p'], 12) != expected_p:
        raise ValueError("This fixture requires monocular P=[K|0]")
    if transform['source_frame'] != camera['header']['frame_id']:
        raise ValueError("Transform source must match the optical frame")
    if transform['target_frame'] != 'base_link':
        raise ValueError("Expected base_link as the target frame")
    rotation = transform['rotation_base_from_optical']
    if len(rotation) != 3:
        raise ValueError("Expected a 3x3 rotation")
    rotation = [vector(row, 3) for row in rotation]
    for i in range(3):
        for j in range(3):
            dot = sum(rotation[i][n] * rotation[j][n] for n in range(3))
            if not math.isclose(dot, float(i == j), abs_tol=1e-12):
                raise ValueError("Rotation rows must be orthonormal")
    a, b, c = rotation
    determinant = (a[0] * (b[1]*c[2] - b[2]*c[1])
                   - a[1] * (b[0]*c[2] - b[2]*c[0])
                   + a[2] * (b[0]*c[1] - b[1]*c[0]))
    if not math.isclose(determinant, 1.0, abs_tol=1e-12):
        raise ValueError("Rotation must be right-handed, determinant +1")
    vector(transform['translation_base_m'], 3)


def project(point, camera):
    x, y, z = vector(point, 3)
    if z <= 0:
        raise ValueError("Projection requires a point in front of the camera")
    k = camera['k']
    return [k[0] * x / z + k[2], k[4] * y / z + k[5]]


def back_project(pixel, depth_z_m, camera):
    """Depth is distance along optical Z, not Euclidean range."""
    u, v = vector(pixel, 2)
    z = vector([depth_z_m], 1)[0]
    if z <= 0:
        raise ValueError("Positive optical-Z depth is required")
    k = camera['k']
    return [(u - k[2]) * z / k[0], (v - k[5]) * z / k[4], z]


def to_base(point, transform):
    point = vector(point, 3)
    rotation = transform['rotation_base_from_optical']
    offset = transform['translation_base_m']
    return [sum(rotation[i][j] * point[j] for j in range(3)) + offset[i]
            for i in range(3)]


def to_optical(point, transform):
    point = vector(point, 3)
    rotation = transform['rotation_base_from_optical']
    delta = [point[i] - transform['translation_base_m'][i] for i in range(3)]
    return [sum(rotation[j][i] * delta[j] for j in range(3)) for i in range(3)]


def load_inputs():
    fixture = json.loads((HERE / 'camera_fixture.json').read_text())
    with (HERE / 'correspondences.csv').open(newline='') as stream:
        rows = list(csv.DictReader(stream))
    return fixture, rows


def row_vector(row, names):
    return vector([row[name] for name in names], len(names))


def evaluate(fixture, rows):
    validate_fixture(fixture)
    if not rows:
        raise ValueError("At least one correspondence is required")
    camera, transform = fixture['camera_info'], fixture['transform']
    records, squared_residuals, base_errors = [], [], []
    seen = set()
    for row in rows:
        if not row['id'] or row['id'] in seen:
            raise ValueError("Correspondence IDs must be unique and nonempty")
        seen.add(row['id'])
        point = row_vector(row, ['x_optical_m', 'y_optical_m', 'z_optical_m'])
        expected_pixel = row_vector(row, ['u_expected_px', 'v_expected_px'])
        expected_base = row_vector(row, ['x_base_expected_m', 'y_base_expected_m', 'z_base_expected_m'])
        pixel, base = project(point, camera), to_base(point, transform)
        if not (0 <= pixel[0] < camera['width'] and 0 <= pixel[1] < camera['height']):
            raise ValueError("This fixture expects every point inside the image")
        squared_residuals.append(sum((a-b)**2 for a, b in zip(pixel, expected_pixel)))
        base_errors.append(math.dist(base, expected_base))
        records.append({'id': row['id'], 'pixel_px': pixel, 'base_point_m': base})
    return {
        'scope': 'synthetic known-parameter validation; no calibration fitting or hardware test',
        'point_count': len(rows),
        'reprojection_rms_px': math.sqrt(sum(squared_residuals) / len(rows)),
        'maximum_base_error_m': max(base_errors),
        'points': records,
    }


def assert_expected(report):
    if report['reprojection_rms_px'] > 1e-9 or report['maximum_base_error_m'] > 1e-9:
        raise ValueError("Known synthetic correspondences do not match (tolerance 1e-9)")


class GeometryTests(unittest.TestCase):
    def setUp(self):
        self.fixture, self.rows = load_inputs()

    def test_six_known_correspondences(self):
        self.assertEqual(len(self.rows), 6)
        assert_expected(evaluate(self.fixture, self.rows))

    def test_axis_mapping_independently(self):
        transform = self.fixture['transform']
        expected = [[0.2, -1, 0.5], [0.2, 0, -0.5], [1.2, 0, 0.5]]
        for point, base in zip([[1, 0, 0], [0, 1, 0], [0, 0, 1]], expected):
            self.assertEqual(to_base(point, transform), base)

    def test_inverse_transform(self):
        point = [0.23, -0.17, 1.9]
        back = to_optical(to_base(point, self.fixture['transform']), self.fixture['transform'])
        self.assertLess(math.dist(point, back), 1e-12)

    def test_known_depth_back_projection(self):
        camera = self.fixture['camera_info']
        self.assertEqual(back_project([370, 265], 2, camera), [0.2, 0.1, 2])
        self.assertEqual(back_project([370, 265], 4, camera), [0.4, 0.2, 4])

    def test_five_pixel_intrinsic_error(self):
        camera = self.fixture['camera_info']
        camera['k'][2] += 5
        camera['p'][2] += 5
        report = evaluate(self.fixture, self.rows)
        self.assertAlmostEqual(report['reprojection_rms_px'], 5.0)
        with self.assertRaises(ValueError):
            assert_expected(report)

    def test_wrong_transform_detected(self):
        self.fixture['transform']['rotation_base_from_optical'] = [[1,0,0],[0,1,0],[0,0,1]]
        with self.assertRaises(ValueError):
            assert_expected(evaluate(self.fixture, self.rows))

    def test_unsupported_camera_models_rejected(self):
        for key, value in [('d', [0.1, 0, 0, 0, 0]), ('k', [0]*9),
                           ('p', [0]*12), ('width', 0), ('r', [0]*9)]:
            changed = copy.deepcopy(self.fixture)
            changed['camera_info'][key] = value
            with self.subTest(key=key), self.assertRaises(ValueError):
                validate_fixture(changed)

    def test_invalid_depth_and_nonfinite_rejected(self):
        for point in [[0,0,0], [0,0,-1], [float('nan'),0,1]]:
            with self.subTest(point=point), self.assertRaises(ValueError):
                project(point, self.fixture['camera_info'])
        with self.assertRaises(ValueError):
            back_project([320, 240], 0, self.fixture['camera_info'])

    def test_reflection_and_frame_mismatch_rejected(self):
        self.fixture['transform']['rotation_base_from_optical'] = [[-1,0,0],[0,1,0],[0,0,1]]
        with self.assertRaises(ValueError):
            validate_fixture(self.fixture)
        self.fixture, _ = load_inputs()
        self.fixture['transform']['source_frame'] = 'wrong_frame'
        with self.assertRaises(ValueError):
            validate_fixture(self.fixture)

    def test_empty_duplicate_and_nonfinite_data_rejected(self):
        for rows in [[], self.rows + [self.rows[0]]]:
            with self.assertRaises(ValueError):
                evaluate(self.fixture, rows)
        self.rows[0]['u_expected_px'] = 'nan'
        with self.assertRaises(ValueError):
            evaluate(self.fixture, self.rows)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--self-test', action='store_true')
    args = parser.parse_args()
    if args.self_test:
        suite = unittest.defaultTestLoader.loadTestsFromTestCase(GeometryTests)
        result = unittest.TextTestRunner(verbosity=2).run(suite)
        return 0 if result.wasSuccessful() else 1
    fixture, rows = load_inputs()
    report = evaluate(fixture, rows)
    assert_expected(report)
    biased = copy.deepcopy(fixture)
    biased['camera_info']['k'][2] += 5
    biased['camera_info']['p'][2] += 5
    report['deliberate_cx_plus_5_px_rms'] = evaluate(biased, rows)['reprojection_rms_px']
    print(json.dumps(report, indent=2, allow_nan=False))
    return 0


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