"""Explicit pixel-grid orientation; XYZ values retain their original sensor axes."""
from __future__ import annotations
from copy import deepcopy
import numpy as np


def rotation_degrees(policy):
    value = (policy or {}).get('pixel_rotation_degrees', 0)
    if isinstance(value, bool) or value not in (0, 180):
        raise ValueError('Supported registered pixel rotations are 0 or 180 degrees')
    return int(value)


def orient_grid(array, policy):
    """Reorder pixels only, preserving each pixel's channel values and dtype."""
    degrees = rotation_degrees(policy)
    return np.ascontiguousarray(np.rot90(array, 2, axes=(0, 1))) if degrees else array


def rotate_rectangle(points, width, height):
    """Continuous image-edge coordinates differ from pixel-center indices."""
    coords = np.asarray(points, dtype=float)
    if coords.shape != (2, 2) or not np.isfinite(coords).all():
        raise ValueError('Rotation requires a finite two-corner rectangle')
    low, high = coords.min(axis=0), coords.max(axis=0)
    if not (0 <= low[0] < high[0] <= width and 0 <= low[1] < high[1] <= height):
        raise ValueError('Rectangle outside native image bounds')
    return [[width-high[0], height-high[1]], [width-low[0], height-low[1]]]


def rotate_document(document):
    result = deepcopy(document)
    for shape in result.get('shapes', []):
        if shape.get('shape_type') != 'rectangle':
            raise ValueError('Only rectangular pallet and ignore regions can be transformed')
        shape['points'] = rotate_rectangle(shape['points'], result['imageWidth'], result['imageHeight'])
    if result.get('imageData') is not None:
        raise ValueError('Embedded imageData must be regenerated when rotating an image')
    return result
