"""Proposed RH metres -> interface centimetres adapter; no accepted placement.

The Y reflection is applied exactly once. Triangle winding is reversed because
its determinant is negative. R must be a proper orthonormal rotation, T is cm.
Actual importer convention and final R/T still require returned controls.
"""
import math

IDENTITY=[[1,0,0],[0,1,0],[0,0,1]]


def check_rotation(rotation):
    if len(rotation)!=3 or any(len(row)!=3 for row in rotation):raise ValueError('rotation must be3x3')
    if not all(math.isfinite(v) for row in rotation for v in row):raise ValueError('nonfinite rotation')
    for i in range(3):
        for j in range(3):
            if abs(sum(rotation[k][i]*rotation[k][j] for k in range(3))-(1 if i==j else 0))>1e-8:raise ValueError('scale/shear not allowed')
    a,b,c=rotation;det=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 abs(det-1)>1e-8:raise ValueError('R must have determinant+1; Y reflection is already in adapter')


def to_interface_cm(point,rotation=IDENTITY,translation_cm=(0,0,0)):
    check_rotation(rotation)
    if len(point)!=3 or len(translation_cm)!=3 or not all(math.isfinite(v) for v in list(point)+list(translation_cm)):raise ValueError('invalid point/translation')
    reflected=[100*point[0],-100*point[1],100*point[2]]
    return [sum(row[j]*reflected[j] for j in range(3))+translation_cm[i] for i,row in enumerate(rotation)]


def to_authoring_m(point_cm,rotation=IDENTITY,translation_cm=(0,0,0)):
    check_rotation(rotation)
    local=[point_cm[i]-translation_cm[i] for i in range(3)]
    reflected=[sum(rotation[j][i]*local[j] for j in range(3)) for i in range(3)]
    return [reflected[0]/100,-reflected[1]/100,reflected[2]/100]


def transform_mesh(vertices,triangles,rotation=IDENTITY,translation_cm=(0,0,0)):
    return ([to_interface_cm(p,rotation,translation_cm) for p in vertices],[[f[0],f[2],f[1]] for f in triangles])
