pub use uom::si::angle::{degree, radian};
pub use uom::si::f64::{Angle, Length};
use uom::si::length::meter;
pub use uom::si::length::millimeter;

pub mod camera;
pub mod cancel;
pub mod color;
pub mod content;
pub mod dimensioned_serde;
pub mod display;
pub mod history;
pub mod icon;
pub mod label;
pub mod reference;
pub mod schema;
pub mod solver;
pub mod space;
pub mod step;

pub use camera::{
    Camera3, CubicEasing, OrbitState, Projection, ProjectionKind, StandardView, ZoomFactor,
};
pub use cancel::{Cancel, CancelFlag};
pub use color::LinearRgba;
pub use content::SolidKey;
pub use display::{DisplayMode, ShadingModel};
pub use history::{
    BuildFailure, FeatureGeneration, RebuildError, RebuildStatus, RebuildWarning, RollbackMarker,
    SuppressionState,
};
pub use icon::{IconId, IconTile};
pub use label::{
    EdgeLabel, EdgeRole, FaceLabel, FaceRole, ImportOrdinal, LoopIndex, SideKind, VertexLabel,
    VertexRole,
};
pub use reference::{
    EdgeFingerprint, EntityFingerprint, EntityRef, FaceFingerprint, FaceRef, MatchScore,
    Resolution, VertexFingerprint,
};
pub use schema::{SchemaHeader, SchemaVersion};
pub use solver::{
    BudgetCeiling, DegreesOfFreedom, NewtonDamping, NewtonStepTolerance, Parameter, ParameterIndex,
    ParentIndex, ResidualIndex, SketchItemId, SketchStatus, SolverResidual, SolverSeed,
};
pub use space::{
    Aabb3, AxisAngle, OrientedBox3, Plane3, Point2, Point3, SketchPlaneBasis, UnitVec2, UnitVec3,
    Vec2, Vec3,
};
pub use step::{
    StepEntityId, StepEntityKind, StepFileHeader, StepFileName, StepOrganization,
    StepOriginatingSystem, StepSchema,
};

#[cfg(feature = "testing")]
pub mod testing;

#[derive(Debug, thiserror::Error)]
pub enum TypesError {
    #[error("sketch plane axes not orthogonal: |x·y|={0}")]
    NonOrthogonalPlaneAxes(f64),
    #[error("axis vector is zero-length")]
    ZeroLengthAxis,
    #[error("axis vector is not unit length: norm {0}")]
    NonUnitAxis(f64),
    #[error("oriented box half-extent must be finite and non-negative: {0}")]
    InvalidHalfExtent(f64),
    #[error("camera eye and target coincide: separation {0} mm")]
    DegenerateCamera(f64),
    #[error("camera eye or target is not finite")]
    CameraNotFinite,
    #[error("camera up direction is parallel to the view direction")]
    CameraUpParallelToView,
    #[error("orthographic half-height must be finite and positive: {0} mm")]
    NonPositiveOrthoHeight(f64),
    #[error("perspective field of view must be within (0, pi) radians: {0}")]
    FovOutOfRange(f64),
    #[error("perspective near distance must be finite and positive: {0} mm")]
    NonPositiveNear(f64),
    #[error("perspective far distance must exceed the near distance: near {near} mm, far {far} mm")]
    FarNotBeyondNear { near: f64, far: f64 },
    #[error("zoom factor must be finite and positive: {0}")]
    NonPositiveZoom(f64),
    #[error("orbit pan target is not finite")]
    OrbitPanTargetNotFinite,
    #[error("orbit rotation is not finite")]
    OrbitRotationNotFinite,
    #[error("view-projection matrix is not invertible")]
    NonInvertibleViewProjection,
    #[error("viewport pixel coordinate is not finite: ({x}, {y})")]
    NonFiniteViewportPixel { x: f64, y: f64 },
    #[error("viewport extent has a zero dimension: {width} x {height}")]
    ZeroViewportExtent { width: u32, height: u32 },
    #[error("step entity instance name must be positive")]
    ZeroStepEntityId,
    #[error("length must be finite and positive: {0} m")]
    NonPositiveLength(f64),
    #[error("normal-to view requires a reference plane")]
    NormalToRequiresPlane,
    #[error("cubic easing needs finite controls with x1,x2 in 0..=1: ({x1},{y1}) ({x2},{y2})")]
    InvalidEasingControl { x1: f64, y1: f64, x2: f64, y2: f64 },
    #[error("match score must be finite and within 0..=1: {0}")]
    MatchScoreOutOfRange(f64),
}

pub type Result<T, E = TypesError> = core::result::Result<T, E>;

slotmap::new_key_type! {
    pub struct FaceId;
    pub struct EdgeId;
    pub struct VertexId;
    pub struct ShellId;
    pub struct SolidId;
    pub struct LoopId;
    pub struct WireId;
    pub struct FeatureId;
    pub struct NodeId;
    pub struct DocumentId;
    pub struct SketchId;
    pub struct SketchEntityId;
    pub struct SketchRelationId;
    pub struct SketchDimensionId;
    pub struct SketchParameterId;
    pub struct ExtrudeId;
    pub struct BodyId;
    pub struct BrepShellId;
    pub struct BrepFaceId;
    pub struct BrepEdgeId;
    pub struct BrepVertexId;
    pub struct BrepLoopId;
}

macro_rules! impl_as_u64 {
    ($($key:ty),+ $(,)?) => {
        $(impl $key {
            /// Encodes this id as an opaque `u64`, stable for the same slotmap slot+version
            /// within a single process. Use only for deterministic widget-key derivation; the
            /// representation is not portable across builds or persisted artifacts.
            #[must_use]
            pub fn as_u64(self) -> u64 {
                use slotmap::Key;
                self.data().as_ffi()
            }
        })+
    };
}

impl_as_u64!(SketchId, ExtrudeId, BrepEdgeId, BrepVertexId);

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct BrepSlot(u32);

impl core::fmt::Display for BrepSlot {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.0.fmt(f)
    }
}

macro_rules! impl_slot {
    ($($key:ty),+ $(,)?) => {
        $(impl $key {
            #[must_use]
            pub fn slot(self) -> BrepSlot {
                use slotmap::Key;
                let low = self.data().as_ffi() & u64::from(u32::MAX);
                BrepSlot(u32::try_from(low).expect("masked value fits in u32"))
            }
        })+
    };
}

impl_slot!(BrepEdgeId, BrepVertexId);

#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Tolerance(f64);

impl Tolerance {
    #[must_use]
    pub const fn new(value: f64) -> Self {
        Self(value)
    }

    #[must_use]
    pub const fn value(self) -> f64 {
        self.0
    }
}

impl core::fmt::Display for Tolerance {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "tol={}", self.0)
    }
}

#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct AngleTolerance(f64);

impl AngleTolerance {
    pub const ZERO: Self = Self(0.0);

    #[must_use]
    pub const fn from_radians(value: f64) -> Self {
        Self(value)
    }

    #[must_use]
    pub const fn radians(self) -> f64 {
        self.0
    }

    #[must_use]
    pub fn from_arc_length(linear: Tolerance, radius: Length) -> Self {
        let r = radius.get::<millimeter>().abs();
        if r > linear.value() {
            Self(linear.value() / r)
        } else {
            Self(linear.value())
        }
    }
}

impl core::fmt::Display for AngleTolerance {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "tol_angle={} rad", self.0)
    }
}

#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct ChordHeightTolerance(Length);

impl ChordHeightTolerance {
    #[must_use]
    pub fn new(length: Length) -> Self {
        Self(length)
    }

    #[must_use]
    pub fn from_mm(value: f64) -> Self {
        Self(Length::new::<millimeter>(value))
    }

    #[must_use]
    pub fn length(self) -> Length {
        self.0
    }

    #[must_use]
    pub fn millimeters(self) -> f64 {
        self.0.get::<millimeter>()
    }
}

impl core::fmt::Display for ChordHeightTolerance {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "chord_tol={} mm", self.0.get::<millimeter>())
    }
}

#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "f64", into = "f64")]
pub struct PositiveLength(Length);

impl PositiveLength {
    pub fn new(length: Length) -> Result<Self> {
        let meters = length.get::<meter>();
        if meters.is_finite() && meters > 0.0 {
            Ok(Self(length))
        } else {
            Err(TypesError::NonPositiveLength(meters))
        }
    }

    #[must_use]
    pub fn get(self) -> Length {
        self.0
    }
}

impl From<PositiveLength> for f64 {
    fn from(value: PositiveLength) -> Self {
        value.0.get::<meter>()
    }
}

impl TryFrom<f64> for PositiveLength {
    type Error = TypesError;

    fn try_from(value: f64) -> Result<Self> {
        Self::new(Length::new::<meter>(value))
    }
}

#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct CreaseAngle(f64);

impl CreaseAngle {
    pub const FLAT: Self = Self(0.0);

    #[must_use]
    pub const fn from_radians(value: f64) -> Self {
        Self(value)
    }

    #[must_use]
    pub fn from_dot(dot: f64) -> Self {
        Self(dot.clamp(-1.0, 1.0).acos())
    }

    #[must_use]
    pub fn angle(self) -> Angle {
        Angle::new::<radian>(self.0)
    }

    #[must_use]
    pub const fn radians(self) -> f64 {
        self.0
    }
}

impl core::fmt::Display for CreaseAngle {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "crease={} rad", self.0)
    }
}

#[derive(
    Copy,
    Clone,
    Debug,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Default,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct MeshGeneration(u64);

impl MeshGeneration {
    #[must_use]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    #[must_use]
    pub const fn value(self) -> u64 {
        self.0
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct GeometryGeneration(u64);

impl GeometryGeneration {
    #[must_use]
    pub fn from_solid_key(key: SolidKey) -> Self {
        let folded = key
            .bytes()
            .chunks_exact(8)
            .map(|word| {
                let mut bytes = [0u8; 8];
                bytes.copy_from_slice(word);
                u64::from_le_bytes(bytes)
            })
            .fold(0u64, core::ops::BitXor::bitxor);
        Self(folded)
    }

    #[must_use]
    pub const fn value(self) -> u64 {
        self.0
    }
}

impl core::fmt::Display for MeshGeneration {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "mesh_gen={}", self.0)
    }
}

#[cfg(test)]
mod tests {
    use super::BrepSlot;
    use super::{
        Aabb3, Angle, AngleTolerance, AxisAngle, BodyId, BrepEdgeId, BrepFaceId, BrepLoopId,
        BrepShellId, BrepVertexId, BuildFailure, Camera3, ChordHeightTolerance, CreaseAngle,
        CubicEasing, DegreesOfFreedom, DisplayMode, DocumentId, EdgeFingerprint, EdgeId, EdgeLabel,
        EdgeRole, EntityFingerprint, EntityRef, ExtrudeId, FaceFingerprint, FaceId, FaceLabel,
        FaceRef, FaceRole, FeatureGeneration, FeatureId, ImportOrdinal, Length, LoopId, LoopIndex,
        MatchScore, MeshGeneration, NodeId, OrbitState, OrientedBox3, Parameter, Plane3, Point2,
        Point3, PositiveLength, Projection, ProjectionKind, RebuildError, RebuildStatus,
        RebuildWarning, Resolution, RollbackMarker, ShadingModel, ShellId, SideKind,
        SketchDimensionId, SketchEntityId, SketchId, SketchParameterId, SketchPlaneBasis,
        SketchRelationId, SolidId, SolverResidual, StandardView, StepEntityId, StepEntityKind,
        StepFileHeader, StepFileName, StepOrganization, StepOriginatingSystem, StepSchema,
        SuppressionState, Tolerance, UnitVec2, UnitVec3, Vec2, Vec3, VertexFingerprint, VertexId,
        VertexLabel, VertexRole, WireId, ZoomFactor, degree, millimeter, radian,
    };
    use slotmap::{Key, SlotMap};
    use uom::si::length::meter;

    fn ortho_camera() -> Camera3 {
        let Ok(projection) = Projection::orthographic(Length::new::<millimeter>(25.0)) else {
            panic!("25 mm half-height is positive");
        };
        let Ok(camera) = Camera3::new(
            Point3::from_mm(0.0, 0.0, 10.0),
            Point3::origin(),
            UnitVec3::y_axis(),
            projection,
        ) else {
            panic!("eye and target are 10 mm apart");
        };
        camera
    }

    #[test]
    fn id_null_is_null() {
        assert!(FaceId::null().is_null());
        assert!(EdgeId::null().is_null());
        assert!(VertexId::null().is_null());
        assert!(ShellId::null().is_null());
        assert!(SolidId::null().is_null());
        assert!(LoopId::null().is_null());
        assert!(WireId::null().is_null());
        assert!(FeatureId::null().is_null());
        assert!(NodeId::null().is_null());
        assert!(DocumentId::null().is_null());
        assert!(SketchId::null().is_null());
        assert!(SketchEntityId::null().is_null());
        assert!(SketchRelationId::null().is_null());
        assert!(SketchDimensionId::null().is_null());
        assert!(SketchParameterId::null().is_null());
        assert!(ExtrudeId::null().is_null());
        assert!(BodyId::null().is_null());
        assert!(BrepShellId::null().is_null());
        assert!(BrepFaceId::null().is_null());
        assert!(BrepEdgeId::null().is_null());
        assert!(BrepVertexId::null().is_null());
        assert!(BrepLoopId::null().is_null());
    }

    #[test]
    fn brep_slot_is_the_one_based_insertion_index() {
        let mut edges: SlotMap<BrepEdgeId, ()> = SlotMap::with_key();
        let slots: Vec<BrepSlot> = (0..3).map(|_| edges.insert(()).slot()).collect();
        assert_eq!(slots, vec![BrepSlot(1), BrepSlot(2), BrepSlot(3)]);
    }

    #[test]
    fn ids_are_distinct_types() {
        let _f: FaceId = FaceId::null();
        let _e: EdgeId = EdgeId::null();
        let _s: SketchEntityId = SketchEntityId::null();
        let _r: SketchRelationId = SketchRelationId::null();
    }

    #[test]
    fn length_mm_roundtrip() {
        let l = Length::new::<millimeter>(12.5);
        assert!((l.get::<millimeter>() - 12.5).abs() < f64::EPSILON);
    }

    #[test]
    fn angle_deg_converts_to_rad() {
        let a = Angle::new::<degree>(180.0);
        assert!((a.get::<radian>() - core::f64::consts::PI).abs() < 1e-12);
    }

    #[test]
    fn tolerance_display() {
        let t = Tolerance::new(1e-6);
        assert_eq!(format!("{t}"), "tol=0.000001");
        assert!((t.value() - 1e-6).abs() < f64::EPSILON);
    }

    #[test]
    fn angle_tolerance_from_arc_length_scales_by_radius() {
        let linear = Tolerance::new(1e-3);
        let r = Length::new::<millimeter>(10.0);
        let a = AngleTolerance::from_arc_length(linear, r);
        assert!((a.radians() - 1e-4).abs() < 1e-15);
    }

    #[test]
    fn angle_tolerance_degenerate_radius_falls_back_to_linear() {
        let linear = Tolerance::new(1e-3);
        let r = Length::new::<millimeter>(0.0);
        let a = AngleTolerance::from_arc_length(linear, r);
        assert!((a.radians() - 1e-3).abs() < 1e-15);
    }

    #[test]
    fn angle_tolerance_zero_constant() {
        assert!(AngleTolerance::ZERO.radians().abs() < f64::EPSILON);
    }

    #[test]
    fn crease_angle_flat_is_zero() {
        assert!(CreaseAngle::FLAT.radians().abs() < f64::EPSILON);
    }

    #[test]
    fn crease_angle_from_dot_right_angle() {
        let a = CreaseAngle::from_dot(0.0);
        assert!((a.radians() - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
    }

    #[test]
    fn crease_angle_from_dot_clamps_outside_unit() {
        let a = CreaseAngle::from_dot(1.5);
        assert!(a.radians().abs() < 1e-12);
        let b = CreaseAngle::from_dot(-1.5);
        assert!((b.radians() - core::f64::consts::PI).abs() < 1e-12);
    }

    #[test]
    fn point2_minus_point2_is_vec2() {
        let a = Point2::from_mm(10.0, 5.0);
        let b = Point2::from_mm(4.0, 2.0);
        let d: Vec2 = a - b;
        assert!((d.x().get::<millimeter>() - 6.0).abs() < 1e-12);
        assert!((d.y().get::<millimeter>() - 3.0).abs() < 1e-12);
    }

    #[test]
    fn point2_plus_vec2_is_point2() {
        let p = Point2::from_mm(1.0, 2.0);
        let v = Vec2::from_mm(10.0, 20.0);
        let q: Point2 = p + v;
        assert!((q.x().get::<millimeter>() - 11.0).abs() < 1e-12);
        assert!((q.y().get::<millimeter>() - 22.0).abs() < 1e-12);
    }

    #[test]
    fn vec2_perp_and_dot() {
        let v = Vec2::from_mm(3.0, 4.0);
        assert!((v.norm_mm() - 5.0).abs() < 1e-12);
        let p = v.perp_ccw();
        assert!((p.x().get::<millimeter>() + 4.0).abs() < 1e-12);
        assert!((p.y().get::<millimeter>() - 3.0).abs() < 1e-12);
        assert!(v.dot_mm2(p).abs() < 1e-12);
        assert!((v.cross_z_mm2(Vec2::from_mm(1.0, 0.0)) + 4.0).abs() < 1e-12);
    }

    #[test]
    fn vec2_try_normalize_rejects_zero() {
        let v = Vec2::zero();
        let r = v.try_normalize(Tolerance::new(1e-9));
        assert!(r.is_err());
    }

    #[test]
    fn vec2_try_normalize_unit() {
        let v = Vec2::from_mm(0.0, 7.0);
        let Ok(u) = v.try_normalize(Tolerance::new(1e-9)) else {
            panic!("nonzero");
        };
        let (ux, uy) = u.components();
        assert!(ux.abs() < 1e-12);
        assert!((uy - 1.0).abs() < 1e-12);
    }

    #[test]
    fn unit_vec2_axes_are_orthogonal() {
        let x = UnitVec2::x_axis();
        let y = UnitVec2::y_axis();
        assert!(x.dot(y).abs() < 1e-15);
        assert_eq!(x.perp_ccw().components(), y.components());
    }

    #[test]
    fn unit_vec2_rejects_zero_axis() {
        let r = UnitVec2::try_from_components(0.0, 0.0, Tolerance::new(1e-9));
        assert!(r.is_err());
    }

    #[test]
    fn unit_vec2_into_vec_scales_by_length() {
        let u = UnitVec2::x_axis();
        let v = u.into_vec(Length::new::<millimeter>(3.0));
        assert!((v.x().get::<millimeter>() - 3.0).abs() < 1e-12);
        assert!(v.y().get::<millimeter>().abs() < 1e-12);
    }

    #[test]
    fn vec2_scalar_and_negation() {
        let v = Vec2::from_mm(3.0, -4.0);
        let w = 2.0 * (-v);
        assert!((w.x().get::<millimeter>() + 6.0).abs() < 1e-12);
        assert!((w.y().get::<millimeter>() - 8.0).abs() < 1e-12);
    }

    #[test]
    fn point3_roundtrip() {
        let p = Point3::from_mm(1.5, 2.5, 3.5);
        assert!((p.x().get::<millimeter>() - 1.5).abs() < 1e-12);
        assert!((p.y().get::<millimeter>() - 2.5).abs() < 1e-12);
        assert!((p.z().get::<millimeter>() - 3.5).abs() < 1e-12);
    }

    #[test]
    fn sketch_plane_basis_accepts_orthogonal_axes() {
        let Ok(basis) = SketchPlaneBasis::new(
            Point3::origin(),
            UnitVec3::x_axis(),
            UnitVec3::y_axis(),
            Tolerance::new(1e-9),
        ) else {
            panic!("x and y unit axes are orthogonal");
        };
        let (nx, ny, nz) = basis.normal().components();
        assert!((nx).abs() < 1e-12);
        assert!((ny).abs() < 1e-12);
        assert!((nz - 1.0).abs() < 1e-12);
    }

    #[test]
    fn sketch_plane_basis_reorthonormalizes_within_tolerance() {
        let Ok(nearly) = UnitVec3::try_from_components(1e-10, 1.0, 0.0, Tolerance::new(1e-9))
        else {
            panic!("input vector is nonzero");
        };
        let Ok(basis) = SketchPlaneBasis::new(
            Point3::origin(),
            UnitVec3::x_axis(),
            nearly,
            Tolerance::new(1e-9),
        ) else {
            panic!("within tolerance");
        };
        let dot_after = basis.x_axis().dot(basis.y_axis()).abs();
        assert!(
            dot_after < 1e-15,
            "re-orthonormalized y should be orthogonal, got {dot_after}"
        );
    }

    #[test]
    fn sketch_plane_basis_rejects_non_orthogonal_axes() {
        let Ok(skew) = UnitVec3::try_from_components(1.0, 1.0, 0.0, Tolerance::new(1e-9)) else {
            panic!("input vector is nonzero");
        };
        let result = SketchPlaneBasis::new(
            Point3::origin(),
            UnitVec3::x_axis(),
            skew,
            Tolerance::new(1e-9),
        );
        assert!(result.is_err());
    }

    #[test]
    fn unit_vec3_rejects_zero_and_near_zero_within_tolerance() {
        let tol = Tolerance::new(1e-9);
        assert!(UnitVec3::try_from_components(0.0, 0.0, 0.0, tol).is_err());
        assert!(UnitVec3::try_from_components(1e-13, 0.0, 0.0, tol).is_err());
        assert!(UnitVec3::try_from_components(1.0, 0.0, 0.0, tol).is_ok());
    }

    #[test]
    fn unit_vec3_deserialize_preserves_irrational_components_bit_exact() {
        let Ok(original) = UnitVec3::try_from_components(1.0, 2.0, 3.0, Tolerance::new(1e-9))
        else {
            panic!("normalizable direction");
        };
        let Ok(text) = ron::to_string(&original) else {
            panic!("serialize");
        };
        let Ok(back) = ron::from_str::<UnitVec3>(&text) else {
            panic!("deserialize");
        };
        let (ox, oy, oz) = original.components();
        let (bx, by, bz) = back.components();
        assert_eq!(ox.to_bits(), bx.to_bits());
        assert_eq!(oy.to_bits(), by.to_bits());
        assert_eq!(oz.to_bits(), bz.to_bits());
    }

    #[test]
    fn unit_vec3_deserialize_rejects_non_unit_components() {
        let probe = UnitVec3::new_unchecked(0.6, 0.8, 0.0);
        let Ok(text) = ron::to_string(&probe) else {
            panic!("serialize");
        };
        assert!(ron::from_str::<UnitVec3>(&text).is_ok());
        let non_unit = text.replacen("0.6", "0.9", 1);
        assert_ne!(text, non_unit, "probe value present for mutation");
        assert!(ron::from_str::<UnitVec3>(&non_unit).is_err());
    }

    #[test]
    fn parameter_display_and_value() {
        let p = Parameter::new(0.25);
        assert_eq!(format!("{p}"), "param=0.25");
        assert!((p.value() - 0.25).abs() < f64::EPSILON);
    }

    #[test]
    fn degrees_of_freedom_display_and_value() {
        let d = DegreesOfFreedom::new(7);
        assert_eq!(format!("{d}"), "dof=7");
        assert_eq!(d.value(), 7);
    }

    #[test]
    fn solver_residual_display_and_value() {
        let r = SolverResidual::new(1.5e-6);
        assert_eq!(format!("{r}"), "res=0.0000015");
        assert!((r.value() - 1.5e-6).abs() < f64::EPSILON);
    }

    #[test]
    fn mesh_generation_orders_by_value() {
        let a = MeshGeneration::new(7);
        let b = MeshGeneration::new(42);
        assert!(a < b);
        assert_eq!(format!("{a}"), "mesh_gen=7");
        assert_eq!(a.value(), 7);
        assert_eq!(MeshGeneration::default(), MeshGeneration::new(0));
    }

    #[test]
    fn chord_height_tolerance_display_and_value() {
        let c = ChordHeightTolerance::from_mm(0.01);
        assert!((c.millimeters() - 0.01).abs() < 1e-15);
        assert_eq!(format!("{c}"), "chord_tol=0.01 mm");
        let c2 = ChordHeightTolerance::new(Length::new::<millimeter>(0.05));
        assert!((c2.length().get::<millimeter>() - 0.05).abs() < 1e-15);
    }

    #[test]
    fn vec3_ops_and_normalize() {
        let vec = Vec3::from_mm(1.0, 2.0, 2.0);
        assert!((vec.norm_mm() - 3.0).abs() < 1e-12);
        let unit_x = Vec3::from_mm(1.0, 0.0, 0.0);
        let unit_y = Vec3::from_mm(0.0, 1.0, 0.0);
        assert!((unit_x.cross(unit_y).z().get::<millimeter>() - 1.0).abs() < 1e-12);
        assert!(unit_x.dot_mm2(unit_y).abs() < 1e-12);
        let Ok(normalized) = vec.try_normalize(Tolerance::new(1e-9)) else {
            panic!("nonzero");
        };
        let (nx, ny, nz) = normalized.components();
        assert!((nx * nx + ny * ny + nz * nz - 1.0).abs() < 1e-12);
        assert!(Vec3::zero().try_normalize(Tolerance::new(1e-9)).is_err());
        let far = Point3::from_mm(5.0, 5.0, 5.0);
        let near = Point3::from_mm(1.0, 2.0, 3.0);
        let delta: Vec3 = far - near;
        assert!((delta.x().get::<millimeter>() - 4.0).abs() < 1e-12);
        assert!(((near + delta).x().get::<millimeter>() - 5.0).abs() < 1e-12);
    }

    #[test]
    fn unit_vec3_reverse_and_into_vec() {
        let zaxis = UnitVec3::z_axis();
        assert!((zaxis.reversed().components().2 + 1.0).abs() < 1e-12);
        let scaled = zaxis.into_vec(Length::new::<millimeter>(4.0));
        assert!(scaled.x().get::<millimeter>().abs() < 1e-12);
        assert!((scaled.z().get::<millimeter>() - 4.0).abs() < 1e-12);
    }

    #[test]
    fn plane3_orthonormalizes_and_rejects_skew() {
        let origin = Point3::from_mm(1.0, 2.0, 3.0);
        let Ok(nearly) = UnitVec3::try_from_components(1e-10, 1.0, 0.0, Tolerance::new(1e-9))
        else {
            panic!("nonzero");
        };
        let Ok(plane) = Plane3::new(origin, UnitVec3::x_axis(), nearly, Tolerance::new(1e-9))
        else {
            panic!("within tolerance");
        };
        assert!(plane.x_axis().dot(plane.y_axis()).abs() < 1e-15);
        let (nx, ny, nz) = plane.normal().components();
        assert!(nx.abs() < 1e-12 && ny.abs() < 1e-12 && (nz - 1.0).abs() < 1e-12);
        let Ok(skew) = UnitVec3::try_from_components(1.0, 1.0, 0.0, Tolerance::new(1e-9)) else {
            panic!("nonzero");
        };
        assert!(Plane3::new(origin, UnitVec3::x_axis(), skew, Tolerance::new(1e-9)).is_err());
    }

    #[test]
    fn axis_angle_accessors() {
        let aa = AxisAngle::new(UnitVec3::z_axis(), Angle::new::<radian>(0.5));
        assert!((aa.angle().get::<radian>() - 0.5).abs() < 1e-15);
        assert!((aa.axis().components().2 - 1.0).abs() < 1e-12);
    }

    #[test]
    fn oriented_box_from_aabb_matches_center_and_half() {
        let aabb = Aabb3::from_corners(
            Point3::from_mm(-2.0, -4.0, 0.0),
            Point3::from_mm(2.0, 4.0, 10.0),
        );
        let obox = OrientedBox3::from_aabb(aabb);
        let (cx, cy, cz) = obox.center().coords_mm();
        assert!(cx.abs() < 1e-12 && cy.abs() < 1e-12 && (cz - 5.0).abs() < 1e-12);
        let (hx, hy, hz) = obox.half_extents().coords_mm();
        assert!((hx - 2.0).abs() < 1e-12 && (hy - 4.0).abs() < 1e-12 && (hz - 5.0).abs() < 1e-12);
        assert!((obox.frame().normal().components().2 - 1.0).abs() < 1e-12);
    }

    #[test]
    fn aabb3_from_points_union_contains() {
        let pts = [
            Point3::from_mm(0.0, 0.0, 0.0),
            Point3::from_mm(2.0, -1.0, 5.0),
            Point3::from_mm(-3.0, 4.0, 1.0),
        ];
        let Some(bb) = Aabb3::from_points(pts) else {
            panic!("nonempty");
        };
        let (lx, ly, lz) = bb.min().coords_mm();
        let (hx, hy, hz) = bb.max().coords_mm();
        assert!((lx + 3.0).abs() < 1e-12 && (ly + 1.0).abs() < 1e-12 && lz.abs() < 1e-12);
        assert!((hx - 2.0).abs() < 1e-12 && (hy - 4.0).abs() < 1e-12 && (hz - 5.0).abs() < 1e-12);
        assert!(bb.contains(Point3::from_mm(0.0, 0.0, 2.0)));
        assert!(!bb.contains(Point3::from_mm(10.0, 0.0, 0.0)));
        let (cx, cy, cz) = bb.center().coords_mm();
        assert!((cx + 0.5).abs() < 1e-12 && (cy - 1.5).abs() < 1e-12 && (cz - 2.5).abs() < 1e-12);
        assert!((bb.extent().x().get::<millimeter>() - 5.0).abs() < 1e-12);
        assert!(Aabb3::from_points(core::iter::empty()).is_none());
    }

    #[test]
    fn face_role_ord_matches_canonical_order() {
        let from = SketchEntityId::default();
        let start = FaceRole::StartCap;
        let side0 = FaceRole::Side {
            loop_index: LoopIndex::OUTER,
            from,
        };
        let side1 = FaceRole::Side {
            loop_index: LoopIndex::new(1),
            from,
        };
        let end = FaceRole::EndCap;
        let imported = FaceRole::Imported {
            ordinal: ImportOrdinal::new(0),
        };
        assert!(start < side0);
        assert!(side0 < side1);
        assert!(side1 < end);
        assert!(end < imported);
    }

    #[test]
    fn edge_role_ord_matches_canonical_order() {
        let from = SketchEntityId::default();
        let start = EdgeRole::StartCapEdge { from };
        let side = EdgeRole::SideEdge {
            from,
            side: SideKind::Corner,
        };
        let end = EdgeRole::EndCapEdge { from };
        let imported = EdgeRole::Imported {
            ordinal: ImportOrdinal::new(0),
        };
        assert!(start < side);
        assert!(side < end);
        assert!(end < imported);
    }

    #[test]
    fn vertex_role_ord_matches_canonical_order() {
        let from = SketchEntityId::default();
        let start = VertexRole::StartCapVertex {
            from,
            side: SideKind::Corner,
        };
        let end = VertexRole::EndCapVertex {
            from,
            side: SideKind::Corner,
        };
        let imported = VertexRole::Imported {
            ordinal: ImportOrdinal::new(0),
        };
        assert!(start < end);
        assert!(end < imported);
    }

    #[test]
    fn oriented_box_rejects_invalid_half_extent() {
        let frame = Plane3::new_unchecked(Point3::origin(), UnitVec3::x_axis(), UnitVec3::y_axis());
        assert!(OrientedBox3::new(frame, Vec3::from_mm(1.0, 2.0, 3.0)).is_ok());
        assert!(OrientedBox3::new(frame, Vec3::from_mm(1.0, -2.0, 3.0)).is_err());
        assert!(OrientedBox3::new(frame, Vec3::from_mm(1.0, f64::NAN, 3.0)).is_err());
        assert!(OrientedBox3::new(frame, Vec3::from_mm(f64::INFINITY, 2.0, 3.0)).is_err());
    }

    #[test]
    fn oriented_box_deserialize_rejects_invalid_half_extent() {
        let frame = Plane3::new_unchecked(Point3::origin(), UnitVec3::x_axis(), UnitVec3::y_axis());
        let Ok(obox) = OrientedBox3::new(frame, Vec3::from_mm(5.0, 5.0, 5.0)) else {
            panic!("non-negative half-extents");
        };
        let Ok(good) = ron::to_string(&obox) else {
            panic!("serialize oriented box");
        };
        assert!(ron::from_str::<OrientedBox3>(&good).is_ok());
        let bad = good.replace('5', "-5");
        assert!(ron::from_str::<OrientedBox3>(&bad).is_err());
    }

    #[test]
    fn labels_ron_roundtrip() {
        let feature = FeatureId::default();
        let from = SketchEntityId::default();
        let face = FaceLabel {
            feature,
            role: FaceRole::Side {
                loop_index: LoopIndex::OUTER,
                from,
            },
        };
        let Ok(text) = ron::to_string(&face) else {
            panic!("serialize face label");
        };
        let Ok(back) = ron::from_str::<FaceLabel>(&text) else {
            panic!("deserialize face label");
        };
        assert_eq!(face, back);

        let edge = EdgeLabel {
            feature,
            role: EdgeRole::SideEdge {
                from,
                side: SideKind::Seam,
            },
        };
        let Ok(text) = ron::to_string(&edge) else {
            panic!("serialize edge label");
        };
        let Ok(back) = ron::from_str::<EdgeLabel>(&text) else {
            panic!("deserialize edge label");
        };
        assert_eq!(edge, back);

        let vertex = VertexLabel {
            feature,
            role: VertexRole::EndCapVertex {
                from,
                side: SideKind::Corner,
            },
        };
        let Ok(text) = ron::to_string(&vertex) else {
            panic!("serialize vertex label");
        };
        let Ok(back) = ron::from_str::<VertexLabel>(&text) else {
            panic!("deserialize vertex label");
        };
        assert_eq!(vertex, back);
    }

    #[test]
    fn role_rejects_unknown_field() {
        let label = FaceLabel {
            feature: FeatureId::default(),
            role: FaceRole::Side {
                loop_index: LoopIndex::OUTER,
                from: SketchEntityId::default(),
            },
        };
        let Ok(text) = ron::to_string(&label) else {
            panic!("serialize face label");
        };
        let Some(idx) = text.find("Side(") else {
            panic!("expected Side variant in {text}");
        };
        let mut munged = text.clone();
        munged.insert_str(idx + "Side(".len(), "bogus:42,");
        assert!(ron::from_str::<FaceLabel>(&munged).is_err());
    }

    #[test]
    fn camera_new_rejects_coincident_eye_and_target() {
        let Ok(projection) = Projection::orthographic(Length::new::<millimeter>(10.0)) else {
            panic!("10 mm half-height is positive");
        };
        let coincident = Camera3::new(
            Point3::from_mm(1.0, 2.0, 3.0),
            Point3::from_mm(1.0, 2.0, 3.0),
            UnitVec3::y_axis(),
            projection,
        );
        assert!(coincident.is_err());
    }

    #[test]
    fn camera_accessors_round_trip_fields() {
        let camera = ortho_camera();
        assert!((camera.eye().z().get::<millimeter>() - 10.0).abs() < 1e-12);
        assert!(camera.target().coords_mm().0.abs() < 1e-12);
        assert!((camera.up().components().1 - 1.0).abs() < 1e-12);
        let ProjectionKind::Orthographic { half_height } = camera.projection().kind() else {
            panic!("constructed an orthographic camera");
        };
        assert!((half_height.get::<millimeter>() - 25.0).abs() < 1e-12);
    }

    #[test]
    fn camera_ron_round_trip() {
        let camera = ortho_camera();
        let Ok(text) = ron::to_string(&camera) else {
            panic!("serialize camera");
        };
        let Ok(back) = ron::from_str::<Camera3>(&text) else {
            panic!("deserialize camera");
        };
        assert_eq!(camera, back);
    }

    #[test]
    fn camera_deserialize_rejects_degenerate() {
        let Ok(text) = ron::to_string(&ortho_camera()) else {
            panic!("serialize camera");
        };
        assert!(ron::from_str::<Camera3>(&text).is_ok());
        let collapsed = text.replace("z:10.0", "z:0.0");
        assert!(ron::from_str::<Camera3>(&collapsed).is_err());
    }

    #[test]
    fn orbit_state_identity_is_unrotated() {
        let orbit = OrbitState::identity();
        assert!((orbit.rotation().angle().get::<radian>()).abs() < 1e-12);
        assert!((orbit.zoom().value() - 1.0).abs() < 1e-12);
        assert!(orbit.pan_target().coords_mm().0.abs() < 1e-12);
    }

    #[test]
    fn orbit_state_rotated_accumulates_angle() {
        let quarter = AxisAngle::new(
            UnitVec3::z_axis(),
            Angle::new::<radian>(core::f64::consts::FRAC_PI_2),
        );
        let once = OrbitState::identity().rotated(quarter);
        let twice = once.rotated(quarter);
        assert!(
            (once.rotation().angle().get::<radian>() - core::f64::consts::FRAC_PI_2).abs() < 1e-12
        );
        assert!((twice.rotation().angle().get::<radian>() - core::f64::consts::PI).abs() < 1e-12);
        assert!((twice.rotation().axis().components().2 - 1.0).abs() < 1e-12);
    }

    #[test]
    fn orbit_state_ron_round_trip() {
        let Ok(zoom) = ZoomFactor::new(2.5) else {
            panic!("positive zoom");
        };
        let Ok(orbit) = OrbitState::new(
            AxisAngle::new(
                UnitVec3::z_axis(),
                Angle::new::<radian>(core::f64::consts::FRAC_PI_2),
            ),
            zoom,
            Point3::from_mm(1.0, 2.0, 3.0),
        ) else {
            panic!("finite pan target");
        };
        let Ok(text) = ron::to_string(&orbit) else {
            panic!("serialize orbit");
        };
        let Ok(back) = ron::from_str::<OrbitState>(&text) else {
            panic!("deserialize orbit");
        };
        assert_eq!(orbit, back);
    }

    #[test]
    fn standard_view_labels_are_distinct() {
        let views = [
            StandardView::Front,
            StandardView::Back,
            StandardView::Left,
            StandardView::Right,
            StandardView::Top,
            StandardView::Bottom,
            StandardView::Isometric,
            StandardView::NormalTo,
        ];
        let labels: std::collections::BTreeSet<&str> = views.iter().map(|v| v.label()).collect();
        assert_eq!(labels.len(), views.len());
    }

    #[test]
    fn step_entity_id_display() {
        let Ok(id) = StepEntityId::new(123) else {
            panic!("123 is a positive instance name");
        };
        assert_eq!(format!("{id}"), "#123");
        let Ok(seven) = StepEntityId::new(7) else {
            panic!("7 is a positive instance name");
        };
        assert_eq!(seven.value(), 7);
    }

    #[test]
    fn step_entity_id_rejects_zero() {
        assert!(StepEntityId::new(0).is_err());
        assert!(StepEntityId::new(1).is_ok());
        assert!(ron::from_str::<StepEntityId>("0").is_err());
        assert!(ron::from_str::<StepEntityId>("123").is_ok());
    }

    #[test]
    fn step_schema_labels() {
        assert_eq!(StepSchema::Ap214.label(), "AP214");
        assert_eq!(StepSchema::Ap242E2.label(), "AP242E2");
    }

    #[test]
    fn step_entity_kind_labels_and_round_trip() {
        assert_eq!(
            StepEntityKind::CylindricalSurface.label(),
            "a cylindrical surface"
        );
        assert_eq!(StepEntityKind::ConicCurve.label(), "a conic curve");
        let Ok(text) = ron::to_string(&StepEntityKind::ToroidalSurface) else {
            panic!("serialize step entity kind");
        };
        let Ok(back) = ron::from_str::<StepEntityKind>(&text) else {
            panic!("deserialize step entity kind");
        };
        assert_eq!(StepEntityKind::ToroidalSurface, back);
    }

    #[test]
    fn step_file_header_ron_round_trip() {
        let header = StepFileHeader {
            schema: StepSchema::Ap214,
            originating_system: StepOriginatingSystem::new("bone 0.0.0"),
            organization: StepOrganization::new("witchcraft.systems"),
            file_name: StepFileName::new("limpet.step"),
        };
        let Ok(text) = ron::to_string(&header) else {
            panic!("serialize step header");
        };
        let Ok(back) = ron::from_str::<StepFileHeader>(&text) else {
            panic!("deserialize step header");
        };
        assert_eq!(header, back);
        assert_eq!(header.file_name.as_str(), "limpet.step");
    }

    #[test]
    fn display_mode_default_and_labels() {
        assert_eq!(DisplayMode::DEFAULT, DisplayMode::ShadedWithEdges);
        assert_eq!(DisplayMode::HiddenLineGray.label(), "hidden_line_gray");
        assert_eq!(ShadingModel::Gouraud.label(), "gouraud");
    }

    #[test]
    fn camera_rejects_non_finite_eye() {
        let Ok(projection) = Projection::orthographic(Length::new::<millimeter>(10.0)) else {
            panic!("10 mm half-height is positive");
        };
        let nan = Camera3::new(
            Point3::from_mm(f64::NAN, 0.0, 0.0),
            Point3::origin(),
            UnitVec3::y_axis(),
            projection,
        );
        assert!(nan.is_err());
        let infinite = Camera3::new(
            Point3::from_mm(f64::INFINITY, 0.0, 0.0),
            Point3::origin(),
            UnitVec3::y_axis(),
            projection,
        );
        assert!(infinite.is_err());
    }

    #[test]
    fn camera_rejects_up_parallel_to_view() {
        let Ok(projection) = Projection::orthographic(Length::new::<millimeter>(10.0)) else {
            panic!("10 mm half-height is positive");
        };
        let parallel = Camera3::new(
            Point3::from_mm(0.0, 0.0, 10.0),
            Point3::origin(),
            UnitVec3::z_axis(),
            projection,
        );
        assert!(parallel.is_err());
    }

    #[test]
    fn projection_constructors_validate() {
        let mm = |v| Length::new::<millimeter>(v);
        assert!(Projection::orthographic(mm(25.0)).is_ok());
        assert!(Projection::orthographic(mm(0.0)).is_err());
        assert!(Projection::orthographic(mm(-1.0)).is_err());
        assert!(Projection::orthographic(Length::new::<millimeter>(f64::NAN)).is_err());
        assert!(Projection::perspective(Angle::new::<degree>(60.0), mm(1.0), mm(1000.0)).is_ok());
        assert!(Projection::perspective(Angle::new::<degree>(400.0), mm(1.0), mm(1000.0)).is_err());
        assert!(Projection::perspective(Angle::new::<degree>(60.0), mm(10.0), mm(1.0)).is_err());
        assert!(Projection::perspective(Angle::new::<degree>(60.0), mm(0.0), mm(1000.0)).is_err());
    }

    #[test]
    fn projection_deserialize_rejects_degenerate() {
        let Ok(valid) = Projection::orthographic(Length::new::<millimeter>(25.0)) else {
            panic!("25 mm half-height is positive");
        };
        let Ok(text) = ron::to_string(&valid) else {
            panic!("serialize projection");
        };
        assert!(ron::from_str::<Projection>(&text).is_ok());
        let degenerate = text.replace("0.025", "-0.025");
        assert!(ron::from_str::<Projection>(&degenerate).is_err());
    }

    #[test]
    fn zoom_factor_rejects_non_positive() {
        assert!(ZoomFactor::new(2.5).is_ok());
        assert!(ZoomFactor::new(0.0).is_err());
        assert!(ZoomFactor::new(-1.0).is_err());
        assert!(ZoomFactor::new(f64::NAN).is_err());
        assert!(ZoomFactor::new(f64::INFINITY).is_err());
    }

    #[test]
    fn cubic_easing_constrains_x_controls_to_the_unit_interval() {
        assert!(CubicEasing::new(0.2, 0.0, 0.0, 1.0).is_ok());
        assert!(CubicEasing::new(0.0, -2.0, 1.0, 3.0).is_ok());
        assert!(CubicEasing::new(1.5, 0.0, 0.5, 1.0).is_err());
        assert!(CubicEasing::new(0.2, 0.0, -0.5, 1.0).is_err());
        assert!(CubicEasing::new(f64::NAN, 0.0, 0.5, 1.0).is_err());
        assert!(CubicEasing::new(0.2, f64::INFINITY, 0.5, 1.0).is_err());
    }

    #[test]
    fn zoom_factor_deserialize_rejects_non_positive() {
        assert!(ron::from_str::<ZoomFactor>("2.5").is_ok());
        assert!(ron::from_str::<ZoomFactor>("0.0").is_err());
        assert!(ron::from_str::<ZoomFactor>("-1.0").is_err());
    }

    #[test]
    fn positive_length_rejects_non_positive_and_non_finite() {
        assert!(PositiveLength::new(Length::new::<meter>(0.5)).is_ok());
        assert!(PositiveLength::new(Length::new::<meter>(f64::MIN_POSITIVE)).is_ok());
        assert!(PositiveLength::new(Length::new::<meter>(0.0)).is_err());
        assert!(PositiveLength::new(Length::new::<meter>(-1.0)).is_err());
        assert!(PositiveLength::new(Length::new::<meter>(f64::INFINITY)).is_err());
        assert!(PositiveLength::new(Length::new::<meter>(f64::NEG_INFINITY)).is_err());
        assert!(PositiveLength::new(Length::new::<meter>(f64::NAN)).is_err());
    }

    #[test]
    fn positive_length_round_trips_through_meters() {
        let Ok(length) = PositiveLength::new(Length::new::<meter>(0.0123)) else {
            panic!("0.0123 m is positive");
        };
        assert!((f64::from(length) - 0.0123).abs() < f64::EPSILON);
        assert!((length.get().get::<meter>() - 0.0123).abs() < f64::EPSILON);
    }

    #[test]
    fn positive_length_deserialize_rejects_non_positive() {
        assert!(ron::from_str::<PositiveLength>("0.5").is_ok());
        assert!(ron::from_str::<PositiveLength>("0.0").is_err());
        assert!(ron::from_str::<PositiveLength>("-1.0").is_err());
        assert!(ron::from_str::<PositiveLength>("inf").is_err());
        assert!(ron::from_str::<PositiveLength>("NaN").is_err());
    }

    #[test]
    fn orbit_state_deserialize_normalizes_non_unit_quaternion() {
        let nonunit = "(qw:2.0,qx:0.0,qy:0.0,qz:0.0,zoom:1.0,pan_target:(x:0.0,y:0.0,z:0.0))";
        let Ok(orbit) = ron::from_str::<OrbitState>(nonunit) else {
            panic!("non-unit quaternion should normalize, not fail");
        };
        let Ok(text) = ron::to_string(&orbit) else {
            panic!("serialize orbit");
        };
        assert!(
            text.contains("qw:1"),
            "quaternion should re-normalize to unit, got {text}"
        );
    }

    #[test]
    fn orbit_state_deserialize_rejects_zero_quaternion() {
        let zero = "(qw:0.0,qx:0.0,qy:0.0,qz:0.0,zoom:1.0,pan_target:(x:0.0,y:0.0,z:0.0))";
        assert!(ron::from_str::<OrbitState>(zero).is_err());
    }

    #[test]
    fn orbit_state_rejects_non_finite_pan_target() {
        let Ok(zoom) = ZoomFactor::new(1.0) else {
            panic!("positive zoom");
        };
        let rotation = AxisAngle::new(UnitVec3::z_axis(), Angle::new::<radian>(0.0));
        assert!(OrbitState::new(rotation, zoom, Point3::from_mm(f64::NAN, 0.0, 0.0)).is_err());
        assert!(OrbitState::new(rotation, zoom, Point3::from_mm(f64::INFINITY, 0.0, 0.0)).is_err());
        assert!(OrbitState::new(rotation, zoom, Point3::origin()).is_ok());
    }

    #[test]
    fn orbit_state_deserialize_rejects_non_finite_pan_target() {
        let finite = "(qw:1.0,qx:0.0,qy:0.0,qz:0.0,zoom:1.0,pan_target:(x:0.0,y:0.0,z:0.0))";
        assert!(ron::from_str::<OrbitState>(finite).is_ok());
        let non_finite = "(qw:1.0,qx:0.0,qy:0.0,qz:0.0,zoom:1.0,pan_target:(x:0.0,y:0.0,z:inf))";
        assert!(ron::from_str::<OrbitState>(non_finite).is_err());
    }

    #[test]
    fn orbit_state_deserialize_rejects_non_finite_rotation() {
        let inf = "(qw:inf,qx:0.0,qy:0.0,qz:0.0,zoom:1.0,pan_target:(x:0.0,y:0.0,z:0.0))";
        assert!(ron::from_str::<OrbitState>(inf).is_err());
        let nan = "(qw:1.0,qx:NaN,qy:0.0,qz:0.0,zoom:1.0,pan_target:(x:0.0,y:0.0,z:0.0))";
        assert!(ron::from_str::<OrbitState>(nan).is_err());
    }

    #[test]
    fn orbit_state_new_rejects_non_finite_rotation() {
        let Ok(zoom) = ZoomFactor::new(1.0) else {
            panic!("positive zoom");
        };
        let bad = AxisAngle::new(UnitVec3::z_axis(), Angle::new::<radian>(f64::INFINITY));
        assert!(OrbitState::new(bad, zoom, Point3::origin()).is_err());
        let good = AxisAngle::new(UnitVec3::z_axis(), Angle::new::<radian>(0.5));
        assert!(OrbitState::new(good, zoom, Point3::origin()).is_ok());
    }

    #[test]
    fn unit_vec3_rotated_quarter_turn_about_z() {
        let q = AxisAngle::new(
            UnitVec3::z_axis(),
            Angle::new::<radian>(core::f64::consts::FRAC_PI_2),
        );
        let (cx, cy, cz) = UnitVec3::x_axis().rotated(q).components();
        assert!(
            cx.abs() < 1e-12 && (cy - 1.0).abs() < 1e-12 && cz.abs() < 1e-12,
            "x rotated +90 deg about z is y: ({cx},{cy},{cz})"
        );
    }

    #[test]
    fn point3_rotated_about_pivot_quarter_turn() {
        let pivot = Point3::from_mm(1.0, 0.0, 0.0);
        let q = AxisAngle::new(
            UnitVec3::z_axis(),
            Angle::new::<radian>(core::f64::consts::FRAC_PI_2),
        );
        let (x, y, z) = Point3::from_mm(2.0, 0.0, 0.0)
            .rotated_about(pivot, q)
            .coords_mm();
        assert!(
            (x - 1.0).abs() < 1e-12 && (y - 1.0).abs() < 1e-12 && z.abs() < 1e-12,
            "(2,0,0) about (1,0,0) +90 deg z is (1,1,0): ({x},{y},{z})"
        );
    }

    #[test]
    fn camera_perspective_ron_round_trip() {
        let Ok(persp) = Projection::perspective(
            Angle::new::<degree>(60.0),
            Length::new::<millimeter>(1.0),
            Length::new::<millimeter>(1000.0),
        ) else {
            panic!("valid perspective");
        };
        let Ok(camera) = Camera3::new(
            Point3::from_mm(0.0, 0.0, 10.0),
            Point3::origin(),
            UnitVec3::y_axis(),
            persp,
        ) else {
            panic!("eye and target are 10 mm apart");
        };
        let Ok(text) = ron::to_string(&camera) else {
            panic!("serialize camera");
        };
        let Ok(back) = ron::from_str::<Camera3>(&text) else {
            panic!("deserialize camera");
        };
        assert_eq!(camera, back);
    }

    fn assert_ron_round_trip<T>(value: &T)
    where
        T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + core::fmt::Debug,
    {
        let Ok(text) = ron::to_string(value) else {
            panic!("serialize {value:?}");
        };
        let Ok(back) = ron::from_str::<T>(&text) else {
            panic!("deserialize {text}");
        };
        assert_eq!(value, &back);
    }

    #[test]
    fn discrete_types_ron_round_trip() {
        [
            DisplayMode::Wireframe,
            DisplayMode::HiddenLineRemoved,
            DisplayMode::HiddenLineGray,
            DisplayMode::ShadedWithEdges,
            DisplayMode::ShadedNoEdges,
        ]
        .iter()
        .for_each(assert_ron_round_trip);
        [
            ShadingModel::Flat,
            ShadingModel::Gouraud,
            ShadingModel::Phong,
        ]
        .iter()
        .for_each(assert_ron_round_trip);
        [
            StandardView::Front,
            StandardView::Back,
            StandardView::Left,
            StandardView::Right,
            StandardView::Top,
            StandardView::Bottom,
            StandardView::Isometric,
            StandardView::NormalTo,
        ]
        .iter()
        .for_each(assert_ron_round_trip);
        [StepSchema::Ap214, StepSchema::Ap242E2]
            .iter()
            .for_each(assert_ron_round_trip);
        let Ok(entity) = StepEntityId::new(123) else {
            panic!("123 is a positive instance name");
        };
        assert_ron_round_trip(&entity);
    }

    fn sample_face_fingerprint() -> FaceFingerprint {
        let plane = Plane3::new_unchecked(
            Point3::from_mm(1.0, 2.0, 3.0),
            UnitVec3::x_axis(),
            UnitVec3::y_axis(),
        );
        FaceFingerprint {
            plane,
            centroid: Point3::from_mm(4.0, 5.0, 6.0),
        }
    }

    fn sample_face_ref() -> EntityRef {
        EntityRef::Face(
            FaceLabel {
                feature: FeatureId::default(),
                role: FaceRole::EndCap,
            },
            sample_face_fingerprint(),
        )
    }

    #[test]
    fn entity_ref_round_trips_all_kinds() {
        assert_ron_round_trip(&sample_face_ref());
        assert_ron_round_trip(&EntityRef::Edge(
            EdgeLabel {
                feature: FeatureId::default(),
                role: EdgeRole::EndCapEdge {
                    from: SketchEntityId::default(),
                },
            },
            EdgeFingerprint {
                sample: Point3::from_mm(1.0, 0.0, 0.0),
                direction: UnitVec3::z_axis(),
            },
        ));
        assert_ron_round_trip(&EntityRef::Vertex(
            VertexLabel {
                feature: FeatureId::default(),
                role: VertexRole::EndCapVertex {
                    from: SketchEntityId::default(),
                    side: SideKind::Corner,
                },
            },
            VertexFingerprint {
                point: Point3::origin(),
            },
        ));
    }

    #[test]
    fn face_ref_round_trips_and_projects_to_an_entity_ref() {
        let face = FaceRef::new(
            FaceLabel {
                feature: FeatureId::default(),
                role: FaceRole::EndCap,
            },
            sample_face_fingerprint(),
        );
        assert_ron_round_trip(&face);
        assert_eq!(face.entity_ref(), sample_face_ref());
    }

    #[test]
    fn entity_ref_fingerprint_projects_its_kind() {
        assert_eq!(
            sample_face_ref().fingerprint(),
            EntityFingerprint::Face(sample_face_fingerprint())
        );
    }

    #[test]
    fn entity_ref_display_shows_the_label() {
        let expected = format!("face[{:?}]:{}", FeatureId::default(), FaceRole::EndCap);
        assert_eq!(format!("{}", sample_face_ref()), expected);
    }

    #[test]
    fn fingerprint_rejects_unknown_field() {
        let Ok(text) = ron::to_string(&sample_face_fingerprint()) else {
            panic!("serialize face fingerprint");
        };
        assert!(ron::from_str::<FaceFingerprint>(&text).is_ok());
        let mut munged = text.clone();
        munged.insert_str(1, "bogus:42,");
        assert!(ron::from_str::<FaceFingerprint>(&munged).is_err());
    }

    #[test]
    fn match_score_rejects_out_of_range_and_non_finite() {
        assert!(MatchScore::new(0.0).is_ok());
        assert!(MatchScore::new(1.0).is_ok());
        assert!(MatchScore::new(0.75).is_ok());
        assert!(MatchScore::new(-0.1).is_err());
        assert!(MatchScore::new(1.5).is_err());
        assert!(MatchScore::new(f64::NAN).is_err());
        assert!(MatchScore::new(f64::INFINITY).is_err());
        assert!(ron::from_str::<MatchScore>("0.5").is_ok());
        assert!(ron::from_str::<MatchScore>("1.5").is_err());
        assert!(ron::from_str::<MatchScore>("-0.1").is_err());
        assert!(ron::from_str::<MatchScore>("inf").is_err());
        assert!(ron::from_str::<MatchScore>("NaN").is_err());
        let Ok(score) = MatchScore::new(0.5) else {
            panic!("0.5 is in range");
        };
        assert!((score.value() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn resolution_id_and_dangling() {
        let resolved: Resolution<FeatureId> = Resolution::Resolved(FeatureId::default());
        assert_eq!(resolved.id(), Some(FeatureId::default()));
        assert!(!resolved.is_dangling());
        assert_ron_round_trip(&resolved);

        let Ok(score) = MatchScore::new(0.9) else {
            panic!("0.9 is in range");
        };
        let repaired: Resolution<FeatureId> = Resolution::Repaired {
            id: FeatureId::default(),
            score,
        };
        assert_eq!(repaired.id(), Some(FeatureId::default()));

        let dangling: Resolution<FeatureId> = Resolution::Dangling {
            last_known: sample_face_ref(),
        };
        assert_eq!(dangling.id(), None);
        assert!(dangling.is_dangling());
        assert_ron_round_trip(&dangling);
        assert_ron_round_trip(&repaired);
    }

    #[test]
    fn resolution_repaired_rejects_unknown_field() {
        let Ok(score) = MatchScore::new(0.9) else {
            panic!("0.9 is in range");
        };
        let repaired: Resolution<FeatureId> = Resolution::Repaired {
            id: FeatureId::default(),
            score,
        };
        let Ok(text) = ron::to_string(&repaired) else {
            panic!("serialize repaired resolution");
        };
        assert!(ron::from_str::<Resolution<FeatureId>>(&text).is_ok());
        let Some(idx) = text.find("Repaired(") else {
            panic!("expected Repaired variant in {text}");
        };
        let mut munged = text.clone();
        munged.insert_str(idx + "Repaired(".len(), "bogus:42,");
        assert!(ron::from_str::<Resolution<FeatureId>>(&munged).is_err());
    }

    #[test]
    fn feature_generation_is_a_monotone_mark() {
        assert_eq!(FeatureGeneration::START, FeatureGeneration::default());
        assert_eq!(FeatureGeneration::START.value(), 0);
        let mark = FeatureGeneration::new(7);
        assert_eq!(mark.succ(), FeatureGeneration::new(8));
        assert!(mark < mark.succ());
        assert_eq!(mark.raised_to(FeatureGeneration::new(3)), mark);
        assert_eq!(
            mark.raised_to(FeatureGeneration::new(12)),
            FeatureGeneration::new(12)
        );
        let Ok(text) = ron::to_string(&mark) else {
            panic!("serialize feature generation");
        };
        assert_eq!(text, "7");
        assert_ron_round_trip(&mark);
        assert_eq!(
            FeatureGeneration::new(u64::MAX).succ(),
            FeatureGeneration::new(u64::MAX)
        );
    }

    #[test]
    fn rollback_marker_defaults_to_end() {
        assert_eq!(RollbackMarker::default(), RollbackMarker::AtEnd);
        assert_eq!(RollbackMarker::AtEnd.feature(), None);
        assert_eq!(
            RollbackMarker::Above(FeatureId::default()).feature(),
            Some(FeatureId::default())
        );
        assert!(RollbackMarker::AtEnd < RollbackMarker::Above(FeatureId::default()));
        assert_ron_round_trip(&RollbackMarker::AtEnd);
        assert_ron_round_trip(&RollbackMarker::Above(FeatureId::default()));
    }

    #[test]
    fn suppression_state_toggles() {
        assert_eq!(SuppressionState::default(), SuppressionState::Active);
        assert!(!SuppressionState::Active.is_suppressed());
        assert!(SuppressionState::Suppressed.is_suppressed());
        assert_eq!(
            SuppressionState::Active.toggled(),
            SuppressionState::Suppressed
        );
        assert_eq!(
            SuppressionState::Suppressed.toggled(),
            SuppressionState::Active
        );
        assert!(SuppressionState::Active < SuppressionState::Suppressed);
        assert_ron_round_trip(&SuppressionState::Active);
        assert_ron_round_trip(&SuppressionState::Suppressed);
    }

    #[test]
    fn rebuild_status_honors_warning_versus_error() {
        let dangling = RebuildStatus::Error(RebuildError::DanglingReference(sample_face_ref()));
        assert!(dangling.is_error());
        assert!(!dangling.builds_geometry());

        let non_planar = RebuildStatus::Error(RebuildError::NonPlanarSketchTarget);
        assert!(!non_planar.builds_geometry());

        let build_failed = RebuildStatus::Error(RebuildError::Build(BuildFailure::Kernel));
        assert!(build_failed.is_error());
        assert!(!build_failed.builds_geometry());

        let Ok(score) = MatchScore::new(0.8) else {
            panic!("0.8 is in range");
        };
        let repaired = RebuildStatus::Warning(RebuildWarning::RepairedReference {
            reference: sample_face_ref(),
            score,
        });
        assert!(!repaired.is_error());
        assert!(repaired.builds_geometry());

        assert!(RebuildStatus::UpToDate.builds_geometry());
        assert!(RebuildStatus::NeedsRebuild.builds_geometry());

        assert_eq!(dangling.worse_of(repaired), dangling);
        assert_eq!(repaired.worse_of(dangling), dangling);
        assert_eq!(repaired.worse_of(RebuildStatus::NeedsRebuild), repaired);
        assert_eq!(
            RebuildStatus::NeedsRebuild.worse_of(RebuildStatus::UpToDate),
            RebuildStatus::NeedsRebuild
        );
        assert_eq!(
            RebuildStatus::UpToDate.worse_of(RebuildStatus::UpToDate),
            RebuildStatus::UpToDate
        );

        assert_ron_round_trip(&dangling);
        assert_ron_round_trip(&non_planar);
        assert_ron_round_trip(&build_failed);
        assert_ron_round_trip(&RebuildStatus::Error(RebuildError::Build(
            BuildFailure::UnsolvedSketch,
        )));
        assert_ron_round_trip(&repaired);
        assert_ron_round_trip(&RebuildStatus::UpToDate);
        assert_ron_round_trip(&RebuildStatus::NeedsRebuild);
    }
}
