Skip to main content

kcl_lib/frontend/
trim.rs

1use std::f64::consts::TAU;
2
3use indexmap::IndexSet;
4use kittycad_modeling_cmds::units::UnitLength;
5
6use crate::execution::types::adjust_length;
7use crate::front::Horizontal;
8use crate::front::Vertical;
9use crate::frontend::api::Number;
10use crate::frontend::api::Object;
11use crate::frontend::api::ObjectId;
12use crate::frontend::api::ObjectKind;
13use crate::frontend::sketch::Constraint;
14use crate::frontend::sketch::ConstraintSegment;
15use crate::frontend::sketch::Segment;
16use crate::frontend::sketch::SegmentCtor;
17use crate::pretty::NumericSuffix;
18use crate::util::MathExt;
19
20#[cfg(test)]
21mod tests;
22
23// Epsilon constants for geometric calculations
24const EPSILON_PARALLEL: f64 = 1e-10;
25const EPSILON_POINT_ON_SEGMENT: f64 = 1e-6;
26const EPSILON_COINCIDENT_TERMINATION_SNAP: f64 = 5e-2;
27
28/// Length unit for a numeric suffix (length variants only). Non-length suffixes default to millimeters.
29fn suffix_to_unit(suffix: NumericSuffix) -> UnitLength {
30    match suffix {
31        NumericSuffix::Mm => UnitLength::Millimeters,
32        NumericSuffix::Cm => UnitLength::Centimeters,
33        NumericSuffix::M => UnitLength::Meters,
34        NumericSuffix::Inch => UnitLength::Inches,
35        NumericSuffix::Ft => UnitLength::Feet,
36        NumericSuffix::Yd => UnitLength::Yards,
37        _ => UnitLength::Millimeters,
38    }
39}
40
41/// Convert a length `Number` to f64 in the target unit. Use when normalizing geometry into a single unit.
42fn number_to_unit(n: &Number, target_unit: UnitLength) -> f64 {
43    adjust_length(suffix_to_unit(n.units), n.value, target_unit).0
44}
45
46/// Convert a length in the given unit to a `Number` in the target suffix.
47fn unit_to_number(value: f64, source_unit: UnitLength, target_suffix: NumericSuffix) -> Number {
48    let (value, _) = adjust_length(source_unit, value, suffix_to_unit(target_suffix));
49    Number {
50        value,
51        units: target_suffix,
52    }
53}
54
55/// Convert trim line points from millimeters into the current/default unit.
56fn normalize_trim_points_to_unit(points: &[Coords2d], default_unit: UnitLength) -> Vec<Coords2d> {
57    points
58        .iter()
59        .map(|point| Coords2d {
60            x: adjust_length(UnitLength::Millimeters, point.x, default_unit).0,
61            y: adjust_length(UnitLength::Millimeters, point.y, default_unit).0,
62        })
63        .collect()
64}
65
66/// 2D coordinates in the trim internal unit (current/default length unit).
67#[derive(Debug, Clone, Copy)]
68pub struct Coords2d {
69    pub x: f64,
70    pub y: f64,
71}
72
73/// Which endpoint of a line segment to get coordinates for
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum LineEndpoint {
76    Start,
77    End,
78}
79
80/// Which point of an arc segment to get coordinates for
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum ArcPoint {
83    Start,
84    End,
85    Center,
86}
87
88/// Which point of a circle segment to get coordinates for
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum CirclePoint {
91    Start,
92    Center,
93}
94
95/// Direction along a segment for finding trim terminations
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum TrimDirection {
98    Left,
99    Right,
100}
101
102// Manual serde implementation for Coords2d to serialize as [x, y] array
103// This matches TypeScript's Coords2d type which is [number, number]
104
105// A trim spawn is the intersection point of the trim line (drawn by the user) and a segment.
106// We travel in both directions along the segment from the trim spawn to determine how to implement the trim.
107
108/// Item from advancing to the next trim spawn (intersection), like an iterator item from `Iterator::next()`.
109#[derive(Debug, Clone)]
110pub enum TrimItem {
111    Spawn {
112        trim_spawn_seg_id: ObjectId,
113        trim_spawn_coords: Coords2d,
114        next_index: usize,
115    },
116    None {
117        next_index: usize,
118    },
119}
120
121/// Trim termination types
122///
123/// Trim termination is the term used to figure out each end of a segment after a trim spawn has been found.
124/// When a trim spawn is found, we travel in both directions to find this termination. It can be:
125/// (1) the end of a segment (floating end), (2) an intersection with another segment, or
126/// (3) a coincident point where another segment is coincident with the segment we're traveling along.
127#[derive(Debug, Clone)]
128pub enum TrimTermination {
129    SegEndPoint {
130        trim_termination_coords: Coords2d,
131    },
132    Intersection {
133        trim_termination_coords: Coords2d,
134        intersecting_seg_id: ObjectId,
135    },
136    TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
137        trim_termination_coords: Coords2d,
138        intersecting_seg_id: ObjectId,
139        other_segment_point_id: ObjectId,
140    },
141}
142
143/// Trim terminations for both sides
144#[derive(Debug, Clone)]
145pub struct TrimTerminations {
146    pub left_side: TrimTermination,
147    pub right_side: TrimTermination,
148}
149
150/// Specifies where a constraint should attach when migrating during split operations
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub enum AttachToEndpoint {
153    Start,
154    End,
155    Segment,
156}
157
158/// Specifies which endpoint of a segment was changed
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum EndpointChanged {
161    Start,
162    End,
163}
164
165/// Coincident data for split segment operations
166#[derive(Debug, Clone)]
167pub struct CoincidentData {
168    pub intersecting_seg_id: ObjectId,
169    pub intersecting_endpoint_point_id: Option<ObjectId>,
170    pub existing_point_segment_constraint_id: Option<ObjectId>,
171}
172
173/// Constraint to migrate during split operations
174#[derive(Debug, Clone)]
175pub struct ConstraintToMigrate {
176    pub constraint_id: ObjectId,
177    pub other_entity_id: ObjectId,
178    /// True if the coincident constraint is between two points (point–point).
179    /// False if it is between a point and a line/arc/segment (point-segment coincident).
180    pub is_point_point: bool,
181    pub attach_to_endpoint: AttachToEndpoint,
182}
183
184/// Semantic trim plan produced by analysis/planning before lowering to frontend operations.
185#[derive(Debug, Clone)]
186pub enum TrimPlan {
187    DeleteSegment {
188        segment_id: ObjectId,
189    },
190    TailCut {
191        segment_id: ObjectId,
192        endpoint_changed: EndpointChanged,
193        ctor: SegmentCtor,
194        segment_or_point_to_make_coincident_to: ObjectId,
195        intersecting_endpoint_point_id: Option<ObjectId>,
196        constraint_ids_to_delete: Vec<ObjectId>,
197        additional_edited_segment_ids: Vec<ObjectId>,
198    },
199    ReplaceCircleWithArc {
200        circle_id: ObjectId,
201        arc_start_coords: Coords2d,
202        arc_end_coords: Coords2d,
203        arc_start_termination: Box<TrimTermination>,
204        arc_end_termination: Box<TrimTermination>,
205    },
206    SplitSegment {
207        segment_id: ObjectId,
208        left_trim_coords: Coords2d,
209        right_trim_coords: Coords2d,
210        original_end_coords: Coords2d,
211        left_side: Box<TrimTermination>,
212        right_side: Box<TrimTermination>,
213        left_side_coincident_data: CoincidentData,
214        right_side_coincident_data: CoincidentData,
215        constraints_to_migrate: Vec<ConstraintToMigrate>,
216        constraints_to_delete: Vec<ObjectId>,
217    },
218}
219
220fn lower_trim_plan(plan: &TrimPlan) -> Vec<TrimOperation> {
221    match plan {
222        TrimPlan::DeleteSegment { segment_id } => vec![TrimOperation::SimpleTrim {
223            segment_to_trim_id: *segment_id,
224        }],
225        TrimPlan::TailCut {
226            segment_id,
227            endpoint_changed,
228            ctor,
229            segment_or_point_to_make_coincident_to,
230            intersecting_endpoint_point_id,
231            constraint_ids_to_delete,
232            additional_edited_segment_ids,
233        } => {
234            let mut ops = vec![
235                TrimOperation::EditSegment {
236                    segment_id: *segment_id,
237                    ctor: ctor.clone(),
238                    endpoint_changed: *endpoint_changed,
239                    additional_edited_segment_ids: additional_edited_segment_ids.clone(),
240                },
241                TrimOperation::AddCoincidentConstraint {
242                    segment_id: *segment_id,
243                    endpoint_changed: *endpoint_changed,
244                    segment_or_point_to_make_coincident_to: *segment_or_point_to_make_coincident_to,
245                    intersecting_endpoint_point_id: *intersecting_endpoint_point_id,
246                },
247            ];
248            if !constraint_ids_to_delete.is_empty() {
249                ops.push(TrimOperation::DeleteConstraints {
250                    constraint_ids: constraint_ids_to_delete.clone(),
251                });
252            }
253            ops
254        }
255        TrimPlan::ReplaceCircleWithArc {
256            circle_id,
257            arc_start_coords,
258            arc_end_coords,
259            arc_start_termination,
260            arc_end_termination,
261        } => vec![TrimOperation::ReplaceCircleWithArc {
262            circle_id: *circle_id,
263            arc_start_coords: *arc_start_coords,
264            arc_end_coords: *arc_end_coords,
265            arc_start_termination: arc_start_termination.clone(),
266            arc_end_termination: arc_end_termination.clone(),
267        }],
268        TrimPlan::SplitSegment {
269            segment_id,
270            left_trim_coords,
271            right_trim_coords,
272            original_end_coords,
273            left_side,
274            right_side,
275            left_side_coincident_data,
276            right_side_coincident_data,
277            constraints_to_migrate,
278            constraints_to_delete,
279        } => vec![TrimOperation::SplitSegment {
280            segment_id: *segment_id,
281            left_trim_coords: *left_trim_coords,
282            right_trim_coords: *right_trim_coords,
283            original_end_coords: *original_end_coords,
284            left_side: left_side.clone(),
285            right_side: right_side.clone(),
286            left_side_coincident_data: left_side_coincident_data.clone(),
287            right_side_coincident_data: right_side_coincident_data.clone(),
288            constraints_to_migrate: constraints_to_migrate.clone(),
289            constraints_to_delete: constraints_to_delete.clone(),
290        }],
291    }
292}
293
294fn trim_plan_modifies_geometry(plan: &TrimPlan) -> bool {
295    matches!(
296        plan,
297        TrimPlan::DeleteSegment { .. }
298            | TrimPlan::TailCut { .. }
299            | TrimPlan::ReplaceCircleWithArc { .. }
300            | TrimPlan::SplitSegment { .. }
301    )
302}
303
304fn rewrite_object_id(id: ObjectId, rewrite_map: &std::collections::HashMap<ObjectId, ObjectId>) -> ObjectId {
305    rewrite_map.get(&id).copied().unwrap_or(id)
306}
307
308fn rewrite_constraint_segment(
309    segment: crate::frontend::sketch::ConstraintSegment,
310    rewrite_map: &std::collections::HashMap<ObjectId, ObjectId>,
311) -> crate::frontend::sketch::ConstraintSegment {
312    match segment {
313        crate::frontend::sketch::ConstraintSegment::Segment(id) => {
314            crate::frontend::sketch::ConstraintSegment::Segment(rewrite_object_id(id, rewrite_map))
315        }
316        crate::frontend::sketch::ConstraintSegment::Origin(origin) => {
317            crate::frontend::sketch::ConstraintSegment::Origin(origin)
318        }
319    }
320}
321
322fn rewrite_constraint_segments(
323    segments: &[crate::frontend::sketch::ConstraintSegment],
324    rewrite_map: &std::collections::HashMap<ObjectId, ObjectId>,
325) -> Vec<crate::frontend::sketch::ConstraintSegment> {
326    segments
327        .iter()
328        .copied()
329        .map(|segment| rewrite_constraint_segment(segment, rewrite_map))
330        .collect()
331}
332
333fn constraint_segments_reference_any(
334    segments: &[crate::frontend::sketch::ConstraintSegment],
335    ids: &std::collections::HashSet<ObjectId>,
336) -> bool {
337    segments.iter().any(|segment| match segment {
338        crate::frontend::sketch::ConstraintSegment::Segment(id) => ids.contains(id),
339        crate::frontend::sketch::ConstraintSegment::Origin(_) => false,
340    })
341}
342
343fn rewrite_constraint_with_map(
344    constraint: &Constraint,
345    rewrite_map: &std::collections::HashMap<ObjectId, ObjectId>,
346) -> Option<Constraint> {
347    // Keep trim constraint matches exhaustive. New constraints can break trim in
348    // unexpected ways; try trimming sketches that use the new constraint and ask
349    // Kurt, Max, or a mechanical engineer when the expected behavior is unclear.
350    match constraint {
351        Constraint::Coincident(coincident) => Some(Constraint::Coincident(crate::frontend::sketch::Coincident {
352            segments: rewrite_constraint_segments(&coincident.segments, rewrite_map),
353        })),
354        Constraint::Distance(distance) => Some(Constraint::Distance(crate::frontend::sketch::Distance {
355            points: rewrite_constraint_segments(&distance.points, rewrite_map),
356            distance: distance.distance,
357            label_position: distance.label_position.clone(),
358            source: distance.source.clone(),
359        })),
360        Constraint::HorizontalDistance(distance) => {
361            Some(Constraint::HorizontalDistance(crate::frontend::sketch::Distance {
362                points: rewrite_constraint_segments(&distance.points, rewrite_map),
363                distance: distance.distance,
364                label_position: distance.label_position.clone(),
365                source: distance.source.clone(),
366            }))
367        }
368        Constraint::VerticalDistance(distance) => {
369            Some(Constraint::VerticalDistance(crate::frontend::sketch::Distance {
370                points: rewrite_constraint_segments(&distance.points, rewrite_map),
371                distance: distance.distance,
372                label_position: distance.label_position.clone(),
373                source: distance.source.clone(),
374            }))
375        }
376        Constraint::Radius(radius) => Some(Constraint::Radius(crate::frontend::sketch::Radius {
377            arc: rewrite_object_id(radius.arc, rewrite_map),
378            radius: radius.radius,
379            label_position: radius.label_position.clone(),
380            source: radius.source.clone(),
381        })),
382        Constraint::Diameter(diameter) => Some(Constraint::Diameter(crate::frontend::sketch::Diameter {
383            arc: rewrite_object_id(diameter.arc, rewrite_map),
384            diameter: diameter.diameter,
385            label_position: diameter.label_position.clone(),
386            source: diameter.source.clone(),
387        })),
388        Constraint::EqualRadius(equal_radius) => Some(Constraint::EqualRadius(crate::frontend::sketch::EqualRadius {
389            input: equal_radius
390                .input
391                .iter()
392                .map(|id| rewrite_object_id(*id, rewrite_map))
393                .collect(),
394        })),
395        Constraint::Midpoint(midpoint) => Some(Constraint::Midpoint(crate::frontend::sketch::Midpoint {
396            point: rewrite_object_id(midpoint.point, rewrite_map),
397            segment: rewrite_object_id(midpoint.segment, rewrite_map),
398        })),
399        Constraint::Tangent(tangent) => Some(Constraint::Tangent(crate::frontend::sketch::Tangent {
400            input: tangent
401                .input
402                .iter()
403                .map(|id| rewrite_object_id(*id, rewrite_map))
404                .collect(),
405        })),
406        Constraint::Symmetric(symmetric) => Some(Constraint::Symmetric(crate::frontend::sketch::Symmetric {
407            input: symmetric
408                .input
409                .iter()
410                .map(|id| rewrite_object_id(*id, rewrite_map))
411                .collect(),
412            axis: rewrite_object_id(symmetric.axis, rewrite_map),
413        })),
414        Constraint::Parallel(parallel) => Some(Constraint::Parallel(crate::frontend::sketch::Parallel {
415            lines: parallel
416                .lines
417                .iter()
418                .map(|id| rewrite_object_id(*id, rewrite_map))
419                .collect(),
420        })),
421        Constraint::Perpendicular(perpendicular) => {
422            Some(Constraint::Perpendicular(crate::frontend::sketch::Perpendicular {
423                lines: perpendicular
424                    .lines
425                    .iter()
426                    .map(|id| rewrite_object_id(*id, rewrite_map))
427                    .collect(),
428            }))
429        }
430        Constraint::Horizontal(horizontal) => match horizontal {
431            crate::front::Horizontal::Line { line } => {
432                Some(Constraint::Horizontal(crate::frontend::sketch::Horizontal::Line {
433                    line: rewrite_object_id(*line, rewrite_map),
434                }))
435            }
436            crate::front::Horizontal::Points { points } => Some(Constraint::Horizontal(Horizontal::Points {
437                points: points
438                    .iter()
439                    .map(|point| match point {
440                        crate::frontend::sketch::ConstraintSegment::Segment(point) => {
441                            crate::frontend::sketch::ConstraintSegment::from(rewrite_object_id(*point, rewrite_map))
442                        }
443                        crate::frontend::sketch::ConstraintSegment::Origin(origin) => {
444                            crate::frontend::sketch::ConstraintSegment::Origin(*origin)
445                        }
446                    })
447                    .collect(),
448            })),
449        },
450        Constraint::Vertical(vertical) => match vertical {
451            crate::front::Vertical::Line { line } => {
452                Some(Constraint::Vertical(crate::frontend::sketch::Vertical::Line {
453                    line: rewrite_object_id(*line, rewrite_map),
454                }))
455            }
456            crate::front::Vertical::Points { points } => Some(Constraint::Vertical(Vertical::Points {
457                points: points
458                    .iter()
459                    .map(|point| match point {
460                        crate::frontend::sketch::ConstraintSegment::Segment(point) => {
461                            crate::frontend::sketch::ConstraintSegment::from(rewrite_object_id(*point, rewrite_map))
462                        }
463                        crate::frontend::sketch::ConstraintSegment::Origin(origin) => {
464                            crate::frontend::sketch::ConstraintSegment::Origin(*origin)
465                        }
466                    })
467                    .collect(),
468            })),
469        },
470        Constraint::Angle(_) | Constraint::Fixed(_) | Constraint::LinesEqualLength(_) => None,
471    }
472}
473
474fn point_axis_constraint_references_point(constraint: &Constraint, point_id: ObjectId) -> bool {
475    // Keep trim constraint matches exhaustive. New constraints should make an
476    // explicit preserve/delete/migrate decision rather than falling through.
477    match constraint {
478        Constraint::Horizontal(Horizontal::Points { points }) => points.contains(&ConstraintSegment::from(point_id)),
479        Constraint::Vertical(Vertical::Points { points }) => points.contains(&ConstraintSegment::from(point_id)),
480        Constraint::Angle(_)
481        | Constraint::Coincident(_)
482        | Constraint::Diameter(_)
483        | Constraint::Distance(_)
484        | Constraint::EqualRadius(_)
485        | Constraint::Fixed(_)
486        | Constraint::Horizontal(Horizontal::Line { .. })
487        | Constraint::HorizontalDistance(_)
488        | Constraint::LinesEqualLength(_)
489        | Constraint::Midpoint(_)
490        | Constraint::Parallel(_)
491        | Constraint::Perpendicular(_)
492        | Constraint::Radius(_)
493        | Constraint::Symmetric(_)
494        | Constraint::Tangent(_)
495        | Constraint::Vertical(Vertical::Line { .. })
496        | Constraint::VerticalDistance(_) => false,
497    }
498}
499
500fn owner_or_segment_id(objects: &[Object], segment_id: ObjectId) -> ObjectId {
501    if let Some(segment_object) = objects.iter().find(|obj| obj.id == segment_id)
502        && let ObjectKind::Segment {
503            segment: Segment::Point(point),
504        } = &segment_object.kind
505        && let Some(owner_id) = point.owner
506    {
507        owner_id
508    } else {
509        segment_id
510    }
511}
512
513fn segment_id_is_or_is_owned_by_curve(objects: &[Object], segment_id: ObjectId) -> bool {
514    objects.iter().find(|obj| obj.id == segment_id).is_some_and(|object| {
515        let ObjectKind::Segment { segment } = &object.kind else {
516            return false;
517        };
518
519        match segment {
520            Segment::Arc(_) | Segment::Circle(_) => true,
521            Segment::Point(point) => point.owner.is_some_and(|owner_id| {
522                objects.iter().find(|obj| obj.id == owner_id).is_some_and(|owner| {
523                    matches!(
524                        owner.kind,
525                        ObjectKind::Segment {
526                            segment: Segment::Arc(_) | Segment::Circle(_)
527                        }
528                    )
529                })
530            }),
531            _ => false,
532        }
533    })
534}
535
536fn sketch_segment_ids_for_segment(objects: &[Object], segment_id: ObjectId) -> Vec<ObjectId> {
537    objects
538        .iter()
539        .find_map(|obj| {
540            let ObjectKind::Sketch(sketch) = &obj.kind else {
541                return None;
542            };
543
544            sketch.segments.contains(&segment_id).then(|| sketch.segments.clone())
545        })
546        .unwrap_or_default()
547}
548
549#[derive(Debug, Clone)]
550#[allow(clippy::large_enum_variant)]
551pub enum TrimOperation {
552    SimpleTrim {
553        segment_to_trim_id: ObjectId,
554    },
555    EditSegment {
556        segment_id: ObjectId,
557        ctor: SegmentCtor,
558        endpoint_changed: EndpointChanged,
559        additional_edited_segment_ids: Vec<ObjectId>,
560    },
561    AddCoincidentConstraint {
562        segment_id: ObjectId,
563        endpoint_changed: EndpointChanged,
564        segment_or_point_to_make_coincident_to: ObjectId,
565        intersecting_endpoint_point_id: Option<ObjectId>,
566    },
567    SplitSegment {
568        segment_id: ObjectId,
569        left_trim_coords: Coords2d,
570        right_trim_coords: Coords2d,
571        original_end_coords: Coords2d,
572        left_side: Box<TrimTermination>,
573        right_side: Box<TrimTermination>,
574        left_side_coincident_data: CoincidentData,
575        right_side_coincident_data: CoincidentData,
576        constraints_to_migrate: Vec<ConstraintToMigrate>,
577        constraints_to_delete: Vec<ObjectId>,
578    },
579    ReplaceCircleWithArc {
580        circle_id: ObjectId,
581        arc_start_coords: Coords2d,
582        arc_end_coords: Coords2d,
583        arc_start_termination: Box<TrimTermination>,
584        arc_end_termination: Box<TrimTermination>,
585    },
586    DeleteConstraints {
587        constraint_ids: Vec<ObjectId>,
588    },
589}
590
591/// Helper to check if a point is on a line segment (within epsilon distance)
592///
593/// Returns the point if it's on the segment, None otherwise.
594pub fn is_point_on_line_segment(
595    point: Coords2d,
596    segment_start: Coords2d,
597    segment_end: Coords2d,
598    epsilon: f64,
599) -> Option<Coords2d> {
600    let dx = segment_end.x - segment_start.x;
601    let dy = segment_end.y - segment_start.y;
602    let segment_length_sq = dx * dx + dy * dy;
603
604    if segment_length_sq < EPSILON_PARALLEL {
605        // Segment is degenerate, i.e it's practically a point
606        let dist_sq = (point.x - segment_start.x) * (point.x - segment_start.x)
607            + (point.y - segment_start.y) * (point.y - segment_start.y);
608        if dist_sq <= epsilon * epsilon {
609            return Some(point);
610        }
611        return None;
612    }
613
614    let point_dx = point.x - segment_start.x;
615    let point_dy = point.y - segment_start.y;
616    let projection_param = (point_dx * dx + point_dy * dy) / segment_length_sq;
617
618    // Check if point projects onto the segment
619    if !(0.0..=1.0).contains(&projection_param) {
620        return None;
621    }
622
623    // Calculate the projected point on the segment
624    let projected_point = Coords2d {
625        x: segment_start.x + projection_param * dx,
626        y: segment_start.y + projection_param * dy,
627    };
628
629    // Check if the distance from point to projected point is within epsilon
630    let dist_dx = point.x - projected_point.x;
631    let dist_dy = point.y - projected_point.y;
632    let distance_sq = dist_dx * dist_dx + dist_dy * dist_dy;
633
634    if distance_sq <= epsilon * epsilon {
635        Some(point)
636    } else {
637        None
638    }
639}
640
641/// Helper to calculate intersection point of two line segments
642///
643/// Returns the intersection point if segments intersect, None otherwise.
644pub fn line_segment_intersection(
645    line1_start: Coords2d,
646    line1_end: Coords2d,
647    line2_start: Coords2d,
648    line2_end: Coords2d,
649    epsilon: f64,
650) -> Option<Coords2d> {
651    // First check if any endpoints are on the other segment
652    if let Some(point) = is_point_on_line_segment(line1_start, line2_start, line2_end, epsilon) {
653        return Some(point);
654    }
655
656    if let Some(point) = is_point_on_line_segment(line1_end, line2_start, line2_end, epsilon) {
657        return Some(point);
658    }
659
660    if let Some(point) = is_point_on_line_segment(line2_start, line1_start, line1_end, epsilon) {
661        return Some(point);
662    }
663
664    if let Some(point) = is_point_on_line_segment(line2_end, line1_start, line1_end, epsilon) {
665        return Some(point);
666    }
667
668    // Then check for actual line segment intersection
669    let x1 = line1_start.x;
670    let y1 = line1_start.y;
671    let x2 = line1_end.x;
672    let y2 = line1_end.y;
673    let x3 = line2_start.x;
674    let y3 = line2_start.y;
675    let x4 = line2_end.x;
676    let y4 = line2_end.y;
677
678    let denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
679    if denominator.abs() < EPSILON_PARALLEL {
680        // Lines are parallel
681        return None;
682    }
683
684    let t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denominator;
685    let u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / denominator;
686
687    // Check if intersection is within both segments
688    if (0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u) {
689        let x = x1 + t * (x2 - x1);
690        let y = y1 + t * (y2 - y1);
691        return Some(Coords2d { x, y });
692    }
693
694    None
695}
696
697/// Helper to calculate the parametric position of a point on a line segment
698///
699/// Returns t where t=0 at segmentStart, t=1 at segmentEnd.
700/// t can be < 0 or > 1 if the point projects outside the segment.
701pub fn project_point_onto_segment(point: Coords2d, segment_start: Coords2d, segment_end: Coords2d) -> f64 {
702    let dx = segment_end.x - segment_start.x;
703    let dy = segment_end.y - segment_start.y;
704    let segment_length_sq = dx * dx + dy * dy;
705
706    if segment_length_sq < EPSILON_PARALLEL {
707        // Segment is degenerate
708        return 0.0;
709    }
710
711    let point_dx = point.x - segment_start.x;
712    let point_dy = point.y - segment_start.y;
713
714    (point_dx * dx + point_dy * dy) / segment_length_sq
715}
716
717/// Helper to calculate the perpendicular distance from a point to a line segment
718///
719/// Returns the distance from the point to the closest point on the segment.
720pub fn perpendicular_distance_to_segment(point: Coords2d, segment_start: Coords2d, segment_end: Coords2d) -> f64 {
721    let dx = segment_end.x - segment_start.x;
722    let dy = segment_end.y - segment_start.y;
723    let segment_length_sq = dx * dx + dy * dy;
724
725    if segment_length_sq < EPSILON_PARALLEL {
726        // Segment is degenerate, return distance to point
727        let dist_dx = point.x - segment_start.x;
728        let dist_dy = point.y - segment_start.y;
729        return (dist_dx * dist_dx + dist_dy * dist_dy).sqrt();
730    }
731
732    // Vector from segment start to point
733    let point_dx = point.x - segment_start.x;
734    let point_dy = point.y - segment_start.y;
735
736    // Project point onto segment
737    let t = (point_dx * dx + point_dy * dy) / segment_length_sq;
738
739    // Clamp t to [0, 1] to get closest point on segment
740    let clamped_t = t.clamp(0.0, 1.0);
741    let closest_point = Coords2d {
742        x: segment_start.x + clamped_t * dx,
743        y: segment_start.y + clamped_t * dy,
744    };
745
746    // Calculate distance
747    let dist_dx = point.x - closest_point.x;
748    let dist_dy = point.y - closest_point.y;
749    (dist_dx * dist_dx + dist_dy * dist_dy).sqrt()
750}
751
752/// Helper to check if a point is on an arc segment (CCW from start to end)
753///
754/// Returns true if the point is on the arc, false otherwise.
755pub fn is_point_on_arc(point: Coords2d, center: Coords2d, start: Coords2d, end: Coords2d, epsilon: f64) -> bool {
756    // Calculate radius
757    let radius = ((start.x - center.x) * (start.x - center.x) + (start.y - center.y) * (start.y - center.y)).sqrt();
758
759    // Check if point is on the circle (within epsilon)
760    let dist_from_center =
761        ((point.x - center.x) * (point.x - center.x) + (point.y - center.y) * (point.y - center.y)).sqrt();
762    if (dist_from_center - radius).abs() > epsilon {
763        return false;
764    }
765
766    // Calculate angles
767    let start_angle = libm::atan2(start.y - center.y, start.x - center.x);
768    let end_angle = libm::atan2(end.y - center.y, end.x - center.x);
769    let point_angle = libm::atan2(point.y - center.y, point.x - center.x);
770
771    // Normalize angles to [0, 2Ï€]
772    let normalize_angle = |angle: f64| -> f64 {
773        if !angle.is_finite() {
774            return angle;
775        }
776        let mut normalized = angle;
777        while normalized < 0.0 {
778            normalized += TAU;
779        }
780        while normalized >= TAU {
781            normalized -= TAU;
782        }
783        normalized
784    };
785
786    let normalized_start = normalize_angle(start_angle);
787    let normalized_end = normalize_angle(end_angle);
788    let normalized_point = normalize_angle(point_angle);
789
790    // Check if point is on the arc going CCW from start to end
791    // Since arcs always travel CCW, we need to check if the point angle
792    // is between start and end when going CCW
793    if normalized_start < normalized_end {
794        // No wrap around
795        normalized_point >= normalized_start && normalized_point <= normalized_end
796    } else {
797        // Wrap around (e.g., start at 350°, end at 10°)
798        normalized_point >= normalized_start || normalized_point <= normalized_end
799    }
800}
801
802/// Helper to calculate intersections between a line segment and an arc.
803///
804/// Returns intersections sorted by the line segment parametric position.
805pub fn line_arc_intersections(
806    line_start: Coords2d,
807    line_end: Coords2d,
808    arc_center: Coords2d,
809    arc_start: Coords2d,
810    arc_end: Coords2d,
811    epsilon: f64,
812) -> Vec<(f64, Coords2d)> {
813    // Calculate radius
814    let radius = ((arc_start.x - arc_center.x) * (arc_start.x - arc_center.x)
815        + (arc_start.y - arc_center.y) * (arc_start.y - arc_center.y))
816        .sqrt();
817
818    // Translate line to origin (center at 0,0)
819    let translated_line_start = Coords2d {
820        x: line_start.x - arc_center.x,
821        y: line_start.y - arc_center.y,
822    };
823    let translated_line_end = Coords2d {
824        x: line_end.x - arc_center.x,
825        y: line_end.y - arc_center.y,
826    };
827
828    // Line equation: p = lineStart + t * (lineEnd - lineStart)
829    let dx = translated_line_end.x - translated_line_start.x;
830    let dy = translated_line_end.y - translated_line_start.y;
831
832    // Circle equation: x² + y² = r²
833    // Substitute line equation into circle equation
834    // (x0 + t*dx)² + (y0 + t*dy)² = r²
835    // Expand: x0² + 2*x0*t*dx + t²*dx² + y0² + 2*y0*t*dy + t²*dy² = r²
836    // Rearrange: t²*(dx² + dy²) + 2*t*(x0*dx + y0*dy) + (x0² + y0² - r²) = 0
837
838    let a = dx * dx + dy * dy;
839    let b = 2.0 * (translated_line_start.x * dx + translated_line_start.y * dy);
840    let c = translated_line_start.x * translated_line_start.x + translated_line_start.y * translated_line_start.y
841        - radius * radius;
842
843    let discriminant = b * b - 4.0 * a * c;
844
845    if discriminant < 0.0 {
846        // No intersection
847        return Vec::new();
848    }
849
850    if a.abs() < EPSILON_PARALLEL {
851        // Line segment is degenerate
852        let dist_from_center = (translated_line_start.x * translated_line_start.x
853            + translated_line_start.y * translated_line_start.y)
854            .sqrt();
855        if (dist_from_center - radius).abs() <= epsilon {
856            // Point is on circle, check if it's on the arc
857            let point = line_start;
858            if is_point_on_arc(point, arc_center, arc_start, arc_end, epsilon) {
859                return vec![(0.0, point)];
860            }
861        }
862        return Vec::new();
863    }
864
865    let sqrt_discriminant = discriminant.sqrt();
866    let t1 = (-b - sqrt_discriminant) / (2.0 * a);
867    let t2 = (-b + sqrt_discriminant) / (2.0 * a);
868
869    // Check both intersection points
870    let mut candidates: Vec<(f64, Coords2d)> = Vec::new();
871    if (0.0..=1.0).contains(&t1) {
872        let point = Coords2d {
873            x: line_start.x + t1 * (line_end.x - line_start.x),
874            y: line_start.y + t1 * (line_end.y - line_start.y),
875        };
876        candidates.push((t1, point));
877    }
878    if (0.0..=1.0).contains(&t2) && (t2 - t1).abs() > epsilon {
879        let point = Coords2d {
880            x: line_start.x + t2 * (line_end.x - line_start.x),
881            y: line_start.y + t2 * (line_end.y - line_start.y),
882        };
883        candidates.push((t2, point));
884    }
885
886    candidates.retain(|(_, point)| is_point_on_arc(*point, arc_center, arc_start, arc_end, epsilon));
887    candidates.sort_by(|(a_t, _), (b_t, _)| a_t.partial_cmp(b_t).unwrap_or(std::cmp::Ordering::Equal));
888    candidates
889}
890
891/// Helper to calculate intersection between a line segment and an arc.
892///
893/// Returns the first intersection point if found, None otherwise.
894pub fn line_arc_intersection(
895    line_start: Coords2d,
896    line_end: Coords2d,
897    arc_center: Coords2d,
898    arc_start: Coords2d,
899    arc_end: Coords2d,
900    epsilon: f64,
901) -> Option<Coords2d> {
902    line_arc_intersections(line_start, line_end, arc_center, arc_start, arc_end, epsilon)
903        .into_iter()
904        .map(|(_, point)| point)
905        .next()
906}
907
908/// Helper to calculate intersection points between a line segment and a circle.
909///
910/// Returns intersections as `(t, point)` where `t` is the line parametric position:
911/// `point = line_start + t * (line_end - line_start)`, with `0 <= t <= 1`.
912pub fn line_circle_intersections(
913    line_start: Coords2d,
914    line_end: Coords2d,
915    circle_center: Coords2d,
916    radius: f64,
917    epsilon: f64,
918) -> Vec<(f64, Coords2d)> {
919    // Translate line to origin (center at 0,0)
920    let translated_line_start = Coords2d {
921        x: line_start.x - circle_center.x,
922        y: line_start.y - circle_center.y,
923    };
924    let translated_line_end = Coords2d {
925        x: line_end.x - circle_center.x,
926        y: line_end.y - circle_center.y,
927    };
928
929    let dx = translated_line_end.x - translated_line_start.x;
930    let dy = translated_line_end.y - translated_line_start.y;
931    let a = dx * dx + dy * dy;
932    let b = 2.0 * (translated_line_start.x * dx + translated_line_start.y * dy);
933    let c = translated_line_start.x * translated_line_start.x + translated_line_start.y * translated_line_start.y
934        - radius * radius;
935
936    if a.abs() < EPSILON_PARALLEL {
937        return Vec::new();
938    }
939
940    let discriminant = b * b - 4.0 * a * c;
941    if discriminant < 0.0 {
942        return Vec::new();
943    }
944
945    let sqrt_discriminant = discriminant.sqrt();
946    let mut intersections = Vec::new();
947
948    let t1 = (-b - sqrt_discriminant) / (2.0 * a);
949    if (0.0..=1.0).contains(&t1) {
950        intersections.push((
951            t1,
952            Coords2d {
953                x: line_start.x + t1 * (line_end.x - line_start.x),
954                y: line_start.y + t1 * (line_end.y - line_start.y),
955            },
956        ));
957    }
958
959    let t2 = (-b + sqrt_discriminant) / (2.0 * a);
960    if (0.0..=1.0).contains(&t2) && (t2 - t1).abs() > epsilon {
961        intersections.push((
962            t2,
963            Coords2d {
964                x: line_start.x + t2 * (line_end.x - line_start.x),
965                y: line_start.y + t2 * (line_end.y - line_start.y),
966            },
967        ));
968    }
969
970    intersections.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
971    intersections
972}
973
974/// Parametric position of a point on a circle, measured CCW from the circle start point.
975///
976/// Returns `t` in `[0, 1)` where:
977/// - `t = 0` at circle start
978/// - increasing `t` moves CCW
979pub fn project_point_onto_circle(point: Coords2d, center: Coords2d, start: Coords2d) -> f64 {
980    let normalize_angle = |angle: f64| -> f64 {
981        if !angle.is_finite() {
982            return angle;
983        }
984        let mut normalized = angle;
985        while normalized < 0.0 {
986            normalized += TAU;
987        }
988        while normalized >= TAU {
989            normalized -= TAU;
990        }
991        normalized
992    };
993
994    let start_angle = normalize_angle(libm::atan2(start.y - center.y, start.x - center.x));
995    let point_angle = normalize_angle(libm::atan2(point.y - center.y, point.x - center.x));
996    let delta_ccw = (point_angle - start_angle).rem_euclid(TAU);
997    delta_ccw / TAU
998}
999
1000fn is_point_on_circle(point: Coords2d, center: Coords2d, radius: f64, epsilon: f64) -> bool {
1001    let dist = ((point.x - center.x) * (point.x - center.x) + (point.y - center.y) * (point.y - center.y)).sqrt();
1002    (dist - radius).abs() <= epsilon
1003}
1004
1005/// Helper to calculate the parametric position of a point on an arc
1006/// Returns t where t=0 at start, t=1 at end, based on CCW angle
1007pub fn project_point_onto_arc(point: Coords2d, arc_center: Coords2d, arc_start: Coords2d, arc_end: Coords2d) -> f64 {
1008    // Calculate angles
1009    let start_angle = libm::atan2(arc_start.y - arc_center.y, arc_start.x - arc_center.x);
1010    let end_angle = libm::atan2(arc_end.y - arc_center.y, arc_end.x - arc_center.x);
1011    let point_angle = libm::atan2(point.y - arc_center.y, point.x - arc_center.x);
1012
1013    // Normalize angles to [0, 2Ï€]
1014    let normalize_angle = |angle: f64| -> f64 {
1015        if !angle.is_finite() {
1016            return angle;
1017        }
1018        let mut normalized = angle;
1019        while normalized < 0.0 {
1020            normalized += TAU;
1021        }
1022        while normalized >= TAU {
1023            normalized -= TAU;
1024        }
1025        normalized
1026    };
1027
1028    let normalized_start = normalize_angle(start_angle);
1029    let normalized_end = normalize_angle(end_angle);
1030    let normalized_point = normalize_angle(point_angle);
1031
1032    // Calculate arc length (CCW)
1033    let arc_length = if normalized_start < normalized_end {
1034        normalized_end - normalized_start
1035    } else {
1036        // Wrap around
1037        TAU - normalized_start + normalized_end
1038    };
1039
1040    if arc_length < EPSILON_PARALLEL {
1041        // Arc is degenerate (full circle or very small)
1042        return 0.0;
1043    }
1044
1045    // Calculate point's position along arc (CCW from start)
1046    let point_arc_length = if normalized_start < normalized_end {
1047        if normalized_point >= normalized_start && normalized_point <= normalized_end {
1048            normalized_point - normalized_start
1049        } else {
1050            // Point is not on the arc, return closest endpoint
1051            let dist_to_start = libm::fmin(
1052                (normalized_point - normalized_start).abs(),
1053                TAU - (normalized_point - normalized_start).abs(),
1054            );
1055            let dist_to_end = libm::fmin(
1056                (normalized_point - normalized_end).abs(),
1057                TAU - (normalized_point - normalized_end).abs(),
1058            );
1059            return if dist_to_start < dist_to_end { 0.0 } else { 1.0 };
1060        }
1061    } else {
1062        // Wrap around case
1063        if normalized_point >= normalized_start || normalized_point <= normalized_end {
1064            if normalized_point >= normalized_start {
1065                normalized_point - normalized_start
1066            } else {
1067                TAU - normalized_start + normalized_point
1068            }
1069        } else {
1070            // Point is not on the arc
1071            let dist_to_start = libm::fmin(
1072                (normalized_point - normalized_start).abs(),
1073                TAU - (normalized_point - normalized_start).abs(),
1074            );
1075            let dist_to_end = libm::fmin(
1076                (normalized_point - normalized_end).abs(),
1077                TAU - (normalized_point - normalized_end).abs(),
1078            );
1079            return if dist_to_start < dist_to_end { 0.0 } else { 1.0 };
1080        }
1081    };
1082
1083    // Return parametric position
1084    point_arc_length / arc_length
1085}
1086
1087/// Helper to calculate all intersections between two arcs (via circle-circle intersection).
1088///
1089/// Returns all valid points that lie on both arcs (0, 1, or 2).
1090pub fn arc_arc_intersections(
1091    arc1_center: Coords2d,
1092    arc1_start: Coords2d,
1093    arc1_end: Coords2d,
1094    arc2_center: Coords2d,
1095    arc2_start: Coords2d,
1096    arc2_end: Coords2d,
1097    epsilon: f64,
1098) -> Vec<Coords2d> {
1099    // Calculate radii
1100    let r1 = ((arc1_start.x - arc1_center.x) * (arc1_start.x - arc1_center.x)
1101        + (arc1_start.y - arc1_center.y) * (arc1_start.y - arc1_center.y))
1102        .sqrt();
1103    let r2 = ((arc2_start.x - arc2_center.x) * (arc2_start.x - arc2_center.x)
1104        + (arc2_start.y - arc2_center.y) * (arc2_start.y - arc2_center.y))
1105        .sqrt();
1106
1107    // Distance between centers
1108    let dx = arc2_center.x - arc1_center.x;
1109    let dy = arc2_center.y - arc1_center.y;
1110    let d = (dx * dx + dy * dy).sqrt();
1111
1112    // Check if circles intersect
1113    if d > r1 + r2 + epsilon || d < (r1 - r2).abs() - epsilon {
1114        // No intersection
1115        return Vec::new();
1116    }
1117
1118    // Check for degenerate cases
1119    if d < EPSILON_PARALLEL {
1120        // Concentric circles - no intersection (or infinite if same radius, but we treat as none)
1121        return Vec::new();
1122    }
1123
1124    // Calculate intersection points
1125    // Using the formula from: https://mathworld.wolfram.com/Circle-CircleIntersection.html
1126    let a = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d);
1127    let h_sq = r1 * r1 - a * a;
1128
1129    // If h_sq is negative, no intersection
1130    if h_sq < 0.0 {
1131        return Vec::new();
1132    }
1133
1134    let h = h_sq.sqrt();
1135
1136    // If h is NaN, no intersection
1137    if h.is_nan() {
1138        return Vec::new();
1139    }
1140
1141    // Unit vector from arc1Center to arc2Center
1142    let ux = dx / d;
1143    let uy = dy / d;
1144
1145    // Perpendicular vector (rotated 90 degrees)
1146    let px = -uy;
1147    let py = ux;
1148
1149    // Midpoint on the line connecting centers
1150    let mid_point = Coords2d {
1151        x: arc1_center.x + a * ux,
1152        y: arc1_center.y + a * uy,
1153    };
1154
1155    // Two intersection points
1156    let intersection1 = Coords2d {
1157        x: mid_point.x + h * px,
1158        y: mid_point.y + h * py,
1159    };
1160    let intersection2 = Coords2d {
1161        x: mid_point.x - h * px,
1162        y: mid_point.y - h * py,
1163    };
1164
1165    // Check which intersection point(s) are on both arcs
1166    let mut candidates: Vec<Coords2d> = Vec::new();
1167
1168    if is_point_on_arc(intersection1, arc1_center, arc1_start, arc1_end, epsilon)
1169        && is_point_on_arc(intersection1, arc2_center, arc2_start, arc2_end, epsilon)
1170    {
1171        candidates.push(intersection1);
1172    }
1173
1174    if (intersection1.x - intersection2.x).abs() > epsilon || (intersection1.y - intersection2.y).abs() > epsilon {
1175        // Only check second point if it's different from the first
1176        if is_point_on_arc(intersection2, arc1_center, arc1_start, arc1_end, epsilon)
1177            && is_point_on_arc(intersection2, arc2_center, arc2_start, arc2_end, epsilon)
1178        {
1179            candidates.push(intersection2);
1180        }
1181    }
1182
1183    candidates
1184}
1185
1186/// Helper to calculate one intersection between two arcs (if any).
1187///
1188/// This is kept for compatibility with existing call sites/tests that expect
1189/// a single optional intersection.
1190pub fn arc_arc_intersection(
1191    arc1_center: Coords2d,
1192    arc1_start: Coords2d,
1193    arc1_end: Coords2d,
1194    arc2_center: Coords2d,
1195    arc2_start: Coords2d,
1196    arc2_end: Coords2d,
1197    epsilon: f64,
1198) -> Option<Coords2d> {
1199    arc_arc_intersections(
1200        arc1_center,
1201        arc1_start,
1202        arc1_end,
1203        arc2_center,
1204        arc2_start,
1205        arc2_end,
1206        epsilon,
1207    )
1208    .first()
1209    .copied()
1210}
1211
1212/// Helper to calculate intersections between a full circle and an arc.
1213///
1214/// Returns all valid intersection points on the arc (0, 1, or 2).
1215pub fn circle_arc_intersections(
1216    circle_center: Coords2d,
1217    circle_radius: f64,
1218    arc_center: Coords2d,
1219    arc_start: Coords2d,
1220    arc_end: Coords2d,
1221    epsilon: f64,
1222) -> Vec<Coords2d> {
1223    let r1 = circle_radius;
1224    let r2 = ((arc_start.x - arc_center.x) * (arc_start.x - arc_center.x)
1225        + (arc_start.y - arc_center.y) * (arc_start.y - arc_center.y))
1226        .sqrt();
1227
1228    let dx = arc_center.x - circle_center.x;
1229    let dy = arc_center.y - circle_center.y;
1230    let d = (dx * dx + dy * dy).sqrt();
1231
1232    if d > r1 + r2 + epsilon || d < (r1 - r2).abs() - epsilon || d < EPSILON_PARALLEL {
1233        return Vec::new();
1234    }
1235
1236    let a = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d);
1237    let h_sq = r1 * r1 - a * a;
1238    if h_sq < 0.0 {
1239        return Vec::new();
1240    }
1241    let h = h_sq.sqrt();
1242    if h.is_nan() {
1243        return Vec::new();
1244    }
1245
1246    let ux = dx / d;
1247    let uy = dy / d;
1248    let px = -uy;
1249    let py = ux;
1250    let mid_point = Coords2d {
1251        x: circle_center.x + a * ux,
1252        y: circle_center.y + a * uy,
1253    };
1254
1255    let intersection1 = Coords2d {
1256        x: mid_point.x + h * px,
1257        y: mid_point.y + h * py,
1258    };
1259    let intersection2 = Coords2d {
1260        x: mid_point.x - h * px,
1261        y: mid_point.y - h * py,
1262    };
1263
1264    let mut intersections = Vec::new();
1265    if is_point_on_arc(intersection1, arc_center, arc_start, arc_end, epsilon) {
1266        intersections.push(intersection1);
1267    }
1268    if ((intersection1.x - intersection2.x).abs() > epsilon || (intersection1.y - intersection2.y).abs() > epsilon)
1269        && is_point_on_arc(intersection2, arc_center, arc_start, arc_end, epsilon)
1270    {
1271        intersections.push(intersection2);
1272    }
1273    intersections
1274}
1275
1276/// Helper to calculate intersections between two full circles.
1277///
1278/// Returns 0, 1 (tangent), or 2 intersection points.
1279pub fn circle_circle_intersections(
1280    circle1_center: Coords2d,
1281    circle1_radius: f64,
1282    circle2_center: Coords2d,
1283    circle2_radius: f64,
1284    epsilon: f64,
1285) -> Vec<Coords2d> {
1286    let dx = circle2_center.x - circle1_center.x;
1287    let dy = circle2_center.y - circle1_center.y;
1288    let d = (dx * dx + dy * dy).sqrt();
1289
1290    if d > circle1_radius + circle2_radius + epsilon
1291        || d < (circle1_radius - circle2_radius).abs() - epsilon
1292        || d < EPSILON_PARALLEL
1293    {
1294        return Vec::new();
1295    }
1296
1297    let a = (circle1_radius * circle1_radius - circle2_radius * circle2_radius + d * d) / (2.0 * d);
1298    let h_sq = circle1_radius * circle1_radius - a * a;
1299    if h_sq < 0.0 {
1300        return Vec::new();
1301    }
1302
1303    let h = if h_sq <= epsilon { 0.0 } else { h_sq.sqrt() };
1304    if h.is_nan() {
1305        return Vec::new();
1306    }
1307
1308    let ux = dx / d;
1309    let uy = dy / d;
1310    let px = -uy;
1311    let py = ux;
1312
1313    let mid_point = Coords2d {
1314        x: circle1_center.x + a * ux,
1315        y: circle1_center.y + a * uy,
1316    };
1317
1318    let intersection1 = Coords2d {
1319        x: mid_point.x + h * px,
1320        y: mid_point.y + h * py,
1321    };
1322    let intersection2 = Coords2d {
1323        x: mid_point.x - h * px,
1324        y: mid_point.y - h * py,
1325    };
1326
1327    let mut intersections = vec![intersection1];
1328    if (intersection1.x - intersection2.x).abs() > epsilon || (intersection1.y - intersection2.y).abs() > epsilon {
1329        intersections.push(intersection2);
1330    }
1331    intersections
1332}
1333
1334/// Helper to extract coordinates from a point object in JSON format
1335// Native type helper - get point coordinates from ObjectId
1336fn get_point_coords_from_native(objects: &[Object], point_id: ObjectId, default_unit: UnitLength) -> Option<Coords2d> {
1337    let point_obj = objects.get(point_id.0)?;
1338
1339    // Check if it's a Point segment
1340    let ObjectKind::Segment { segment } = &point_obj.kind else {
1341        return None;
1342    };
1343
1344    let Segment::Point(point) = segment else {
1345        return None;
1346    };
1347
1348    // Extract position coordinates in the trim internal unit
1349    Some(Coords2d {
1350        x: number_to_unit(&point.position.x, default_unit),
1351        y: number_to_unit(&point.position.y, default_unit),
1352    })
1353}
1354
1355// Legacy JSON helper (will be removed)
1356/// Helper to get point coordinates from a Line segment by looking up the point object (native types)
1357pub fn get_position_coords_for_line(
1358    segment_obj: &Object,
1359    which: LineEndpoint,
1360    objects: &[Object],
1361    default_unit: UnitLength,
1362) -> Option<Coords2d> {
1363    let ObjectKind::Segment { segment } = &segment_obj.kind else {
1364        return None;
1365    };
1366
1367    let Segment::Line(line) = segment else {
1368        return None;
1369    };
1370
1371    // Get the point ID from the segment
1372    let point_id = match which {
1373        LineEndpoint::Start => line.start,
1374        LineEndpoint::End => line.end,
1375    };
1376
1377    get_point_coords_from_native(objects, point_id, default_unit)
1378}
1379
1380/// Helper to check if a point is coincident with a segment (line or arc) via constraints (native types)
1381fn is_point_coincident_with_segment_native(point_id: ObjectId, segment_id: ObjectId, objects: &[Object]) -> bool {
1382    // Find coincident constraints
1383    for obj in objects {
1384        let ObjectKind::Constraint { constraint } = &obj.kind else {
1385            continue;
1386        };
1387
1388        let Constraint::Coincident(coincident) = constraint else {
1389            continue;
1390        };
1391
1392        // Check if both pointId and segmentId are in the segments array
1393        let has_point = coincident.contains_segment(point_id);
1394        let has_segment = coincident.contains_segment(segment_id);
1395
1396        if has_point && has_segment {
1397            return true;
1398        }
1399    }
1400    false
1401}
1402
1403/// Helper to get point coordinates from an Arc segment by looking up the point object (native types)
1404pub fn get_position_coords_from_arc(
1405    segment_obj: &Object,
1406    which: ArcPoint,
1407    objects: &[Object],
1408    default_unit: UnitLength,
1409) -> Option<Coords2d> {
1410    let ObjectKind::Segment { segment } = &segment_obj.kind else {
1411        return None;
1412    };
1413
1414    let Segment::Arc(arc) = segment else {
1415        return None;
1416    };
1417
1418    // Get the point ID from the segment
1419    let point_id = match which {
1420        ArcPoint::Start => arc.start,
1421        ArcPoint::End => arc.end,
1422        ArcPoint::Center => arc.center,
1423    };
1424
1425    get_point_coords_from_native(objects, point_id, default_unit)
1426}
1427
1428/// Helper to get point coordinates from a Circle segment by looking up the point object (native types)
1429pub fn get_position_coords_from_circle(
1430    segment_obj: &Object,
1431    which: CirclePoint,
1432    objects: &[Object],
1433    default_unit: UnitLength,
1434) -> Option<Coords2d> {
1435    let ObjectKind::Segment { segment } = &segment_obj.kind else {
1436        return None;
1437    };
1438
1439    let Segment::Circle(circle) = segment else {
1440        return None;
1441    };
1442
1443    let point_id = match which {
1444        CirclePoint::Start => circle.start,
1445        CirclePoint::Center => circle.center,
1446    };
1447
1448    get_point_coords_from_native(objects, point_id, default_unit)
1449}
1450
1451/// Internal normalized curve kind used by trim.
1452#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1453enum CurveKind {
1454    Line,
1455    Circular,
1456}
1457
1458/// Internal curve domain used by trim.
1459#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1460enum CurveDomain {
1461    Open,
1462    Closed,
1463}
1464
1465/// Internal normalized curve representation loaded from a scene segment.
1466#[derive(Debug, Clone, Copy)]
1467struct CurveHandle {
1468    segment_id: ObjectId,
1469    kind: CurveKind,
1470    domain: CurveDomain,
1471    start: Coords2d,
1472    end: Coords2d,
1473    center: Option<Coords2d>,
1474    radius: Option<f64>,
1475}
1476
1477impl CurveHandle {
1478    fn project_for_trim(self, point: Coords2d) -> Result<f64, String> {
1479        match (self.kind, self.domain) {
1480            (CurveKind::Line, CurveDomain::Open) => Ok(project_point_onto_segment(point, self.start, self.end)),
1481            (CurveKind::Circular, CurveDomain::Open) => {
1482                let center = self
1483                    .center
1484                    .ok_or_else(|| format!("Curve {} missing center for arc projection", self.segment_id.0))?;
1485                Ok(project_point_onto_arc(point, center, self.start, self.end))
1486            }
1487            (CurveKind::Circular, CurveDomain::Closed) => {
1488                let center = self
1489                    .center
1490                    .ok_or_else(|| format!("Curve {} missing center for circle projection", self.segment_id.0))?;
1491                Ok(project_point_onto_circle(point, center, self.start))
1492            }
1493            (CurveKind::Line, CurveDomain::Closed) => Err(format!(
1494                "Invalid curve state: line {} cannot be closed",
1495                self.segment_id.0
1496            )),
1497        }
1498    }
1499}
1500
1501/// Load a normalized curve handle from a segment object.
1502fn load_curve_handle(
1503    segment_obj: &Object,
1504    objects: &[Object],
1505    default_unit: UnitLength,
1506) -> Result<CurveHandle, String> {
1507    let ObjectKind::Segment { segment } = &segment_obj.kind else {
1508        return Err("Object is not a segment".to_owned());
1509    };
1510
1511    match segment {
1512        Segment::Line(_) => {
1513            let start = get_position_coords_for_line(segment_obj, LineEndpoint::Start, objects, default_unit)
1514                .ok_or_else(|| format!("Could not get line start for segment {}", segment_obj.id.0))?;
1515            let end = get_position_coords_for_line(segment_obj, LineEndpoint::End, objects, default_unit)
1516                .ok_or_else(|| format!("Could not get line end for segment {}", segment_obj.id.0))?;
1517            Ok(CurveHandle {
1518                segment_id: segment_obj.id,
1519                kind: CurveKind::Line,
1520                domain: CurveDomain::Open,
1521                start,
1522                end,
1523                center: None,
1524                radius: None,
1525            })
1526        }
1527        Segment::Arc(_) => {
1528            let start = get_position_coords_from_arc(segment_obj, ArcPoint::Start, objects, default_unit)
1529                .ok_or_else(|| format!("Could not get arc start for segment {}", segment_obj.id.0))?;
1530            let end = get_position_coords_from_arc(segment_obj, ArcPoint::End, objects, default_unit)
1531                .ok_or_else(|| format!("Could not get arc end for segment {}", segment_obj.id.0))?;
1532            let center = get_position_coords_from_arc(segment_obj, ArcPoint::Center, objects, default_unit)
1533                .ok_or_else(|| format!("Could not get arc center for segment {}", segment_obj.id.0))?;
1534            let radius =
1535                ((start.x - center.x) * (start.x - center.x) + (start.y - center.y) * (start.y - center.y)).sqrt();
1536            Ok(CurveHandle {
1537                segment_id: segment_obj.id,
1538                kind: CurveKind::Circular,
1539                domain: CurveDomain::Open,
1540                start,
1541                end,
1542                center: Some(center),
1543                radius: Some(radius),
1544            })
1545        }
1546        Segment::Circle(_) => {
1547            let start = get_position_coords_from_circle(segment_obj, CirclePoint::Start, objects, default_unit)
1548                .ok_or_else(|| format!("Could not get circle start for segment {}", segment_obj.id.0))?;
1549            let center = get_position_coords_from_circle(segment_obj, CirclePoint::Center, objects, default_unit)
1550                .ok_or_else(|| format!("Could not get circle center for segment {}", segment_obj.id.0))?;
1551            let radius =
1552                ((start.x - center.x) * (start.x - center.x) + (start.y - center.y) * (start.y - center.y)).sqrt();
1553            Ok(CurveHandle {
1554                segment_id: segment_obj.id,
1555                kind: CurveKind::Circular,
1556                domain: CurveDomain::Closed,
1557                start,
1558                // Closed curves have no true "end"; keep current trim semantics by mirroring start.
1559                end: start,
1560                center: Some(center),
1561                radius: Some(radius),
1562            })
1563        }
1564        Segment::Point(_) => Err(format!(
1565            "Point segment {} cannot be used as trim curve",
1566            segment_obj.id.0
1567        )),
1568    }
1569}
1570
1571fn project_point_onto_curve(curve: CurveHandle, point: Coords2d) -> Result<f64, String> {
1572    curve.project_for_trim(point)
1573}
1574
1575fn curve_contains_point(curve: CurveHandle, point: Coords2d, epsilon: f64) -> bool {
1576    match (curve.kind, curve.domain) {
1577        (CurveKind::Line, CurveDomain::Open) => {
1578            let t = project_point_onto_segment(point, curve.start, curve.end);
1579            (0.0..=1.0).contains(&t) && perpendicular_distance_to_segment(point, curve.start, curve.end) <= epsilon
1580        }
1581        (CurveKind::Circular, CurveDomain::Open) => curve
1582            .center
1583            .is_some_and(|center| is_point_on_arc(point, center, curve.start, curve.end, epsilon)),
1584        (CurveKind::Circular, CurveDomain::Closed) => curve.center.is_some_and(|center| {
1585            let radius = curve.radius.unwrap_or_else(|| {
1586                ((curve.start.x - center.x).squared() + (curve.start.y - center.y).squared()).sqrt()
1587            });
1588            is_point_on_circle(point, center, radius, epsilon)
1589        }),
1590        (CurveKind::Line, CurveDomain::Closed) => false,
1591    }
1592}
1593
1594fn curve_line_segment_intersections(
1595    curve: CurveHandle,
1596    line_start: Coords2d,
1597    line_end: Coords2d,
1598    epsilon: f64,
1599) -> Vec<(f64, Coords2d)> {
1600    match (curve.kind, curve.domain) {
1601        (CurveKind::Line, CurveDomain::Open) => {
1602            line_segment_intersection(line_start, line_end, curve.start, curve.end, epsilon)
1603                .map(|intersection| {
1604                    (
1605                        project_point_onto_segment(intersection, line_start, line_end),
1606                        intersection,
1607                    )
1608                })
1609                .into_iter()
1610                .collect()
1611        }
1612        (CurveKind::Circular, CurveDomain::Open) => curve
1613            .center
1614            .map(|center| line_arc_intersections(line_start, line_end, center, curve.start, curve.end, epsilon))
1615            .unwrap_or_default(),
1616        (CurveKind::Circular, CurveDomain::Closed) => {
1617            let Some(center) = curve.center else {
1618                return Vec::new();
1619            };
1620            let radius = curve.radius.unwrap_or_else(|| {
1621                ((curve.start.x - center.x).squared() + (curve.start.y - center.y).squared()).sqrt()
1622            });
1623            line_circle_intersections(line_start, line_end, center, radius, epsilon)
1624        }
1625        (CurveKind::Line, CurveDomain::Closed) => Vec::new(),
1626    }
1627}
1628
1629fn curve_polyline_intersections(curve: CurveHandle, polyline: &[Coords2d], epsilon: f64) -> Vec<(Coords2d, usize)> {
1630    let mut intersections = Vec::new();
1631
1632    for i in 0..polyline.len().saturating_sub(1) {
1633        let p1 = polyline[i];
1634        let p2 = polyline[i + 1];
1635        for (_, intersection) in curve_line_segment_intersections(curve, p1, p2, epsilon) {
1636            intersections.push((intersection, i));
1637        }
1638    }
1639
1640    intersections
1641}
1642
1643fn curve_curve_intersections(curve: CurveHandle, other: CurveHandle, epsilon: f64) -> Vec<Coords2d> {
1644    match (curve.kind, curve.domain, other.kind, other.domain) {
1645        (CurveKind::Line, CurveDomain::Open, CurveKind::Line, CurveDomain::Open) => {
1646            line_segment_intersection(curve.start, curve.end, other.start, other.end, epsilon)
1647                .into_iter()
1648                .collect()
1649        }
1650        (CurveKind::Line, CurveDomain::Open, CurveKind::Circular, CurveDomain::Open) => other
1651            .center
1652            .map(|other_center| {
1653                line_arc_intersections(curve.start, curve.end, other_center, other.start, other.end, epsilon)
1654                    .into_iter()
1655                    .map(|(_, point)| point)
1656                    .collect()
1657            })
1658            .unwrap_or_default(),
1659        (CurveKind::Line, CurveDomain::Open, CurveKind::Circular, CurveDomain::Closed) => {
1660            let Some(other_center) = other.center else {
1661                return Vec::new();
1662            };
1663            let other_radius = other.radius.unwrap_or_else(|| {
1664                ((other.start.x - other_center.x).squared() + (other.start.y - other_center.y).squared()).sqrt()
1665            });
1666            line_circle_intersections(curve.start, curve.end, other_center, other_radius, epsilon)
1667                .into_iter()
1668                .map(|(_, point)| point)
1669                .collect()
1670        }
1671        (CurveKind::Circular, CurveDomain::Open, CurveKind::Line, CurveDomain::Open) => curve
1672            .center
1673            .map(|curve_center| {
1674                line_arc_intersections(other.start, other.end, curve_center, curve.start, curve.end, epsilon)
1675                    .into_iter()
1676                    .map(|(_, point)| point)
1677                    .collect()
1678            })
1679            .unwrap_or_default(),
1680        (CurveKind::Circular, CurveDomain::Open, CurveKind::Circular, CurveDomain::Open) => {
1681            let (Some(curve_center), Some(other_center)) = (curve.center, other.center) else {
1682                return Vec::new();
1683            };
1684            arc_arc_intersections(
1685                curve_center,
1686                curve.start,
1687                curve.end,
1688                other_center,
1689                other.start,
1690                other.end,
1691                epsilon,
1692            )
1693        }
1694        (CurveKind::Circular, CurveDomain::Open, CurveKind::Circular, CurveDomain::Closed) => {
1695            let (Some(curve_center), Some(other_center)) = (curve.center, other.center) else {
1696                return Vec::new();
1697            };
1698            let other_radius = other.radius.unwrap_or_else(|| {
1699                ((other.start.x - other_center.x).squared() + (other.start.y - other_center.y).squared()).sqrt()
1700            });
1701            circle_arc_intersections(
1702                other_center,
1703                other_radius,
1704                curve_center,
1705                curve.start,
1706                curve.end,
1707                epsilon,
1708            )
1709        }
1710        (CurveKind::Circular, CurveDomain::Closed, CurveKind::Line, CurveDomain::Open) => {
1711            let Some(curve_center) = curve.center else {
1712                return Vec::new();
1713            };
1714            let curve_radius = curve.radius.unwrap_or_else(|| {
1715                ((curve.start.x - curve_center.x).squared() + (curve.start.y - curve_center.y).squared()).sqrt()
1716            });
1717            line_circle_intersections(other.start, other.end, curve_center, curve_radius, epsilon)
1718                .into_iter()
1719                .map(|(_, point)| point)
1720                .collect()
1721        }
1722        (CurveKind::Circular, CurveDomain::Closed, CurveKind::Circular, CurveDomain::Open) => {
1723            let (Some(curve_center), Some(other_center)) = (curve.center, other.center) else {
1724                return Vec::new();
1725            };
1726            let curve_radius = curve.radius.unwrap_or_else(|| {
1727                ((curve.start.x - curve_center.x).squared() + (curve.start.y - curve_center.y).squared()).sqrt()
1728            });
1729            circle_arc_intersections(
1730                curve_center,
1731                curve_radius,
1732                other_center,
1733                other.start,
1734                other.end,
1735                epsilon,
1736            )
1737        }
1738        (CurveKind::Circular, CurveDomain::Closed, CurveKind::Circular, CurveDomain::Closed) => {
1739            let (Some(curve_center), Some(other_center)) = (curve.center, other.center) else {
1740                return Vec::new();
1741            };
1742            let curve_radius = curve.radius.unwrap_or_else(|| {
1743                ((curve.start.x - curve_center.x).squared() + (curve.start.y - curve_center.y).squared()).sqrt()
1744            });
1745            let other_radius = other.radius.unwrap_or_else(|| {
1746                ((other.start.x - other_center.x).squared() + (other.start.y - other_center.y).squared()).sqrt()
1747            });
1748            circle_circle_intersections(curve_center, curve_radius, other_center, other_radius, epsilon)
1749        }
1750        _ => Vec::new(),
1751    }
1752}
1753
1754fn segment_endpoint_points(
1755    segment_obj: &Object,
1756    objects: &[Object],
1757    default_unit: UnitLength,
1758) -> Vec<(ObjectId, Coords2d)> {
1759    let ObjectKind::Segment { segment } = &segment_obj.kind else {
1760        return Vec::new();
1761    };
1762
1763    match segment {
1764        Segment::Line(line) => {
1765            let mut points = Vec::new();
1766            if let Some(start) = get_position_coords_for_line(segment_obj, LineEndpoint::Start, objects, default_unit) {
1767                points.push((line.start, start));
1768            }
1769            if let Some(end) = get_position_coords_for_line(segment_obj, LineEndpoint::End, objects, default_unit) {
1770                points.push((line.end, end));
1771            }
1772            points
1773        }
1774        Segment::Arc(arc) => {
1775            let mut points = Vec::new();
1776            if let Some(start) = get_position_coords_from_arc(segment_obj, ArcPoint::Start, objects, default_unit) {
1777                points.push((arc.start, start));
1778            }
1779            if let Some(end) = get_position_coords_from_arc(segment_obj, ArcPoint::End, objects, default_unit) {
1780                points.push((arc.end, end));
1781            }
1782            points
1783        }
1784        _ => Vec::new(),
1785    }
1786}
1787
1788/// Find the next trim spawn (intersection) between trim line and scene segments
1789///
1790/// When a user draws a trim line, we loop over each pairs of points of the trim line,
1791/// until we find an intersection, this intersection is called the trim spawn (to differentiate from
1792/// segment-segment intersections which are also important for trimming).
1793/// Below the dashes are segments and the periods are points on the trim line.
1794///
1795/// ```
1796///          /
1797///         /
1798///        /    .
1799/// ------/-------x--------
1800///      /       .       
1801///     /       .       
1802///    /           .   
1803/// ```
1804///
1805/// When we find a trim spawn we stop looping but save the index as we process each trim spawn one at a time.
1806/// The loop that processes each spawn one at a time is managed by `execute_trim_loop` (or `execute_trim_loop_with_context`).
1807///
1808/// Loops through polyline segments starting from startIndex and checks for intersections
1809/// with all scene segments (both Line and Arc). Returns the first intersection found.
1810///
1811/// **Units:** Trim line points are expected in millimeters at the API boundary. Callers should
1812/// normalize points to the current/default length unit before calling this function (the
1813/// trim loop does this for you). Segment positions read from `objects` are converted to that same
1814/// unit internally.
1815pub fn get_next_trim_spawn(
1816    points: &[Coords2d],
1817    start_index: usize,
1818    objects: &[Object],
1819    default_unit: UnitLength,
1820) -> TrimItem {
1821    let scene_curves: Vec<CurveHandle> = objects
1822        .iter()
1823        .filter_map(|obj| load_curve_handle(obj, objects, default_unit).ok())
1824        .collect();
1825
1826    // Loop through polyline segments starting from startIndex
1827    for i in start_index..points.len().saturating_sub(1) {
1828        let p1 = points[i];
1829        let p2 = points[i + 1];
1830
1831        // Check this polyline segment against all scene segments
1832        for curve in &scene_curves {
1833            let intersections = curve_line_segment_intersections(*curve, p1, p2, EPSILON_POINT_ON_SEGMENT);
1834            if let Some((_, intersection)) = intersections.first() {
1835                return TrimItem::Spawn {
1836                    trim_spawn_seg_id: curve.segment_id,
1837                    trim_spawn_coords: *intersection,
1838                    next_index: i,
1839                };
1840            }
1841        }
1842    }
1843
1844    // No intersection found
1845    TrimItem::None {
1846        next_index: points.len().saturating_sub(1),
1847    }
1848}
1849
1850/**
1851 * For the trim spawn segment and the intersection point on that segment,
1852 * finds the "trim terminations" in both directions (left and right from the intersection point).
1853 * A trim termination is the point where trimming should stop in each direction.
1854 *
1855 * The function searches for candidates in each direction and selects the closest one,
1856 * with the following priority when distances are equal: coincident > intersection > endpoint.
1857 *
1858 * ## segEndPoint: The segment's own endpoint
1859 *
1860 *   ========0
1861 * OR
1862 *   ========0
1863 *            \
1864 *             \
1865 *
1866 *  Returns this when:
1867 *  - No other candidates are found between the intersection point and the segment end
1868 *  - An intersection is found at the segment's own endpoint (even if due to numerical precision)
1869 *  - An intersection is found at another segment's endpoint (without a coincident constraint)
1870 *  - The closest candidate is the segment's own endpoint
1871 *
1872 * ## intersection: Intersection with another segment's body
1873 *            /
1874 *           /
1875 *  ========X=====
1876 *         /
1877 *        /
1878 *
1879 *  Returns this when:
1880 *  - A geometric intersection is found with another segment's body (not at an endpoint)
1881 *  - The intersection is not at our own segment's endpoint
1882 *  - The intersection is not at the other segment's endpoint (which would be segEndPoint)
1883 *
1884 * ## trimSpawnSegmentCoincidentWithAnotherSegmentPoint: Another segment's endpoint coincident with our segment
1885 *
1886 *  ========0=====
1887 *         /
1888 *        /
1889 *
1890 *  Returns this when:
1891 *  - Another segment's endpoint has a coincident constraint with our trim spawn segment
1892 *  - The endpoint's perpendicular distance to our segment is within epsilon
1893 *  - The endpoint is geometrically on our segment (between start and end)
1894 *  - This takes priority over intersections when distances are equal (within epsilon)
1895 *
1896 * ## Fallback
1897 *  If no candidates are found in a direction, defaults to "segEndPoint".
1898 * */
1899/// Find trim terminations for both sides of a trim spawn
1900///
1901/// For the trim spawn segment and the intersection point on that segment,
1902/// finds the "trim terminations" in both directions (left and right from the intersection point).
1903/// A trim termination is the point where trimming should stop in each direction.
1904pub fn get_trim_spawn_terminations(
1905    trim_spawn_seg_id: ObjectId,
1906    trim_spawn_coords: &[Coords2d],
1907    objects: &[Object],
1908    default_unit: UnitLength,
1909) -> Result<TrimTerminations, String> {
1910    // Find the trim spawn segment
1911    let trim_spawn_seg = objects.iter().find(|obj| obj.id == trim_spawn_seg_id);
1912
1913    let trim_spawn_seg = match trim_spawn_seg {
1914        Some(seg) => seg,
1915        None => {
1916            return Err(format!("Trim spawn segment {} not found", trim_spawn_seg_id.0));
1917        }
1918    };
1919
1920    let trim_curve = load_curve_handle(trim_spawn_seg, objects, default_unit).map_err(|e| {
1921        format!(
1922            "Failed to load trim spawn segment {} as normalized curve: {}",
1923            trim_spawn_seg_id.0, e
1924        )
1925    })?;
1926
1927    // Find intersection point between polyline and trim spawn segment
1928    // trimSpawnCoords is a polyline, so we check each segment
1929    // We need to find ALL intersections and use a consistent one to avoid
1930    // different results for different trim lines in the same area
1931    let all_intersections = curve_polyline_intersections(trim_curve, trim_spawn_coords, EPSILON_POINT_ON_SEGMENT);
1932
1933    // Use the intersection that's closest to the middle of the polyline
1934    // This ensures consistent results regardless of which segment intersects first
1935    let intersection_point = if all_intersections.is_empty() {
1936        return Err("Could not find intersection point between polyline and trim spawn segment".to_string());
1937    } else {
1938        // Find the middle of the polyline
1939        let mid_index = (trim_spawn_coords.len() - 1) / 2;
1940        let mid_point = trim_spawn_coords[mid_index];
1941
1942        // Find the intersection closest to the middle
1943        let mut min_dist = f64::INFINITY;
1944        let mut closest_intersection = all_intersections[0].0;
1945
1946        for (intersection, _) in &all_intersections {
1947            let dist = ((intersection.x - mid_point.x) * (intersection.x - mid_point.x)
1948                + (intersection.y - mid_point.y) * (intersection.y - mid_point.y))
1949                .sqrt();
1950            if dist < min_dist {
1951                min_dist = dist;
1952                closest_intersection = *intersection;
1953            }
1954        }
1955
1956        closest_intersection
1957    };
1958
1959    // Project intersection point onto segment to get parametric position
1960    let intersection_t = project_point_onto_curve(trim_curve, intersection_point)?;
1961
1962    // Find terminations on both sides
1963    let left_termination = find_termination_in_direction(
1964        trim_spawn_seg,
1965        trim_curve,
1966        intersection_t,
1967        TrimDirection::Left,
1968        objects,
1969        default_unit,
1970    )?;
1971
1972    let right_termination = find_termination_in_direction(
1973        trim_spawn_seg,
1974        trim_curve,
1975        intersection_t,
1976        TrimDirection::Right,
1977        objects,
1978        default_unit,
1979    )?;
1980
1981    Ok(TrimTerminations {
1982        left_side: left_termination,
1983        right_side: right_termination,
1984    })
1985}
1986
1987/// Helper to find trim termination in a given direction from the intersection point
1988///
1989/// This is called by `get_trim_spawn_terminations` for each direction (left and right).
1990/// It searches for candidates in the specified direction and selects the closest one,
1991/// with the following priority when distances are equal: coincident > intersection > endpoint.
1992///
1993/// ## segEndPoint: The segment's own endpoint
1994///
1995/// ```
1996///   ========0
1997/// OR
1998///   ========0
1999///            \
2000///             \
2001/// ```
2002///
2003/// Returns this when:
2004/// - No other candidates are found between the intersection point and the segment end
2005/// - An intersection is found at the segment's own endpoint (even if due to numerical precision)
2006/// - An intersection is found at another segment's endpoint (without a coincident constraint)
2007/// - The closest candidate is the segment's own endpoint
2008///
2009/// ## intersection: Intersection with another segment's body
2010/// ```
2011///            /
2012///           /
2013///  ========X=====
2014///         /
2015///        /
2016/// ```
2017///
2018/// Returns this when:
2019/// - A geometric intersection is found with another segment's body (not at an endpoint)
2020/// - The intersection is not at our own segment's endpoint
2021/// - The intersection is not at the other segment's endpoint (which would be segEndPoint)
2022///
2023/// ## trimSpawnSegmentCoincidentWithAnotherSegmentPoint: Another segment's endpoint coincident with our segment
2024///
2025/// ```
2026///  ========0=====
2027///         /
2028///        /
2029/// ```
2030///
2031/// Returns this when:
2032/// - Another segment's endpoint has a coincident constraint with our trim spawn segment
2033/// - The endpoint's perpendicular distance to our segment is within epsilon
2034/// - The endpoint is geometrically on our segment (between start and end)
2035/// - This takes priority over intersections when distances are equal (within epsilon)
2036///
2037/// ## Fallback
2038/// If no candidates are found in a direction, defaults to "segEndPoint".
2039fn find_termination_in_direction(
2040    trim_spawn_seg: &Object,
2041    trim_curve: CurveHandle,
2042    intersection_t: f64,
2043    direction: TrimDirection,
2044    objects: &[Object],
2045    default_unit: UnitLength,
2046) -> Result<TrimTermination, String> {
2047    // Use native types
2048    let ObjectKind::Segment { segment } = &trim_spawn_seg.kind else {
2049        return Err("Trim spawn segment is not a segment".to_string());
2050    };
2051
2052    // Collect all candidate points: intersections, coincident points, and endpoints
2053    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
2054    enum CandidateType {
2055        Intersection,
2056        Coincident,
2057        Endpoint,
2058    }
2059
2060    #[derive(Debug, Clone)]
2061    struct Candidate {
2062        t: f64,
2063        point: Coords2d,
2064        candidate_type: CandidateType,
2065        segment_id: Option<ObjectId>,
2066        point_id: Option<ObjectId>,
2067    }
2068
2069    let mut candidates: Vec<Candidate> = Vec::new();
2070
2071    // Add segment endpoints using native types
2072    match segment {
2073        Segment::Line(line) => {
2074            candidates.push(Candidate {
2075                t: 0.0,
2076                point: trim_curve.start,
2077                candidate_type: CandidateType::Endpoint,
2078                segment_id: None,
2079                point_id: Some(line.start),
2080            });
2081            candidates.push(Candidate {
2082                t: 1.0,
2083                point: trim_curve.end,
2084                candidate_type: CandidateType::Endpoint,
2085                segment_id: None,
2086                point_id: Some(line.end),
2087            });
2088        }
2089        Segment::Arc(arc) => {
2090            // For arcs, endpoints are at t=0 and t=1 conceptually
2091            candidates.push(Candidate {
2092                t: 0.0,
2093                point: trim_curve.start,
2094                candidate_type: CandidateType::Endpoint,
2095                segment_id: None,
2096                point_id: Some(arc.start),
2097            });
2098            candidates.push(Candidate {
2099                t: 1.0,
2100                point: trim_curve.end,
2101                candidate_type: CandidateType::Endpoint,
2102                segment_id: None,
2103                point_id: Some(arc.end),
2104            });
2105        }
2106        Segment::Circle(_) => {
2107            // Circles have no endpoints for trim termination purposes.
2108        }
2109        _ => {}
2110    }
2111
2112    // Get trim spawn segment ID for comparison
2113    let trim_spawn_seg_id = trim_spawn_seg.id;
2114
2115    // Find intersections and coincident endpoint candidates against all other segments.
2116    for other_seg in objects.iter() {
2117        let other_id = other_seg.id;
2118        if other_id == trim_spawn_seg_id {
2119            continue;
2120        }
2121
2122        if let Ok(other_curve) = load_curve_handle(other_seg, objects, default_unit) {
2123            for intersection in curve_curve_intersections(trim_curve, other_curve, EPSILON_POINT_ON_SEGMENT) {
2124                let Ok(t) = project_point_onto_curve(trim_curve, intersection) else {
2125                    continue;
2126                };
2127                candidates.push(Candidate {
2128                    t,
2129                    point: intersection,
2130                    candidate_type: CandidateType::Intersection,
2131                    segment_id: Some(other_id),
2132                    point_id: None,
2133                });
2134            }
2135        }
2136
2137        for (other_point_id, other_point) in segment_endpoint_points(other_seg, objects, default_unit) {
2138            if !is_point_coincident_with_segment_native(other_point_id, trim_spawn_seg_id, objects) {
2139                continue;
2140            }
2141            if !curve_contains_point(trim_curve, other_point, EPSILON_POINT_ON_SEGMENT) {
2142                continue;
2143            }
2144            let Ok(t) = project_point_onto_curve(trim_curve, other_point) else {
2145                continue;
2146            };
2147            candidates.push(Candidate {
2148                t,
2149                point: other_point,
2150                candidate_type: CandidateType::Coincident,
2151                segment_id: Some(other_id),
2152                point_id: Some(other_point_id),
2153            });
2154        }
2155    }
2156
2157    let is_circle_segment = trim_curve.domain == CurveDomain::Closed;
2158
2159    // Filter candidates to exclude the intersection point itself and those on the wrong side.
2160    // Use a slightly larger epsilon to account for numerical precision variations.
2161    let intersection_epsilon = EPSILON_POINT_ON_SEGMENT * 10.0; // 0.0001mm
2162    let direction_distance = |candidate_t: f64| -> f64 {
2163        if is_circle_segment {
2164            match direction {
2165                TrimDirection::Left => (intersection_t - candidate_t).rem_euclid(1.0),
2166                TrimDirection::Right => (candidate_t - intersection_t).rem_euclid(1.0),
2167            }
2168        } else {
2169            (candidate_t - intersection_t).abs()
2170        }
2171    };
2172    let filtered_candidates: Vec<Candidate> = candidates
2173        .into_iter()
2174        .filter(|candidate| {
2175            let dist_from_intersection = if is_circle_segment {
2176                let ccw = (candidate.t - intersection_t).rem_euclid(1.0);
2177                let cw = (intersection_t - candidate.t).rem_euclid(1.0);
2178                libm::fmin(ccw, cw)
2179            } else {
2180                (candidate.t - intersection_t).abs()
2181            };
2182            if dist_from_intersection < intersection_epsilon {
2183                return false; // Too close to intersection point
2184            }
2185
2186            if is_circle_segment {
2187                direction_distance(candidate.t) > intersection_epsilon
2188            } else {
2189                match direction {
2190                    TrimDirection::Left => candidate.t < intersection_t,
2191                    TrimDirection::Right => candidate.t > intersection_t,
2192                }
2193            }
2194        })
2195        .collect();
2196
2197    // Sort candidates by distance from intersection (closest first).
2198    // When distances are equal, prioritize: coincident > intersection > endpoint.
2199    // Also allow constrained coincident endpoints to win over nearby geometric
2200    // intersections so arc endpoints coincident with line segments terminate at
2201    // the authored endpoint instead of a tiny adjacent arc-body intersection.
2202    let mut sorted_candidates = filtered_candidates;
2203    sorted_candidates.sort_by(|a, b| {
2204        let dist_a = direction_distance(a.t);
2205        let dist_b = direction_distance(b.t);
2206        let dist_diff = dist_a - dist_b;
2207        let coincident_snap_applies = dist_diff.abs() <= EPSILON_COINCIDENT_TERMINATION_SNAP
2208            && (a.candidate_type == CandidateType::Coincident || b.candidate_type == CandidateType::Coincident);
2209        if dist_diff.abs() > EPSILON_POINT_ON_SEGMENT && !coincident_snap_applies {
2210            dist_diff.partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal)
2211        } else {
2212            // Distances are effectively equal - prioritize by type
2213            let type_priority = |candidate_type: CandidateType| -> i32 {
2214                match candidate_type {
2215                    CandidateType::Coincident => 0,
2216                    CandidateType::Intersection => 1,
2217                    CandidateType::Endpoint => 2,
2218                }
2219            };
2220            type_priority(a.candidate_type).cmp(&type_priority(b.candidate_type))
2221        }
2222    });
2223
2224    // Find the first valid trim termination
2225    let closest_candidate = match sorted_candidates.first() {
2226        Some(c) => c,
2227        None => {
2228            if is_circle_segment {
2229                return Err("No trim termination candidate found for circle".to_string());
2230            }
2231            // No trim termination found, default to segment endpoint
2232            let endpoint = match direction {
2233                TrimDirection::Left => trim_curve.start,
2234                TrimDirection::Right => trim_curve.end,
2235            };
2236            return Ok(TrimTermination::SegEndPoint {
2237                trim_termination_coords: endpoint,
2238            });
2239        }
2240    };
2241
2242    // Check if the closest candidate is an intersection that is actually another segment's endpoint
2243    // According to test case: if another segment's endpoint is on our segment (even without coincident constraint),
2244    // we should return segEndPoint, not intersection
2245    if !is_circle_segment
2246        && closest_candidate.candidate_type == CandidateType::Intersection
2247        && let Some(seg_id) = closest_candidate.segment_id
2248    {
2249        let intersecting_seg = objects.iter().find(|obj| obj.id == seg_id);
2250
2251        if let Some(intersecting_seg) = intersecting_seg {
2252            // Use a larger epsilon for checking if intersection is at another segment's endpoint
2253            let endpoint_epsilon = EPSILON_POINT_ON_SEGMENT * 1000.0; // 0.001mm
2254            let is_other_seg_endpoint = segment_endpoint_points(intersecting_seg, objects, default_unit)
2255                .into_iter()
2256                .any(|(_, endpoint)| {
2257                    let dist_to_endpoint = ((closest_candidate.point.x - endpoint.x).squared()
2258                        + (closest_candidate.point.y - endpoint.y).squared())
2259                    .sqrt();
2260                    dist_to_endpoint < endpoint_epsilon
2261                });
2262
2263            // If the intersection point is another segment's endpoint (even without coincident constraint),
2264            // return segEndPoint instead of intersection
2265            if is_other_seg_endpoint {
2266                let endpoint = match direction {
2267                    TrimDirection::Left => trim_curve.start,
2268                    TrimDirection::Right => trim_curve.end,
2269                };
2270                return Ok(TrimTermination::SegEndPoint {
2271                    trim_termination_coords: endpoint,
2272                });
2273            }
2274        }
2275
2276        // Also check if intersection is at our arc's endpoint
2277        let endpoint_t = match direction {
2278            TrimDirection::Left => 0.0,
2279            TrimDirection::Right => 1.0,
2280        };
2281        let endpoint = match direction {
2282            TrimDirection::Left => trim_curve.start,
2283            TrimDirection::Right => trim_curve.end,
2284        };
2285        let dist_to_endpoint_param = (closest_candidate.t - endpoint_t).abs();
2286        let dist_to_endpoint_coords = ((closest_candidate.point.x - endpoint.x)
2287            * (closest_candidate.point.x - endpoint.x)
2288            + (closest_candidate.point.y - endpoint.y) * (closest_candidate.point.y - endpoint.y))
2289            .sqrt();
2290
2291        let is_at_endpoint =
2292            dist_to_endpoint_param < EPSILON_POINT_ON_SEGMENT || dist_to_endpoint_coords < EPSILON_POINT_ON_SEGMENT;
2293
2294        if is_at_endpoint {
2295            // Intersection is at our endpoint -> segEndPoint
2296            return Ok(TrimTermination::SegEndPoint {
2297                trim_termination_coords: endpoint,
2298            });
2299        }
2300    }
2301
2302    // Check if the closest candidate is an intersection at an endpoint
2303    let endpoint_t_for_return = match direction {
2304        TrimDirection::Left => 0.0,
2305        TrimDirection::Right => 1.0,
2306    };
2307    if !is_circle_segment && closest_candidate.candidate_type == CandidateType::Intersection {
2308        let dist_to_endpoint = (closest_candidate.t - endpoint_t_for_return).abs();
2309        if dist_to_endpoint < EPSILON_POINT_ON_SEGMENT {
2310            // Intersection is at endpoint - check if there's a coincident constraint
2311            // or if it's just a numerical precision issue
2312            let endpoint = match direction {
2313                TrimDirection::Left => trim_curve.start,
2314                TrimDirection::Right => trim_curve.end,
2315            };
2316            return Ok(TrimTermination::SegEndPoint {
2317                trim_termination_coords: endpoint,
2318            });
2319        }
2320    }
2321
2322    // Check if the closest candidate is an endpoint at the trim spawn segment's endpoint
2323    let endpoint = match direction {
2324        TrimDirection::Left => trim_curve.start,
2325        TrimDirection::Right => trim_curve.end,
2326    };
2327    if !is_circle_segment && closest_candidate.candidate_type == CandidateType::Endpoint {
2328        let dist_to_endpoint = (closest_candidate.t - endpoint_t_for_return).abs();
2329        if dist_to_endpoint < EPSILON_POINT_ON_SEGMENT {
2330            // This is our own endpoint, return it
2331            return Ok(TrimTermination::SegEndPoint {
2332                trim_termination_coords: endpoint,
2333            });
2334        }
2335    }
2336
2337    // Return appropriate termination type
2338    if closest_candidate.candidate_type == CandidateType::Coincident {
2339        // Even if at endpoint, return coincident type because it's a constraint-based termination
2340        Ok(TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
2341            trim_termination_coords: closest_candidate.point,
2342            intersecting_seg_id: closest_candidate
2343                .segment_id
2344                .ok_or_else(|| "Missing segment_id for coincident".to_string())?,
2345            other_segment_point_id: closest_candidate
2346                .point_id
2347                .ok_or_else(|| "Missing point_id for coincident".to_string())?,
2348        })
2349    } else if closest_candidate.candidate_type == CandidateType::Intersection {
2350        Ok(TrimTermination::Intersection {
2351            trim_termination_coords: closest_candidate.point,
2352            intersecting_seg_id: closest_candidate
2353                .segment_id
2354                .ok_or_else(|| "Missing segment_id for intersection".to_string())?,
2355        })
2356    } else {
2357        if is_circle_segment {
2358            return Err("Circle trim termination unexpectedly resolved to endpoint".to_string());
2359        }
2360        // endpoint
2361        Ok(TrimTermination::SegEndPoint {
2362            trim_termination_coords: closest_candidate.point,
2363        })
2364    }
2365}
2366
2367/// Execute the core trim loop.
2368/// This function handles the iteration through trim points, finding intersections,
2369/// and determining strategies. It calls the provided callback to execute operations.
2370///
2371/// The callback receives:
2372/// - The strategy (list of operations to execute)
2373/// - The current scene graph delta
2374///
2375/// The callback should return:
2376/// - The updated scene graph delta after executing operations
2377#[cfg(test)]
2378#[allow(dead_code)]
2379pub(crate) async fn execute_trim_loop<F, Fut>(
2380    points: &[Coords2d],
2381    default_unit: UnitLength,
2382    initial_scene_graph_delta: crate::frontend::api::SceneGraphDelta,
2383    mut execute_operations: F,
2384) -> Result<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta), String>
2385where
2386    F: FnMut(Vec<TrimOperation>, crate::frontend::api::SceneGraphDelta) -> Fut,
2387    Fut: std::future::Future<
2388            Output = Result<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta), String>,
2389        >,
2390{
2391    // Trim line points are expected in millimeters and normalized to the current unit here.
2392    let normalized_points = normalize_trim_points_to_unit(points, default_unit);
2393    let points = normalized_points.as_slice();
2394
2395    let mut start_index = 0;
2396    let max_iterations = 1000;
2397    let mut iteration_count = 0;
2398    let mut last_result: Option<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta)> = Some((
2399        crate::frontend::api::SourceDelta { text: String::new() },
2400        initial_scene_graph_delta.clone(),
2401    ));
2402    let mut invalidates_ids = false;
2403    let mut current_scene_graph_delta = initial_scene_graph_delta;
2404    let circle_delete_fallback_strategy =
2405        |error: &str, segment_id: ObjectId, scene_objects: &[Object]| -> Option<Vec<TrimOperation>> {
2406            if !error.contains("No trim termination candidate found for circle") {
2407                return None;
2408            }
2409            let is_circle = scene_objects
2410                .iter()
2411                .find(|obj| obj.id == segment_id)
2412                .is_some_and(|obj| {
2413                    matches!(
2414                        obj.kind,
2415                        ObjectKind::Segment {
2416                            segment: Segment::Circle(_)
2417                        }
2418                    )
2419                });
2420            if is_circle {
2421                Some(vec![TrimOperation::SimpleTrim {
2422                    segment_to_trim_id: segment_id,
2423                }])
2424            } else {
2425                None
2426            }
2427        };
2428
2429    while start_index < points.len().saturating_sub(1) && iteration_count < max_iterations {
2430        iteration_count += 1;
2431
2432        // Get next trim result
2433        let next_trim_spawn = get_next_trim_spawn(
2434            points,
2435            start_index,
2436            &current_scene_graph_delta.new_graph.objects,
2437            default_unit,
2438        );
2439
2440        match &next_trim_spawn {
2441            TrimItem::None { next_index } => {
2442                let old_start_index = start_index;
2443                start_index = *next_index;
2444
2445                // Fail-safe: if start_index didn't advance, force it to advance
2446                if start_index <= old_start_index {
2447                    start_index = old_start_index + 1;
2448                }
2449
2450                // Early exit if we've reached the end
2451                if start_index >= points.len().saturating_sub(1) {
2452                    break;
2453                }
2454                continue;
2455            }
2456            TrimItem::Spawn {
2457                trim_spawn_seg_id,
2458                trim_spawn_coords,
2459                next_index,
2460                ..
2461            } => {
2462                // Get terminations
2463                let terminations = match get_trim_spawn_terminations(
2464                    *trim_spawn_seg_id,
2465                    points,
2466                    &current_scene_graph_delta.new_graph.objects,
2467                    default_unit,
2468                ) {
2469                    Ok(terms) => terms,
2470                    Err(e) => {
2471                        crate::logln!("Error getting trim spawn terminations: {}", e);
2472                        if let Some(strategy) = circle_delete_fallback_strategy(
2473                            &e,
2474                            *trim_spawn_seg_id,
2475                            &current_scene_graph_delta.new_graph.objects,
2476                        ) {
2477                            match execute_operations(strategy, current_scene_graph_delta.clone()).await {
2478                                Ok((source_delta, scene_graph_delta)) => {
2479                                    last_result = Some((source_delta, scene_graph_delta.clone()));
2480                                    invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
2481                                    current_scene_graph_delta = scene_graph_delta;
2482                                }
2483                                Err(exec_err) => {
2484                                    crate::logln!(
2485                                        "Error executing circle-delete fallback trim operation: {}",
2486                                        exec_err
2487                                    );
2488                                }
2489                            }
2490
2491                            let old_start_index = start_index;
2492                            start_index = *next_index;
2493                            if start_index <= old_start_index {
2494                                start_index = old_start_index + 1;
2495                            }
2496                            continue;
2497                        }
2498
2499                        let old_start_index = start_index;
2500                        start_index = *next_index;
2501                        if start_index <= old_start_index {
2502                            start_index = old_start_index + 1;
2503                        }
2504                        continue;
2505                    }
2506                };
2507
2508                // Get trim strategy
2509                let trim_spawn_segment = current_scene_graph_delta
2510                    .new_graph
2511                    .objects
2512                    .iter()
2513                    .find(|obj| obj.id == *trim_spawn_seg_id)
2514                    .ok_or_else(|| format!("Trim spawn segment {} not found", trim_spawn_seg_id.0))?;
2515
2516                let plan = match build_trim_plan(
2517                    *trim_spawn_seg_id,
2518                    *trim_spawn_coords,
2519                    trim_spawn_segment,
2520                    &terminations.left_side,
2521                    &terminations.right_side,
2522                    &current_scene_graph_delta.new_graph.objects,
2523                    default_unit,
2524                ) {
2525                    Ok(plan) => plan,
2526                    Err(e) => {
2527                        crate::logln!("Error determining trim strategy: {}", e);
2528                        let old_start_index = start_index;
2529                        start_index = *next_index;
2530                        if start_index <= old_start_index {
2531                            start_index = old_start_index + 1;
2532                        }
2533                        continue;
2534                    }
2535                };
2536                let strategy = lower_trim_plan(&plan);
2537
2538                // Keep processing the same trim polyline segment after geometry-changing ops.
2539                // This allows a single stroke to trim multiple intersected segments.
2540                let geometry_was_modified = trim_plan_modifies_geometry(&plan);
2541
2542                // Execute operations via callback
2543                match execute_operations(strategy, current_scene_graph_delta.clone()).await {
2544                    Ok((source_delta, scene_graph_delta)) => {
2545                        last_result = Some((source_delta, scene_graph_delta.clone()));
2546                        invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
2547                        current_scene_graph_delta = scene_graph_delta;
2548                    }
2549                    Err(e) => {
2550                        crate::logln!("Error executing trim operations: {}", e);
2551                        // Continue to next segment
2552                    }
2553                }
2554
2555                // Move to next segment
2556                let old_start_index = start_index;
2557                start_index = *next_index;
2558
2559                // Fail-safe: if start_index didn't advance, force it to advance
2560                if start_index <= old_start_index && !geometry_was_modified {
2561                    start_index = old_start_index + 1;
2562                }
2563            }
2564        }
2565    }
2566
2567    if iteration_count >= max_iterations {
2568        return Err(format!("Reached max iterations ({})", max_iterations));
2569    }
2570
2571    // Return the last result
2572    last_result.ok_or_else(|| "No trim operations were executed".to_string())
2573}
2574
2575/// Result of executing trim flow
2576#[cfg(test)]
2577#[derive(Debug, Clone)]
2578pub struct TrimFlowResult {
2579    pub kcl_code: String,
2580    pub invalidates_ids: bool,
2581}
2582
2583/// Execute a complete trim flow from KCL code to KCL code.
2584/// This is a high-level function that sets up the frontend state and executes the trim loop.
2585///
2586/// This function:
2587/// 1. Parses the input KCL code
2588/// 2. Sets up ExecutorContext and FrontendState
2589/// 3. Executes the initial code to get the scene graph
2590/// 4. Runs the trim loop using `execute_trim_loop`
2591/// 5. Returns the resulting KCL code
2592///
2593/// This is designed for testing and simple use cases. For more complex scenarios
2594/// (like WASM with batching), use `execute_trim_loop` directly with a custom callback.
2595///
2596/// Note: This function is only available for non-WASM builds (tests) and uses
2597/// a mock executor context so tests can run without an engine token.
2598#[cfg(all(not(target_arch = "wasm32"), test))]
2599pub(crate) async fn execute_trim_flow(
2600    kcl_code: &str,
2601    trim_points: &[Coords2d],
2602    sketch_id: ObjectId,
2603) -> Result<TrimFlowResult, String> {
2604    use crate::ExecutorContext;
2605    use crate::Program;
2606    use crate::execution::MockConfig;
2607    use crate::frontend::FrontendState;
2608    use crate::frontend::api::Version;
2609
2610    // Parse KCL code
2611    let parse_result = Program::parse(kcl_code).map_err(|e| format!("Failed to parse KCL: {}", e))?;
2612    let (program_opt, errors) = parse_result;
2613    if !errors.is_empty() {
2614        return Err(format!("Failed to parse KCL: {:?}", errors));
2615    }
2616    let program = program_opt.ok_or_else(|| "No AST produced".to_string())?;
2617
2618    let mock_ctx = ExecutorContext::new_mock(None).await;
2619
2620    // Use a guard to ensure context is closed even on error
2621    let result = async {
2622        let mut frontend = FrontendState::new();
2623
2624        // Set the program
2625        frontend.program = program.clone();
2626
2627        let exec_outcome = mock_ctx
2628            .run_mock(&program, &MockConfig::default())
2629            .await
2630            .map_err(|e| format!("Failed to execute program: {}", e.error.message()))?;
2631
2632        let exec_outcome = frontend.update_state_after_exec(exec_outcome, false);
2633        let mut initial_scene_graph = frontend.scene_graph.clone();
2634
2635        // If scene graph is empty, try to get objects from exec_outcome.scene_objects
2636        if initial_scene_graph.objects.is_empty() && !exec_outcome.scene_objects.is_empty() {
2637            initial_scene_graph.objects = exec_outcome.scene_objects.clone();
2638        }
2639
2640        // Get the sketch ID from the scene graph
2641        // First try sketch_mode, then try to find a sketch object, then fall back to provided sketch_id
2642        let actual_sketch_id = if let Some(sketch_mode) = initial_scene_graph.sketch_mode {
2643            sketch_mode
2644        } else {
2645            // Try to find a sketch object in the scene graph
2646            initial_scene_graph
2647                .objects
2648                .iter()
2649                .find(|obj| matches!(obj.kind, crate::frontend::api::ObjectKind::Sketch { .. }))
2650                .map(|obj| obj.id)
2651                .unwrap_or(sketch_id) // Fall back to provided sketch_id
2652        };
2653
2654        let version = Version(0);
2655        let initial_scene_graph_delta = crate::frontend::api::SceneGraphDelta {
2656            new_graph: initial_scene_graph,
2657            new_objects: vec![],
2658            invalidates_ids: false,
2659            exec_outcome,
2660        };
2661
2662        // Execute the trim loop with a callback that executes operations using SketchApi
2663        // We need to use a different approach since we can't easily capture mutable references in closures
2664        // Instead, we'll use a helper that takes the necessary parameters
2665        // Use mock_ctx for operations (SketchApi methods require mock context)
2666        let (source_delta, scene_graph_delta) = execute_trim_loop_with_context(
2667            trim_points,
2668            initial_scene_graph_delta,
2669            &mut frontend,
2670            &mock_ctx,
2671            version,
2672            actual_sketch_id,
2673        )
2674        .await?;
2675
2676        // Return the source delta text - this should contain the full updated KCL code
2677        // If it's empty, that means no operations were executed, which is an error
2678        if source_delta.text.is_empty() {
2679            return Err("No trim operations were executed - source delta is empty".to_string());
2680        }
2681
2682        Ok(TrimFlowResult {
2683            kcl_code: source_delta.text,
2684            invalidates_ids: scene_graph_delta.invalidates_ids,
2685        })
2686    }
2687    .await;
2688
2689    // Clean up context regardless of success or failure
2690    mock_ctx.close().await;
2691
2692    result
2693}
2694
2695/// Execute the trim loop with a context struct that provides access to FrontendState.
2696/// This is a convenience wrapper that inlines the loop to avoid borrow checker issues with closures.
2697/// The core loop logic is duplicated here, but this allows direct access to frontend and ctx.
2698///
2699/// Trim line points are expected in millimeters and are normalized to the current/default unit.
2700pub async fn execute_trim_loop_with_context(
2701    points: &[Coords2d],
2702    initial_scene_graph_delta: crate::frontend::api::SceneGraphDelta,
2703    frontend: &mut crate::frontend::FrontendState,
2704    ctx: &crate::ExecutorContext,
2705    version: crate::frontend::api::Version,
2706    sketch_id: ObjectId,
2707) -> Result<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta), String> {
2708    // Trim line points are expected in millimeters and normalized to the current unit here.
2709    let default_unit = frontend.default_length_unit();
2710    let normalized_points = normalize_trim_points_to_unit(points, default_unit);
2711
2712    // We inline the loop logic here to avoid borrow checker issues with closures capturing mutable references
2713    // This duplicates the loop from execute_trim_loop, but allows us to access frontend and ctx directly
2714    let mut current_scene_graph_delta = initial_scene_graph_delta.clone();
2715    let mut last_result: Option<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta)> = Some((
2716        crate::frontend::api::SourceDelta { text: String::new() },
2717        initial_scene_graph_delta.clone(),
2718    ));
2719    let mut invalidates_ids = false;
2720    let mut start_index = 0;
2721    let max_iterations = 1000;
2722    let mut iteration_count = 0;
2723    let circle_delete_fallback_strategy =
2724        |error: &str, segment_id: ObjectId, scene_objects: &[Object]| -> Option<Vec<TrimOperation>> {
2725            if !error.contains("No trim termination candidate found for circle") {
2726                return None;
2727            }
2728            let is_circle = scene_objects
2729                .iter()
2730                .find(|obj| obj.id == segment_id)
2731                .is_some_and(|obj| {
2732                    matches!(
2733                        obj.kind,
2734                        ObjectKind::Segment {
2735                            segment: Segment::Circle(_)
2736                        }
2737                    )
2738                });
2739            if is_circle {
2740                Some(vec![TrimOperation::SimpleTrim {
2741                    segment_to_trim_id: segment_id,
2742                }])
2743            } else {
2744                None
2745            }
2746        };
2747
2748    let points = normalized_points.as_slice();
2749
2750    while start_index < points.len().saturating_sub(1) && iteration_count < max_iterations {
2751        iteration_count += 1;
2752
2753        // Get next trim result
2754        let next_trim_spawn = get_next_trim_spawn(
2755            points,
2756            start_index,
2757            &current_scene_graph_delta.new_graph.objects,
2758            default_unit,
2759        );
2760
2761        match &next_trim_spawn {
2762            TrimItem::None { next_index } => {
2763                let old_start_index = start_index;
2764                start_index = *next_index;
2765                if start_index <= old_start_index {
2766                    start_index = old_start_index + 1;
2767                }
2768                if start_index >= points.len().saturating_sub(1) {
2769                    break;
2770                }
2771                continue;
2772            }
2773            TrimItem::Spawn {
2774                trim_spawn_seg_id,
2775                trim_spawn_coords,
2776                next_index,
2777                ..
2778            } => {
2779                // Get terminations
2780                let terminations = match get_trim_spawn_terminations(
2781                    *trim_spawn_seg_id,
2782                    points,
2783                    &current_scene_graph_delta.new_graph.objects,
2784                    default_unit,
2785                ) {
2786                    Ok(terms) => terms,
2787                    Err(e) => {
2788                        crate::logln!("Error getting trim spawn terminations: {}", e);
2789                        if let Some(strategy) = circle_delete_fallback_strategy(
2790                            &e,
2791                            *trim_spawn_seg_id,
2792                            &current_scene_graph_delta.new_graph.objects,
2793                        ) {
2794                            match execute_trim_operations_simple(
2795                                strategy.clone(),
2796                                &current_scene_graph_delta,
2797                                frontend,
2798                                ctx,
2799                                version,
2800                                sketch_id,
2801                            )
2802                            .await
2803                            {
2804                                Ok((source_delta, scene_graph_delta)) => {
2805                                    invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
2806                                    last_result = Some((source_delta, scene_graph_delta.clone()));
2807                                    current_scene_graph_delta = scene_graph_delta;
2808                                }
2809                                Err(exec_err) => {
2810                                    crate::logln!(
2811                                        "Error executing circle-delete fallback trim operation: {}",
2812                                        exec_err
2813                                    );
2814                                }
2815                            }
2816
2817                            let old_start_index = start_index;
2818                            start_index = *next_index;
2819                            if start_index <= old_start_index {
2820                                start_index = old_start_index + 1;
2821                            }
2822                            continue;
2823                        }
2824
2825                        let old_start_index = start_index;
2826                        start_index = *next_index;
2827                        if start_index <= old_start_index {
2828                            start_index = old_start_index + 1;
2829                        }
2830                        continue;
2831                    }
2832                };
2833
2834                // Get trim strategy
2835                let trim_spawn_segment = current_scene_graph_delta
2836                    .new_graph
2837                    .objects
2838                    .iter()
2839                    .find(|obj| obj.id == *trim_spawn_seg_id)
2840                    .ok_or_else(|| format!("Trim spawn segment {} not found", trim_spawn_seg_id.0))?;
2841
2842                let plan = match build_trim_plan(
2843                    *trim_spawn_seg_id,
2844                    *trim_spawn_coords,
2845                    trim_spawn_segment,
2846                    &terminations.left_side,
2847                    &terminations.right_side,
2848                    &current_scene_graph_delta.new_graph.objects,
2849                    default_unit,
2850                ) {
2851                    Ok(plan) => plan,
2852                    Err(e) => {
2853                        crate::logln!("Error determining trim strategy: {}", e);
2854                        let old_start_index = start_index;
2855                        start_index = *next_index;
2856                        if start_index <= old_start_index {
2857                            start_index = old_start_index + 1;
2858                        }
2859                        continue;
2860                    }
2861                };
2862                let strategy = lower_trim_plan(&plan);
2863
2864                // Keep processing the same trim polyline segment after geometry-changing ops.
2865                // This allows a single stroke to trim multiple intersected segments.
2866                let geometry_was_modified = trim_plan_modifies_geometry(&plan);
2867
2868                // Execute operations
2869                match execute_trim_operations_simple(
2870                    strategy.clone(),
2871                    &current_scene_graph_delta,
2872                    frontend,
2873                    ctx,
2874                    version,
2875                    sketch_id,
2876                )
2877                .await
2878                {
2879                    Ok((source_delta, scene_graph_delta)) => {
2880                        invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
2881                        last_result = Some((source_delta, scene_graph_delta.clone()));
2882                        current_scene_graph_delta = scene_graph_delta;
2883                    }
2884                    Err(e) => {
2885                        crate::logln!("Error executing trim operations: {}", e);
2886                    }
2887                }
2888
2889                // Move to next segment
2890                let old_start_index = start_index;
2891                start_index = *next_index;
2892                if start_index <= old_start_index && !geometry_was_modified {
2893                    start_index = old_start_index + 1;
2894                }
2895            }
2896        }
2897    }
2898
2899    if iteration_count >= max_iterations {
2900        return Err(format!("Reached max iterations ({})", max_iterations));
2901    }
2902
2903    let (source_delta, mut scene_graph_delta) =
2904        last_result.ok_or_else(|| "No trim operations were executed".to_string())?;
2905    // Set invalidates_ids if any operation invalidated IDs
2906    scene_graph_delta.invalidates_ids = invalidates_ids;
2907    Ok((source_delta, scene_graph_delta))
2908}
2909
2910/// Determine the trim strategy based on the terminations found on both sides
2911///
2912/// Once we have the termination of both sides, we have all the information we need to come up with a trim strategy.
2913/// In the below x is the trim spawn.
2914///
2915/// ## When both sides are the end of a segment
2916///
2917/// ```
2918/// o - -----x - -----o
2919/// ```
2920///
2921/// This is the simplest and we just delete the segment. This includes when the ends of the segment have
2922/// coincident constraints, as the delete API cascade deletes these constraints
2923///
2924/// ## When one side is the end of the segment and the other side is either an intersection or has another segment endpoint coincident with it
2925///
2926/// ```
2927///        /
2928/// -------/---x--o
2929///      /
2930/// ```
2931/// OR
2932/// ```
2933/// ----o---x---o
2934///    /
2935///   /
2936/// ```
2937///
2938/// In both of these cases, we need to edit one end of the segment to be the location of the
2939/// intersection/coincident point of this other segment though:
2940/// - If it's an intersection, we need to create a point-segment coincident constraint
2941/// ```
2942///        /
2943/// -------o
2944///      /
2945/// ```
2946/// - If it's a coincident endpoint, we need to create a point-point coincident constraint
2947///
2948/// ```
2949/// ----o
2950///    /
2951///   /
2952/// ```
2953///
2954/// ## When both sides are either intersections or coincident endpoints
2955///
2956/// ```
2957///        /
2958/// -------/---x----o------
2959///      /         |
2960/// ```
2961///
2962/// We need to split the segment in two, which basically means editing the existing segment to be one side
2963/// of the split, and adding a new segment for the other side of the split. And then there is lots of
2964/// complications around how to migrate constraints applied to each side of the segment, to list a couple
2965/// of considerations:
2966/// - Coincident constraints on either side need to be migrated to the correct side
2967/// - Angle based constraints (parallel, perpendicular, horizontal, vertical), need to be applied to both sides of the trim
2968/// - If the segment getting split is an arc, and there's a constraints applied to an arc's center, this should be applied to both arcs after they are split.
2969pub(crate) fn build_trim_plan(
2970    trim_spawn_id: ObjectId,
2971    trim_spawn_coords: Coords2d,
2972    trim_spawn_segment: &Object,
2973    left_side: &TrimTermination,
2974    right_side: &TrimTermination,
2975    objects: &[Object],
2976    default_unit: UnitLength,
2977) -> Result<TrimPlan, String> {
2978    // Simple trim: both sides are endpoints
2979    if matches!(left_side, TrimTermination::SegEndPoint { .. })
2980        && matches!(right_side, TrimTermination::SegEndPoint { .. })
2981    {
2982        return Ok(TrimPlan::DeleteSegment {
2983            segment_id: trim_spawn_id,
2984        });
2985    }
2986
2987    // Helper to check if a side is an intersection or coincident
2988    let is_intersect_or_coincident = |side: &TrimTermination| -> bool {
2989        matches!(
2990            side,
2991            TrimTermination::Intersection { .. }
2992                | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint { .. }
2993        )
2994    };
2995
2996    let left_side_needs_tail_cut = is_intersect_or_coincident(left_side) && !is_intersect_or_coincident(right_side);
2997    let right_side_needs_tail_cut = is_intersect_or_coincident(right_side) && !is_intersect_or_coincident(left_side);
2998
2999    // Validate trim spawn segment using native types
3000    let ObjectKind::Segment { segment } = &trim_spawn_segment.kind else {
3001        return Err("Trim spawn segment is not a segment".to_string());
3002    };
3003
3004    let (_segment_type, ctor) = match segment {
3005        Segment::Line(line) => ("Line", &line.ctor),
3006        Segment::Arc(arc) => ("Arc", &arc.ctor),
3007        Segment::Circle(circle) => ("Circle", &circle.ctor),
3008        _ => {
3009            return Err("Trim spawn segment is not a Line, Arc, or Circle".to_string());
3010        }
3011    };
3012
3013    // Extract units from the existing ctor's start point
3014    let units = match ctor {
3015        SegmentCtor::Line(line_ctor) => match &line_ctor.start.x {
3016            crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
3017            _ => NumericSuffix::Mm,
3018        },
3019        SegmentCtor::Arc(arc_ctor) => match &arc_ctor.start.x {
3020            crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
3021            _ => NumericSuffix::Mm,
3022        },
3023        SegmentCtor::Circle(circle_ctor) => match &circle_ctor.start.x {
3024            crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
3025            _ => NumericSuffix::Mm,
3026        },
3027        _ => NumericSuffix::Mm,
3028    };
3029
3030    // Helper to find distance constraints that reference a segment (via owned points)
3031    let find_distance_constraints_for_segment = |segment_id: ObjectId| -> Vec<ObjectId> {
3032        let mut constraint_ids = Vec::new();
3033        for obj in objects {
3034            let ObjectKind::Constraint { constraint } = &obj.kind else {
3035                continue;
3036            };
3037
3038            let Constraint::Distance(distance) = constraint else {
3039                continue;
3040            };
3041
3042            // Only delete distance constraints where BOTH points are owned by this segment.
3043            // Distance constraints that reference points on other segments should be preserved,
3044            // as they define relationships between this segment and other geometry that remain valid
3045            // even when this segment is trimmed. Only constraints that measure distances between
3046            // points on the same segment (e.g., segment length constraints) should be deleted.
3047            let points_owned_by_segment: Vec<bool> = distance
3048                .point_ids()
3049                .map(|point_id| {
3050                    if let Some(point_obj) = objects.iter().find(|o| o.id == point_id)
3051                        && let ObjectKind::Segment { segment } = &point_obj.kind
3052                        && let Segment::Point(point) = segment
3053                        && let Some(owner_id) = point.owner
3054                    {
3055                        return owner_id == segment_id;
3056                    }
3057                    false
3058                })
3059                .collect();
3060
3061            // Only include if ALL points are owned by this segment
3062            if points_owned_by_segment.len() == 2 && points_owned_by_segment.iter().all(|&owned| owned) {
3063                constraint_ids.push(obj.id);
3064            }
3065        }
3066        constraint_ids
3067    };
3068
3069    // Helper to find existing point-segment coincident constraint (using native types)
3070    let find_existing_point_segment_coincident =
3071        |trim_seg_id: ObjectId, intersecting_seg_id: ObjectId| -> CoincidentData {
3072            // If the intersecting id itself is a point, try a fast lookup using it directly
3073            let lookup_by_point_id = |point_id: ObjectId| -> Option<CoincidentData> {
3074                for obj in objects {
3075                    let ObjectKind::Constraint { constraint } = &obj.kind else {
3076                        continue;
3077                    };
3078
3079                    let Constraint::Coincident(coincident) = constraint else {
3080                        continue;
3081                    };
3082
3083                    let involves_trim_seg = coincident.segment_ids().any(|id| id == trim_seg_id || id == point_id);
3084                    let involves_point = coincident.contains_segment(point_id);
3085
3086                    if involves_trim_seg && involves_point {
3087                        return Some(CoincidentData {
3088                            intersecting_seg_id,
3089                            intersecting_endpoint_point_id: Some(point_id),
3090                            existing_point_segment_constraint_id: Some(obj.id),
3091                        });
3092                    }
3093                }
3094                None
3095            };
3096
3097            // Collect trim endpoints using native types
3098            let trim_seg = objects.iter().find(|obj| obj.id == trim_seg_id);
3099
3100            let mut trim_endpoint_ids: Vec<ObjectId> = Vec::new();
3101            if let Some(seg) = trim_seg
3102                && let ObjectKind::Segment { segment } = &seg.kind
3103            {
3104                match segment {
3105                    Segment::Line(line) => {
3106                        trim_endpoint_ids.push(line.start);
3107                        trim_endpoint_ids.push(line.end);
3108                    }
3109                    Segment::Arc(arc) => {
3110                        trim_endpoint_ids.push(arc.start);
3111                        trim_endpoint_ids.push(arc.end);
3112                    }
3113                    _ => {}
3114                }
3115            }
3116
3117            let intersecting_obj = objects.iter().find(|obj| obj.id == intersecting_seg_id);
3118
3119            if let Some(obj) = intersecting_obj
3120                && let ObjectKind::Segment { segment } = &obj.kind
3121                && let Segment::Point(_) = segment
3122                && let Some(found) = lookup_by_point_id(intersecting_seg_id)
3123            {
3124                return found;
3125            }
3126
3127            // Collect intersecting endpoint IDs using native types
3128            let mut intersecting_endpoint_ids: Vec<ObjectId> = Vec::new();
3129            if let Some(obj) = intersecting_obj
3130                && let ObjectKind::Segment { segment } = &obj.kind
3131            {
3132                match segment {
3133                    Segment::Line(line) => {
3134                        intersecting_endpoint_ids.push(line.start);
3135                        intersecting_endpoint_ids.push(line.end);
3136                    }
3137                    Segment::Arc(arc) => {
3138                        intersecting_endpoint_ids.push(arc.start);
3139                        intersecting_endpoint_ids.push(arc.end);
3140                    }
3141                    _ => {}
3142                }
3143            }
3144
3145            // Also include the intersecting_seg_id itself (it might already be a point id)
3146            intersecting_endpoint_ids.push(intersecting_seg_id);
3147
3148            // Search for constraints involving trim segment (or trim endpoints) and intersecting endpoints/points
3149            for obj in objects {
3150                let ObjectKind::Constraint { constraint } = &obj.kind else {
3151                    continue;
3152                };
3153
3154                let Constraint::Coincident(coincident) = constraint else {
3155                    continue;
3156                };
3157
3158                let constraint_segment_ids: Vec<ObjectId> = coincident.get_segments();
3159
3160                // Check if constraint involves the trim segment itself OR any trim endpoint
3161                let involves_trim_seg = constraint_segment_ids.contains(&trim_seg_id)
3162                    || trim_endpoint_ids.iter().any(|&id| constraint_segment_ids.contains(&id));
3163
3164                if !involves_trim_seg {
3165                    continue;
3166                }
3167
3168                // Check if any intersecting endpoint/point is involved
3169                if let Some(&intersecting_endpoint_id) = intersecting_endpoint_ids
3170                    .iter()
3171                    .find(|&&id| constraint_segment_ids.contains(&id))
3172                {
3173                    return CoincidentData {
3174                        intersecting_seg_id,
3175                        intersecting_endpoint_point_id: Some(intersecting_endpoint_id),
3176                        existing_point_segment_constraint_id: Some(obj.id),
3177                    };
3178                }
3179            }
3180
3181            // No existing constraint found
3182            CoincidentData {
3183                intersecting_seg_id,
3184                intersecting_endpoint_point_id: None,
3185                existing_point_segment_constraint_id: None,
3186            }
3187        };
3188
3189    // Helper to find point-segment coincident constraints on an endpoint (using native types)
3190    let find_point_segment_coincident_constraints = |endpoint_point_id: ObjectId| -> Vec<serde_json::Value> {
3191        let mut constraints: Vec<serde_json::Value> = Vec::new();
3192        for obj in objects {
3193            let ObjectKind::Constraint { constraint } = &obj.kind else {
3194                continue;
3195            };
3196
3197            let Constraint::Coincident(coincident) = constraint else {
3198                continue;
3199            };
3200
3201            // Check if this constraint involves the endpoint
3202            if !coincident.contains_segment(endpoint_point_id) {
3203                continue;
3204            }
3205
3206            // Find the other entity
3207            let other_segment_id = coincident.segment_ids().find(|&seg_id| seg_id != endpoint_point_id);
3208
3209            if let Some(other_id) = other_segment_id
3210                && let Some(other_obj) = objects.iter().find(|o| o.id == other_id)
3211            {
3212                // Check if other is a segment (not a point)
3213                if matches!(&other_obj.kind, ObjectKind::Segment { segment } if !matches!(segment, Segment::Point(_))) {
3214                    constraints.push(serde_json::json!({
3215                        "constraintId": obj.id.0,
3216                        "segmentOrPointId": other_id.0,
3217                    }));
3218                }
3219            }
3220        }
3221        constraints
3222    };
3223
3224    // Helper to find point-point coincident constraints on an endpoint (using native types)
3225    // Returns constraint IDs
3226    let find_point_point_coincident_constraints = |endpoint_point_id: ObjectId| -> Vec<ObjectId> {
3227        let mut constraint_ids = Vec::new();
3228        for obj in objects {
3229            let ObjectKind::Constraint { constraint } = &obj.kind else {
3230                continue;
3231            };
3232
3233            let Constraint::Coincident(coincident) = constraint else {
3234                continue;
3235            };
3236
3237            // Check if this constraint involves the endpoint
3238            if !coincident.contains_segment(endpoint_point_id) {
3239                continue;
3240            }
3241
3242            // Check if this is a point-point constraint (all segments are points)
3243            let is_point_point = coincident.segment_ids().all(|seg_id| {
3244                if let Some(seg_obj) = objects.iter().find(|o| o.id == seg_id) {
3245                    matches!(&seg_obj.kind, ObjectKind::Segment { segment } if matches!(segment, Segment::Point(_)))
3246                } else {
3247                    false
3248                }
3249            });
3250
3251            if is_point_point {
3252                constraint_ids.push(obj.id);
3253            }
3254        }
3255        constraint_ids
3256    };
3257
3258    // Helper to find point-segment coincident constraints on an endpoint (using native types)
3259    // Returns constraint IDs
3260    let find_point_segment_coincident_constraint_ids = |endpoint_point_id: ObjectId| -> Vec<ObjectId> {
3261        let mut constraint_ids = Vec::new();
3262        for obj in objects {
3263            let ObjectKind::Constraint { constraint } = &obj.kind else {
3264                continue;
3265            };
3266
3267            let Constraint::Coincident(coincident) = constraint else {
3268                continue;
3269            };
3270
3271            // Check if this constraint involves the endpoint
3272            if !coincident.contains_segment(endpoint_point_id) {
3273                continue;
3274            }
3275
3276            // Find the other entity
3277            let other_segment_id = coincident.segment_ids().find(|&seg_id| seg_id != endpoint_point_id);
3278
3279            if let Some(other_id) = other_segment_id
3280                && let Some(other_obj) = objects.iter().find(|o| o.id == other_id)
3281            {
3282                // Check if other is a segment (not a point) - this is a point-segment constraint
3283                if matches!(&other_obj.kind, ObjectKind::Segment { segment } if !matches!(segment, Segment::Point(_))) {
3284                    constraint_ids.push(obj.id);
3285                }
3286            }
3287        }
3288        constraint_ids
3289    };
3290
3291    let find_midpoint_constraints_for_segment = |segment_id: ObjectId| -> Vec<ObjectId> {
3292        objects
3293            .iter()
3294            .filter_map(|obj| {
3295                let ObjectKind::Constraint { constraint } = &obj.kind else {
3296                    return None;
3297                };
3298
3299                let Constraint::Midpoint(midpoint) = constraint else {
3300                    return None;
3301                };
3302
3303                (midpoint.segment == segment_id).then_some(obj.id)
3304            })
3305            .collect()
3306    };
3307
3308    // Cut tail: one side intersects, one is endpoint
3309    if left_side_needs_tail_cut || right_side_needs_tail_cut {
3310        let side = if left_side_needs_tail_cut {
3311            left_side
3312        } else {
3313            right_side
3314        };
3315
3316        let intersection_coords = match side {
3317            TrimTermination::Intersection {
3318                trim_termination_coords,
3319                ..
3320            }
3321            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3322                trim_termination_coords,
3323                ..
3324            } => *trim_termination_coords,
3325            TrimTermination::SegEndPoint { .. } => {
3326                return Err("Logic error: side should not be segEndPoint here".to_string());
3327            }
3328        };
3329
3330        let endpoint_to_change = if left_side_needs_tail_cut {
3331            EndpointChanged::End
3332        } else {
3333            EndpointChanged::Start
3334        };
3335
3336        let intersecting_seg_id = match side {
3337            TrimTermination::Intersection {
3338                intersecting_seg_id, ..
3339            }
3340            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3341                intersecting_seg_id, ..
3342            } => *intersecting_seg_id,
3343            TrimTermination::SegEndPoint { .. } => {
3344                return Err("Logic error".to_string());
3345            }
3346        };
3347
3348        let mut coincident_data = if matches!(
3349            side,
3350            TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint { .. }
3351        ) {
3352            let point_id = match side {
3353                TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3354                    other_segment_point_id, ..
3355                } => *other_segment_point_id,
3356                _ => return Err("Logic error".to_string()),
3357            };
3358            let mut data = find_existing_point_segment_coincident(trim_spawn_id, intersecting_seg_id);
3359            data.intersecting_endpoint_point_id = Some(point_id);
3360            data
3361        } else {
3362            find_existing_point_segment_coincident(trim_spawn_id, intersecting_seg_id)
3363        };
3364
3365        if matches!(side, TrimTermination::Intersection { .. })
3366            && let Some(point_id) = coincident_data.intersecting_endpoint_point_id
3367        {
3368            let endpoint_is_at_intersection = get_point_coords_from_native(objects, point_id, default_unit)
3369                .is_some_and(|point_coords| {
3370                    ((point_coords.x - intersection_coords.x).squared()
3371                        + (point_coords.y - intersection_coords.y).squared())
3372                    .sqrt()
3373                        <= EPSILON_POINT_ON_SEGMENT * 1000.0
3374                });
3375
3376            if !endpoint_is_at_intersection {
3377                coincident_data.existing_point_segment_constraint_id = None;
3378                coincident_data.intersecting_endpoint_point_id = None;
3379            }
3380        }
3381
3382        // Find the endpoint that will be trimmed using native types
3383        let trim_seg = objects.iter().find(|obj| obj.id == trim_spawn_id);
3384
3385        let endpoint_point_id = if let Some(seg) = trim_seg {
3386            let ObjectKind::Segment { segment } = &seg.kind else {
3387                return Err("Trim spawn segment is not a segment".to_string());
3388            };
3389            match segment {
3390                Segment::Line(line) => {
3391                    if endpoint_to_change == EndpointChanged::Start {
3392                        Some(line.start)
3393                    } else {
3394                        Some(line.end)
3395                    }
3396                }
3397                Segment::Arc(arc) => {
3398                    if endpoint_to_change == EndpointChanged::Start {
3399                        Some(arc.start)
3400                    } else {
3401                        Some(arc.end)
3402                    }
3403                }
3404                _ => None,
3405            }
3406        } else {
3407            None
3408        };
3409
3410        if let (Some(endpoint_id), Some(existing_constraint_id)) =
3411            (endpoint_point_id, coincident_data.existing_point_segment_constraint_id)
3412        {
3413            let constraint_involves_trimmed_endpoint = objects
3414                .iter()
3415                .find(|obj| obj.id == existing_constraint_id)
3416                .and_then(|obj| match &obj.kind {
3417                    ObjectKind::Constraint {
3418                        constraint: Constraint::Coincident(coincident),
3419                    } => Some(coincident.contains_segment(endpoint_id) || coincident.contains_segment(trim_spawn_id)),
3420                    _ => None,
3421                })
3422                .unwrap_or(false);
3423
3424            if !constraint_involves_trimmed_endpoint {
3425                coincident_data.existing_point_segment_constraint_id = None;
3426                coincident_data.intersecting_endpoint_point_id = None;
3427            }
3428        }
3429
3430        // Find point-point and point-segment constraints to delete
3431        let coincident_end_constraint_to_delete_ids = if let Some(point_id) = endpoint_point_id {
3432            let mut constraint_ids = find_point_point_coincident_constraints(point_id);
3433            // Also find point-segment constraints where the point is the endpoint being trimmed
3434            constraint_ids.extend(find_point_segment_coincident_constraint_ids(point_id));
3435            constraint_ids
3436        } else {
3437            Vec::new()
3438        };
3439
3440        let point_axis_constraint_ids_to_delete = if let Some(point_id) = endpoint_point_id {
3441            objects
3442                .iter()
3443                .filter_map(|obj| {
3444                    let ObjectKind::Constraint { constraint } = &obj.kind else {
3445                        return None;
3446                    };
3447
3448                    point_axis_constraint_references_point(constraint, point_id).then_some(obj.id)
3449                })
3450                .collect::<Vec<_>>()
3451        } else {
3452            Vec::new()
3453        };
3454
3455        // Edit the segment - create new ctor with updated endpoint
3456        let new_ctor = match ctor {
3457            SegmentCtor::Line(line_ctor) => {
3458                // Convert to segment units only; rounding happens at final conversion to output if needed.
3459                let new_point = crate::frontend::sketch::Point2d {
3460                    x: crate::frontend::api::Expr::Var(unit_to_number(intersection_coords.x, default_unit, units)),
3461                    y: crate::frontend::api::Expr::Var(unit_to_number(intersection_coords.y, default_unit, units)),
3462                };
3463                if endpoint_to_change == EndpointChanged::Start {
3464                    SegmentCtor::Line(crate::frontend::sketch::LineCtor {
3465                        start: new_point,
3466                        end: line_ctor.end.clone(),
3467                        construction: line_ctor.construction,
3468                    })
3469                } else {
3470                    SegmentCtor::Line(crate::frontend::sketch::LineCtor {
3471                        start: line_ctor.start.clone(),
3472                        end: new_point,
3473                        construction: line_ctor.construction,
3474                    })
3475                }
3476            }
3477            SegmentCtor::Arc(arc_ctor) => {
3478                // Convert to segment units only; rounding happens at final conversion to output if needed.
3479                let new_point = crate::frontend::sketch::Point2d {
3480                    x: crate::frontend::api::Expr::Var(unit_to_number(intersection_coords.x, default_unit, units)),
3481                    y: crate::frontend::api::Expr::Var(unit_to_number(intersection_coords.y, default_unit, units)),
3482                };
3483                if endpoint_to_change == EndpointChanged::Start {
3484                    SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
3485                        start: new_point,
3486                        end: arc_ctor.end.clone(),
3487                        center: arc_ctor.center.clone(),
3488                        construction: arc_ctor.construction,
3489                    })
3490                } else {
3491                    SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
3492                        start: arc_ctor.start.clone(),
3493                        end: new_point,
3494                        center: arc_ctor.center.clone(),
3495                        construction: arc_ctor.construction,
3496                    })
3497                }
3498            }
3499            _ => {
3500                return Err("Unsupported segment type for edit".to_string());
3501            }
3502        };
3503
3504        // Delete old constraints
3505        let mut all_constraint_ids_to_delete: Vec<ObjectId> = Vec::new();
3506        if let Some(constraint_id) = coincident_data.existing_point_segment_constraint_id {
3507            all_constraint_ids_to_delete.push(constraint_id);
3508        }
3509        all_constraint_ids_to_delete.extend(coincident_end_constraint_to_delete_ids);
3510        all_constraint_ids_to_delete.extend(point_axis_constraint_ids_to_delete);
3511        all_constraint_ids_to_delete.extend(find_midpoint_constraints_for_segment(trim_spawn_id));
3512
3513        // Delete distance constraints that reference this segment
3514        // When trimming an endpoint, the distance constraint no longer makes sense
3515        let distance_constraint_ids = find_distance_constraints_for_segment(trim_spawn_id);
3516        all_constraint_ids_to_delete.extend(distance_constraint_ids);
3517
3518        let coincident_target_id = coincident_data
3519            .intersecting_endpoint_point_id
3520            .unwrap_or(intersecting_seg_id);
3521        let adds_curved_segment_coincident = endpoint_point_id
3522            .is_some_and(|point_id| segment_id_is_or_is_owned_by_curve(objects, point_id))
3523            || segment_id_is_or_is_owned_by_curve(objects, coincident_target_id);
3524        let has_midpoint_deletions = all_constraint_ids_to_delete.iter().any(|constraint_id| {
3525            objects
3526                .iter()
3527                .find(|obj| obj.id == *constraint_id)
3528                .is_some_and(|object| {
3529                    matches!(
3530                        object.kind,
3531                        ObjectKind::Constraint {
3532                            constraint: Constraint::Midpoint(_)
3533                        }
3534                    )
3535                })
3536        });
3537
3538        let mut additional_edited_segment_ids = IndexSet::new();
3539        if has_midpoint_deletions || (adds_curved_segment_coincident && all_constraint_ids_to_delete.is_empty()) {
3540            additional_edited_segment_ids.extend(sketch_segment_ids_for_segment(objects, trim_spawn_id));
3541        }
3542
3543        if adds_curved_segment_coincident {
3544            for constraint_id in &all_constraint_ids_to_delete {
3545                let Some(constraint_object) = objects.iter().find(|obj| obj.id == *constraint_id) else {
3546                    continue;
3547                };
3548                let ObjectKind::Constraint {
3549                    constraint: Constraint::Coincident(coincident),
3550                } = &constraint_object.kind
3551                else {
3552                    continue;
3553                };
3554
3555                additional_edited_segment_ids.extend(
3556                    coincident
3557                        .segment_ids()
3558                        .map(|segment_id| owner_or_segment_id(objects, segment_id)),
3559                );
3560            }
3561        }
3562
3563        return Ok(TrimPlan::TailCut {
3564            segment_id: trim_spawn_id,
3565            endpoint_changed: endpoint_to_change,
3566            ctor: new_ctor,
3567            segment_or_point_to_make_coincident_to: intersecting_seg_id,
3568            intersecting_endpoint_point_id: coincident_data.intersecting_endpoint_point_id,
3569            constraint_ids_to_delete: all_constraint_ids_to_delete,
3570            additional_edited_segment_ids: additional_edited_segment_ids.into_iter().collect(),
3571        });
3572    }
3573
3574    // Circle trim: both sides must terminate on intersections/coincident points.
3575    // A circle cannot be "split" into two circles; it is converted into a single arc.
3576    if matches!(segment, Segment::Circle(_)) {
3577        let left_side_intersects = is_intersect_or_coincident(left_side);
3578        let right_side_intersects = is_intersect_or_coincident(right_side);
3579        if !(left_side_intersects && right_side_intersects) {
3580            return Err(format!(
3581                "Unsupported circle trim termination combination: left={:?} right={:?}",
3582                left_side, right_side
3583            ));
3584        }
3585
3586        let left_trim_coords = match left_side {
3587            TrimTermination::SegEndPoint {
3588                trim_termination_coords,
3589            }
3590            | TrimTermination::Intersection {
3591                trim_termination_coords,
3592                ..
3593            }
3594            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3595                trim_termination_coords,
3596                ..
3597            } => *trim_termination_coords,
3598        };
3599        let right_trim_coords = match right_side {
3600            TrimTermination::SegEndPoint {
3601                trim_termination_coords,
3602            }
3603            | TrimTermination::Intersection {
3604                trim_termination_coords,
3605                ..
3606            }
3607            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3608                trim_termination_coords,
3609                ..
3610            } => *trim_termination_coords,
3611        };
3612
3613        // If both sides resolve to essentially the same trim point (e.g., tangent-only hit),
3614        // deleting the circle matches expected trim behavior better than creating a zero-length arc.
3615        let trim_points_coincident = ((left_trim_coords.x - right_trim_coords.x)
3616            * (left_trim_coords.x - right_trim_coords.x)
3617            + (left_trim_coords.y - right_trim_coords.y) * (left_trim_coords.y - right_trim_coords.y))
3618            .sqrt()
3619            <= EPSILON_POINT_ON_SEGMENT * 10.0;
3620        if trim_points_coincident {
3621            return Ok(TrimPlan::DeleteSegment {
3622                segment_id: trim_spawn_id,
3623            });
3624        }
3625
3626        let circle_center_coords =
3627            get_position_coords_from_circle(trim_spawn_segment, CirclePoint::Center, objects, default_unit)
3628                .ok_or_else(|| {
3629                    format!(
3630                        "Could not get center coordinates for circle segment {}",
3631                        trim_spawn_id.0
3632                    )
3633                })?;
3634
3635        // The trim removes the side containing the trim spawn. Keep the opposite side.
3636        let spawn_on_left_to_right = is_point_on_arc(
3637            trim_spawn_coords,
3638            circle_center_coords,
3639            left_trim_coords,
3640            right_trim_coords,
3641            EPSILON_POINT_ON_SEGMENT,
3642        );
3643        let (arc_start_coords, arc_end_coords, arc_start_termination, arc_end_termination) = if spawn_on_left_to_right {
3644            (
3645                right_trim_coords,
3646                left_trim_coords,
3647                Box::new(right_side.clone()),
3648                Box::new(left_side.clone()),
3649            )
3650        } else {
3651            (
3652                left_trim_coords,
3653                right_trim_coords,
3654                Box::new(left_side.clone()),
3655                Box::new(right_side.clone()),
3656            )
3657        };
3658
3659        return Ok(TrimPlan::ReplaceCircleWithArc {
3660            circle_id: trim_spawn_id,
3661            arc_start_coords,
3662            arc_end_coords,
3663            arc_start_termination,
3664            arc_end_termination,
3665        });
3666    }
3667
3668    // Split segment: both sides intersect
3669    let left_side_intersects = is_intersect_or_coincident(left_side);
3670    let right_side_intersects = is_intersect_or_coincident(right_side);
3671
3672    if left_side_intersects && right_side_intersects {
3673        // This is the most complex case - split segment
3674        // Get coincident data for both sides
3675        let left_intersecting_seg_id = match left_side {
3676            TrimTermination::Intersection {
3677                intersecting_seg_id, ..
3678            }
3679            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3680                intersecting_seg_id, ..
3681            } => *intersecting_seg_id,
3682            TrimTermination::SegEndPoint { .. } => {
3683                return Err("Logic error: left side should not be segEndPoint".to_string());
3684            }
3685        };
3686
3687        let right_intersecting_seg_id = match right_side {
3688            TrimTermination::Intersection {
3689                intersecting_seg_id, ..
3690            }
3691            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3692                intersecting_seg_id, ..
3693            } => *intersecting_seg_id,
3694            TrimTermination::SegEndPoint { .. } => {
3695                return Err("Logic error: right side should not be segEndPoint".to_string());
3696            }
3697        };
3698
3699        let left_coincident_data = if matches!(
3700            left_side,
3701            TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint { .. }
3702        ) {
3703            let point_id = match left_side {
3704                TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3705                    other_segment_point_id, ..
3706                } => *other_segment_point_id,
3707                _ => return Err("Logic error".to_string()),
3708            };
3709            let mut data = find_existing_point_segment_coincident(trim_spawn_id, left_intersecting_seg_id);
3710            data.intersecting_endpoint_point_id = Some(point_id);
3711            data
3712        } else {
3713            find_existing_point_segment_coincident(trim_spawn_id, left_intersecting_seg_id)
3714        };
3715
3716        let right_coincident_data = if matches!(
3717            right_side,
3718            TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint { .. }
3719        ) {
3720            let point_id = match right_side {
3721                TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3722                    other_segment_point_id, ..
3723                } => *other_segment_point_id,
3724                _ => return Err("Logic error".to_string()),
3725            };
3726            let mut data = find_existing_point_segment_coincident(trim_spawn_id, right_intersecting_seg_id);
3727            data.intersecting_endpoint_point_id = Some(point_id);
3728            data
3729        } else {
3730            find_existing_point_segment_coincident(trim_spawn_id, right_intersecting_seg_id)
3731        };
3732
3733        // Find the endpoints of the segment being split using native types
3734        let (original_start_point_id, original_end_point_id) = match segment {
3735            Segment::Line(line) => (Some(line.start), Some(line.end)),
3736            Segment::Arc(arc) => (Some(arc.start), Some(arc.end)),
3737            _ => (None, None),
3738        };
3739
3740        // Get the original end point coordinates before editing using native types
3741        let original_end_point_coords = match segment {
3742            Segment::Line(_) => {
3743                get_position_coords_for_line(trim_spawn_segment, LineEndpoint::End, objects, default_unit)
3744            }
3745            Segment::Arc(_) => get_position_coords_from_arc(trim_spawn_segment, ArcPoint::End, objects, default_unit),
3746            _ => None,
3747        };
3748
3749        let Some(original_end_coords) = original_end_point_coords else {
3750            return Err(
3751                "Could not get original end point coordinates before editing - this is required for split trim"
3752                    .to_string(),
3753            );
3754        };
3755
3756        // Calculate trim coordinates for both sides
3757        let left_trim_coords = match left_side {
3758            TrimTermination::SegEndPoint {
3759                trim_termination_coords,
3760            }
3761            | TrimTermination::Intersection {
3762                trim_termination_coords,
3763                ..
3764            }
3765            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3766                trim_termination_coords,
3767                ..
3768            } => *trim_termination_coords,
3769        };
3770
3771        let right_trim_coords = match right_side {
3772            TrimTermination::SegEndPoint {
3773                trim_termination_coords,
3774            }
3775            | TrimTermination::Intersection {
3776                trim_termination_coords,
3777                ..
3778            }
3779            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
3780                trim_termination_coords,
3781                ..
3782            } => *trim_termination_coords,
3783        };
3784
3785        // Check if the split point is at the original end point
3786        let dist_to_original_end = ((right_trim_coords.x - original_end_coords.x)
3787            * (right_trim_coords.x - original_end_coords.x)
3788            + (right_trim_coords.y - original_end_coords.y) * (right_trim_coords.y - original_end_coords.y))
3789            .sqrt();
3790        if dist_to_original_end < EPSILON_POINT_ON_SEGMENT {
3791            return Err(
3792                "Split point is at original end point - this should be handled as cutTail, not split".to_string(),
3793            );
3794        }
3795
3796        // For now, implement a simplified version that creates the split operation
3797        // The full constraint migration logic is very complex and can be refined during testing
3798        let mut constraints_to_migrate: Vec<ConstraintToMigrate> = Vec::new();
3799        let mut constraints_to_delete_set: IndexSet<ObjectId> = IndexSet::new();
3800
3801        // Add existing point-segment constraints from terminations to delete list
3802        if let Some(constraint_id) = left_coincident_data.existing_point_segment_constraint_id {
3803            constraints_to_delete_set.insert(constraint_id);
3804        }
3805        if let Some(constraint_id) = right_coincident_data.existing_point_segment_constraint_id {
3806            constraints_to_delete_set.insert(constraint_id);
3807        }
3808
3809        if let Some(end_id) = original_end_point_id {
3810            for obj in objects {
3811                let ObjectKind::Constraint { constraint } = &obj.kind else {
3812                    continue;
3813                };
3814
3815                if point_axis_constraint_references_point(constraint, end_id) {
3816                    constraints_to_delete_set.insert(obj.id);
3817                }
3818            }
3819        }
3820
3821        // Find point-point constraints on end endpoint to migrate
3822        if let Some(end_id) = original_end_point_id {
3823            let end_point_point_constraint_ids = find_point_point_coincident_constraints(end_id);
3824            for constraint_id in end_point_point_constraint_ids {
3825                // Identify the other point in the coincident constraint
3826                let other_point_id_opt = objects.iter().find_map(|obj| {
3827                    if obj.id != constraint_id {
3828                        return None;
3829                    }
3830                    let ObjectKind::Constraint { constraint } = &obj.kind else {
3831                        return None;
3832                    };
3833                    let Constraint::Coincident(coincident) = constraint else {
3834                        return None;
3835                    };
3836                    coincident.segment_ids().find(|&seg_id| seg_id != end_id)
3837                });
3838
3839                if let Some(other_point_id) = other_point_id_opt {
3840                    constraints_to_delete_set.insert(constraint_id);
3841                    // Migrate as point-point constraint to the new end endpoint
3842                    constraints_to_migrate.push(ConstraintToMigrate {
3843                        constraint_id,
3844                        other_entity_id: other_point_id,
3845                        is_point_point: true,
3846                        attach_to_endpoint: AttachToEndpoint::End,
3847                    });
3848                }
3849            }
3850        }
3851
3852        // Find point-segment constraints on end endpoint to migrate
3853        if let Some(end_id) = original_end_point_id {
3854            let end_point_segment_constraints = find_point_segment_coincident_constraints(end_id);
3855            for constraint_json in end_point_segment_constraints {
3856                if let Some(constraint_id_usize) = constraint_json
3857                    .get("constraintId")
3858                    .and_then(|v| v.as_u64())
3859                    .map(|id| id as usize)
3860                {
3861                    let constraint_id = ObjectId(constraint_id_usize);
3862                    constraints_to_delete_set.insert(constraint_id);
3863                    // Add to migrate list (simplified)
3864                    if let Some(other_id_usize) = constraint_json
3865                        .get("segmentOrPointId")
3866                        .and_then(|v| v.as_u64())
3867                        .map(|id| id as usize)
3868                    {
3869                        constraints_to_migrate.push(ConstraintToMigrate {
3870                            constraint_id,
3871                            other_entity_id: ObjectId(other_id_usize),
3872                            is_point_point: false,
3873                            attach_to_endpoint: AttachToEndpoint::End,
3874                        });
3875                    }
3876                }
3877            }
3878        }
3879
3880        // Find point-segment constraints where the point is geometrically at the original end point
3881        // These should migrate to [newSegmentEndPointId, pointId] (point-point), not [pointId, newSegmentId] (point-segment)
3882        // We need to find these by checking all point-segment constraints involving the segment ID
3883        // and checking if the point is at the original end point
3884        if let Some(end_id) = original_end_point_id {
3885            for obj in objects {
3886                let ObjectKind::Constraint { constraint } = &obj.kind else {
3887                    continue;
3888                };
3889
3890                let Constraint::Coincident(coincident) = constraint else {
3891                    continue;
3892                };
3893
3894                // Only consider constraints that involve the segment ID but NOT the endpoint IDs directly
3895                // Note: We want to find constraints like [pointId, segmentId] where pointId is a point
3896                // that happens to be at the endpoint geometrically, but the constraint doesn't reference
3897                // the endpoint ID directly
3898                if !coincident.contains_segment(trim_spawn_id) {
3899                    continue;
3900                }
3901                // Skip constraints that involve endpoint IDs directly (those are handled by endpoint constraint migration)
3902                // But we still want to find constraints where a point (not an endpoint ID) is at the endpoint
3903                if let (Some(start_id), Some(end_id_val)) = (original_start_point_id, Some(end_id))
3904                    && coincident.segment_ids().any(|id| id == start_id || id == end_id_val)
3905                {
3906                    continue; // Skip constraints that involve endpoint IDs directly
3907                }
3908
3909                // Find the other entity (should be a point)
3910                let other_id = coincident.segment_ids().find(|&seg_id| seg_id != trim_spawn_id);
3911
3912                if let Some(other_id) = other_id {
3913                    // Check if the other entity is a point
3914                    if let Some(other_obj) = objects.iter().find(|o| o.id == other_id) {
3915                        let ObjectKind::Segment { segment: other_segment } = &other_obj.kind else {
3916                            continue;
3917                        };
3918
3919                        let Segment::Point(point) = other_segment else {
3920                            continue;
3921                        };
3922
3923                        // Get point coordinates in the trim internal unit
3924                        let point_coords = Coords2d {
3925                            x: number_to_unit(&point.position.x, default_unit),
3926                            y: number_to_unit(&point.position.y, default_unit),
3927                        };
3928
3929                        // Check if point is at original end point (geometrically)
3930                        // Use post-solve coordinates for original end point if available, otherwise use the coordinates we have
3931                        let original_end_point_post_solve_coords = if let Some(end_id) = original_end_point_id {
3932                            if let Some(end_point_obj) = objects.iter().find(|o| o.id == end_id) {
3933                                if let ObjectKind::Segment {
3934                                    segment: Segment::Point(end_point),
3935                                } = &end_point_obj.kind
3936                                {
3937                                    Some(Coords2d {
3938                                        x: number_to_unit(&end_point.position.x, default_unit),
3939                                        y: number_to_unit(&end_point.position.y, default_unit),
3940                                    })
3941                                } else {
3942                                    None
3943                                }
3944                            } else {
3945                                None
3946                            }
3947                        } else {
3948                            None
3949                        };
3950
3951                        let reference_coords = original_end_point_post_solve_coords.unwrap_or(original_end_coords);
3952                        let dist_to_original_end = ((point_coords.x - reference_coords.x)
3953                            * (point_coords.x - reference_coords.x)
3954                            + (point_coords.y - reference_coords.y) * (point_coords.y - reference_coords.y))
3955                            .sqrt();
3956
3957                        if dist_to_original_end < EPSILON_POINT_ON_SEGMENT {
3958                            // Point is at the original end point - migrate as point-point constraint
3959                            // Check if there's already a point-point constraint between this point and the original end point
3960                            let has_point_point_constraint = find_point_point_coincident_constraints(end_id)
3961                                .iter()
3962                                .any(|&constraint_id| {
3963                                    if let Some(constraint_obj) = objects.iter().find(|o| o.id == constraint_id) {
3964                                        if let ObjectKind::Constraint {
3965                                            constraint: Constraint::Coincident(coincident),
3966                                        } = &constraint_obj.kind
3967                                        {
3968                                            coincident.contains_segment(other_id)
3969                                        } else {
3970                                            false
3971                                        }
3972                                    } else {
3973                                        false
3974                                    }
3975                                });
3976
3977                            if !has_point_point_constraint {
3978                                // No existing point-point constraint - migrate as point-point constraint
3979                                constraints_to_migrate.push(ConstraintToMigrate {
3980                                    constraint_id: obj.id,
3981                                    other_entity_id: other_id,
3982                                    is_point_point: true, // Convert to point-point constraint
3983                                    attach_to_endpoint: AttachToEndpoint::End, // Attach to new segment's end
3984                                });
3985                            }
3986                            // Always delete the old point-segment constraint (whether we migrate or not)
3987                            constraints_to_delete_set.insert(obj.id);
3988                        }
3989                    }
3990                }
3991            }
3992        }
3993
3994        // Find point-segment constraints on the segment body (not at endpoints)
3995        // These are constraints [pointId, segmentId] where the point is on the segment body
3996        // They should be migrated to [pointId, newSegmentId] if the point is after the split point
3997        let split_point = right_trim_coords; // Use right trim coords as split point
3998        let segment_start_coords = match segment {
3999            Segment::Line(_) => {
4000                get_position_coords_for_line(trim_spawn_segment, LineEndpoint::Start, objects, default_unit)
4001            }
4002            Segment::Arc(_) => get_position_coords_from_arc(trim_spawn_segment, ArcPoint::Start, objects, default_unit),
4003            _ => None,
4004        };
4005        let segment_end_coords = match segment {
4006            Segment::Line(_) => {
4007                get_position_coords_for_line(trim_spawn_segment, LineEndpoint::End, objects, default_unit)
4008            }
4009            Segment::Arc(_) => get_position_coords_from_arc(trim_spawn_segment, ArcPoint::End, objects, default_unit),
4010            _ => None,
4011        };
4012        let segment_center_coords = match segment {
4013            Segment::Line(_) => None,
4014            Segment::Arc(_) => {
4015                get_position_coords_from_arc(trim_spawn_segment, ArcPoint::Center, objects, default_unit)
4016            }
4017            _ => None,
4018        };
4019
4020        if let (Some(start_coords), Some(end_coords)) = (segment_start_coords, segment_end_coords) {
4021            // Calculate split point parametric position
4022            let split_point_t_opt = match segment {
4023                Segment::Line(_) => Some(project_point_onto_segment(split_point, start_coords, end_coords)),
4024                Segment::Arc(_) => segment_center_coords
4025                    .map(|center| project_point_onto_arc(split_point, center, start_coords, end_coords)),
4026                _ => None,
4027            };
4028
4029            if let Some(split_point_t) = split_point_t_opt {
4030                // Find all coincident constraints involving the segment
4031                for obj in objects {
4032                    let ObjectKind::Constraint { constraint } = &obj.kind else {
4033                        continue;
4034                    };
4035
4036                    let Constraint::Coincident(coincident) = constraint else {
4037                        continue;
4038                    };
4039
4040                    // Check if constraint involves the segment being split
4041                    if !coincident.contains_segment(trim_spawn_id) {
4042                        continue;
4043                    }
4044
4045                    // Skip if constraint also involves endpoint IDs directly (those are handled separately)
4046                    if let (Some(start_id), Some(end_id)) = (original_start_point_id, original_end_point_id)
4047                        && coincident.segment_ids().any(|id| id == start_id || id == end_id)
4048                    {
4049                        continue;
4050                    }
4051
4052                    // Find the other entity in the constraint
4053                    let other_id = coincident.segment_ids().find(|&seg_id| seg_id != trim_spawn_id);
4054
4055                    if let Some(other_id) = other_id {
4056                        // Check if the other entity is a point
4057                        if let Some(other_obj) = objects.iter().find(|o| o.id == other_id) {
4058                            let ObjectKind::Segment { segment: other_segment } = &other_obj.kind else {
4059                                continue;
4060                            };
4061
4062                            let Segment::Point(point) = other_segment else {
4063                                continue;
4064                            };
4065
4066                            // Get point coordinates in the trim internal unit
4067                            let point_coords = Coords2d {
4068                                x: number_to_unit(&point.position.x, default_unit),
4069                                y: number_to_unit(&point.position.y, default_unit),
4070                            };
4071
4072                            // Project the point onto the segment to get its parametric position
4073                            let point_t = match segment {
4074                                Segment::Line(_) => project_point_onto_segment(point_coords, start_coords, end_coords),
4075                                Segment::Arc(_) => {
4076                                    if let Some(center) = segment_center_coords {
4077                                        project_point_onto_arc(point_coords, center, start_coords, end_coords)
4078                                    } else {
4079                                        continue; // Skip this constraint if no center
4080                                    }
4081                                }
4082                                _ => continue, // Skip non-line/arc segments
4083                            };
4084
4085                            // Check if point is at the original end point (skip if so - already handled above)
4086                            // Use post-solve coordinates for original end point if available
4087                            let original_end_point_post_solve_coords = if let Some(end_id) = original_end_point_id {
4088                                if let Some(end_point_obj) = objects.iter().find(|o| o.id == end_id) {
4089                                    if let ObjectKind::Segment {
4090                                        segment: Segment::Point(end_point),
4091                                    } = &end_point_obj.kind
4092                                    {
4093                                        Some(Coords2d {
4094                                            x: number_to_unit(&end_point.position.x, default_unit),
4095                                            y: number_to_unit(&end_point.position.y, default_unit),
4096                                        })
4097                                    } else {
4098                                        None
4099                                    }
4100                                } else {
4101                                    None
4102                                }
4103                            } else {
4104                                None
4105                            };
4106
4107                            let reference_coords = original_end_point_post_solve_coords.unwrap_or(original_end_coords);
4108                            let dist_to_original_end = ((point_coords.x - reference_coords.x)
4109                                * (point_coords.x - reference_coords.x)
4110                                + (point_coords.y - reference_coords.y) * (point_coords.y - reference_coords.y))
4111                                .sqrt();
4112
4113                            if dist_to_original_end < EPSILON_POINT_ON_SEGMENT {
4114                                // This should have been handled in the first loop, but if we find it here,
4115                                // make sure it's deleted (it might have been missed due to filtering)
4116                                // Also check if we should migrate it as point-point constraint
4117                                let has_point_point_constraint = if let Some(end_id) = original_end_point_id {
4118                                    find_point_point_coincident_constraints(end_id)
4119                                        .iter()
4120                                        .any(|&constraint_id| {
4121                                            if let Some(constraint_obj) = objects.iter().find(|o| o.id == constraint_id)
4122                                            {
4123                                                if let ObjectKind::Constraint {
4124                                                    constraint: Constraint::Coincident(coincident),
4125                                                } = &constraint_obj.kind
4126                                                {
4127                                                    coincident.contains_segment(other_id)
4128                                                } else {
4129                                                    false
4130                                                }
4131                                            } else {
4132                                                false
4133                                            }
4134                                        })
4135                                } else {
4136                                    false
4137                                };
4138
4139                                if !has_point_point_constraint {
4140                                    // No existing point-point constraint - migrate as point-point constraint
4141                                    constraints_to_migrate.push(ConstraintToMigrate {
4142                                        constraint_id: obj.id,
4143                                        other_entity_id: other_id,
4144                                        is_point_point: true, // Convert to point-point constraint
4145                                        attach_to_endpoint: AttachToEndpoint::End, // Attach to new segment's end
4146                                    });
4147                                }
4148                                // Always delete the old point-segment constraint
4149                                constraints_to_delete_set.insert(obj.id);
4150                                continue; // Already handled as point-point constraint migration above
4151                            }
4152
4153                            // Check if point is at the current start endpoint (skip if so - handled separately)
4154                            let dist_to_start = ((point_coords.x - start_coords.x) * (point_coords.x - start_coords.x)
4155                                + (point_coords.y - start_coords.y) * (point_coords.y - start_coords.y))
4156                                .sqrt();
4157                            let is_at_start = (point_t - 0.0).abs() < EPSILON_POINT_ON_SEGMENT
4158                                || dist_to_start < EPSILON_POINT_ON_SEGMENT;
4159
4160                            if is_at_start {
4161                                continue; // Handled by endpoint constraint migration
4162                            }
4163
4164                            // Check if point is at the split point (don't migrate - would pull halves together)
4165                            let dist_to_split = (point_t - split_point_t).abs();
4166                            if dist_to_split < EPSILON_POINT_ON_SEGMENT * 100.0 {
4167                                continue; // Too close to split point
4168                            }
4169
4170                            // If point is after split point (closer to end), migrate to new segment
4171                            if point_t > split_point_t {
4172                                constraints_to_migrate.push(ConstraintToMigrate {
4173                                    constraint_id: obj.id,
4174                                    other_entity_id: other_id,
4175                                    is_point_point: false, // Keep as point-segment, but replace the segment
4176                                    attach_to_endpoint: AttachToEndpoint::Segment, // Replace old segment with new segment
4177                                });
4178                                constraints_to_delete_set.insert(obj.id);
4179                            }
4180                        }
4181                    }
4182                }
4183            } // End of if let Some(split_point_t)
4184        } // End of if let (Some(start_coords), Some(end_coords))
4185
4186        // Find distance constraints that reference the segment being split
4187        // These need to be deleted and re-added with new endpoints after split
4188        // BUT: For arcs, we need to exclude distance constraints that reference the center point
4189        // (those will be migrated separately in the execution code)
4190        let distance_constraint_ids_for_split = find_distance_constraints_for_segment(trim_spawn_id);
4191
4192        // Get the center point ID if this is an arc, so we can exclude center point constraints
4193        let arc_center_point_id: Option<ObjectId> = match segment {
4194            Segment::Arc(arc) => Some(arc.center),
4195            _ => None,
4196        };
4197
4198        for constraint_id in distance_constraint_ids_for_split {
4199            // Skip if this is a center point constraint for an arc (will be migrated separately)
4200            if let Some(center_id) = arc_center_point_id {
4201                // Check if this constraint references the center point
4202                if let Some(constraint_obj) = objects.iter().find(|o| o.id == constraint_id)
4203                    && let ObjectKind::Constraint { constraint } = &constraint_obj.kind
4204                    && let Constraint::Distance(distance) = constraint
4205                    && distance.contains_point(center_id)
4206                {
4207                    // This is a center point constraint - skip deletion, it will be migrated
4208                    continue;
4209                }
4210            }
4211
4212            constraints_to_delete_set.insert(constraint_id);
4213        }
4214
4215        // Midpoint constraints become stale after trim changes the owning
4216        // segment's extent, so delete them instead of migrating them.
4217        for obj in objects {
4218            let ObjectKind::Constraint { constraint } = &obj.kind else {
4219                continue;
4220            };
4221
4222            let Constraint::Midpoint(midpoint) = constraint else {
4223                continue;
4224            };
4225
4226            let references_trimmed_segment = midpoint.segment == trim_spawn_id;
4227            let references_trimmed_endpoint = original_start_point_id.is_some_and(|id| midpoint.point == id)
4228                || original_end_point_id.is_some_and(|id| midpoint.point == id);
4229
4230            if references_trimmed_segment || references_trimmed_endpoint {
4231                constraints_to_delete_set.insert(obj.id);
4232            }
4233        }
4234
4235        // Find angle constraints (Parallel, Perpendicular, Horizontal, Vertical) that reference the segment being split
4236        // Note: We don't delete these - they still apply to the original (trimmed) segment
4237        // We'll add new constraints for the new segment in the execution code
4238
4239        // Catch-all: Find any remaining point-segment constraints involving the segment
4240        // that we might have missed (e.g., due to coordinate precision issues)
4241        // This ensures we don't leave orphaned constraints
4242        for obj in objects {
4243            let ObjectKind::Constraint { constraint } = &obj.kind else {
4244                continue;
4245            };
4246
4247            let Constraint::Coincident(coincident) = constraint else {
4248                continue;
4249            };
4250
4251            // Only consider constraints that involve the segment ID
4252            if !coincident.contains_segment(trim_spawn_id) {
4253                continue;
4254            }
4255
4256            // Skip if already marked for deletion
4257            if constraints_to_delete_set.contains(&obj.id) {
4258                continue;
4259            }
4260
4261            // Skip if this constraint involves an endpoint directly (handled separately)
4262            // BUT: if the other entity is a point that's at the original end point geometrically,
4263            // we still want to handle it here even if it's not the same point object
4264            // So we'll check this after we verify the other entity is a point and check its coordinates
4265
4266            // Find the other entity (should be a point)
4267            let other_id = coincident.segment_ids().find(|&seg_id| seg_id != trim_spawn_id);
4268
4269            if let Some(other_id) = other_id {
4270                // Check if the other entity is a point
4271                if let Some(other_obj) = objects.iter().find(|o| o.id == other_id) {
4272                    let ObjectKind::Segment { segment: other_segment } = &other_obj.kind else {
4273                        continue;
4274                    };
4275
4276                    let Segment::Point(point) = other_segment else {
4277                        continue;
4278                    };
4279
4280                    // Skip if this constraint involves an endpoint directly (handled separately)
4281                    // BUT: if the point is at the original end point geometrically, we still want to handle it
4282                    let _is_endpoint_constraint =
4283                        if let (Some(start_id), Some(end_id)) = (original_start_point_id, original_end_point_id) {
4284                            coincident.segment_ids().any(|id| id == start_id || id == end_id)
4285                        } else {
4286                            false
4287                        };
4288
4289                    // Get point coordinates in the trim internal unit
4290                    let point_coords = Coords2d {
4291                        x: number_to_unit(&point.position.x, default_unit),
4292                        y: number_to_unit(&point.position.y, default_unit),
4293                    };
4294
4295                    // Check if point is at original end point (with relaxed tolerance for catch-all)
4296                    let original_end_point_post_solve_coords = if let Some(end_id) = original_end_point_id {
4297                        if let Some(end_point_obj) = objects.iter().find(|o| o.id == end_id) {
4298                            if let ObjectKind::Segment {
4299                                segment: Segment::Point(end_point),
4300                            } = &end_point_obj.kind
4301                            {
4302                                Some(Coords2d {
4303                                    x: number_to_unit(&end_point.position.x, default_unit),
4304                                    y: number_to_unit(&end_point.position.y, default_unit),
4305                                })
4306                            } else {
4307                                None
4308                            }
4309                        } else {
4310                            None
4311                        }
4312                    } else {
4313                        None
4314                    };
4315
4316                    let reference_coords = original_end_point_post_solve_coords.unwrap_or(original_end_coords);
4317                    let dist_to_original_end = ((point_coords.x - reference_coords.x)
4318                        * (point_coords.x - reference_coords.x)
4319                        + (point_coords.y - reference_coords.y) * (point_coords.y - reference_coords.y))
4320                        .sqrt();
4321
4322                    // Use a slightly more relaxed tolerance for catch-all to catch edge cases
4323                    // Also handle endpoint constraints that might have been missed
4324                    let is_at_original_end = dist_to_original_end < EPSILON_POINT_ON_SEGMENT * 2.0;
4325
4326                    if is_at_original_end {
4327                        // Point is at or very close to original end point - delete the constraint
4328                        // Check if we should migrate it as point-point constraint
4329                        let has_point_point_constraint = if let Some(end_id) = original_end_point_id {
4330                            find_point_point_coincident_constraints(end_id)
4331                                .iter()
4332                                .any(|&constraint_id| {
4333                                    if let Some(constraint_obj) = objects.iter().find(|o| o.id == constraint_id) {
4334                                        if let ObjectKind::Constraint {
4335                                            constraint: Constraint::Coincident(coincident),
4336                                        } = &constraint_obj.kind
4337                                        {
4338                                            coincident.contains_segment(other_id)
4339                                        } else {
4340                                            false
4341                                        }
4342                                    } else {
4343                                        false
4344                                    }
4345                                })
4346                        } else {
4347                            false
4348                        };
4349
4350                        if !has_point_point_constraint {
4351                            // No existing point-point constraint - migrate as point-point constraint
4352                            constraints_to_migrate.push(ConstraintToMigrate {
4353                                constraint_id: obj.id,
4354                                other_entity_id: other_id,
4355                                is_point_point: true, // Convert to point-point constraint
4356                                attach_to_endpoint: AttachToEndpoint::End, // Attach to new segment's end
4357                            });
4358                        }
4359                        // Always delete the old point-segment constraint
4360                        constraints_to_delete_set.insert(obj.id);
4361                    }
4362                }
4363            }
4364        }
4365
4366        // Create split segment operation
4367        let constraints_to_delete: Vec<ObjectId> = constraints_to_delete_set.iter().copied().collect();
4368        let plan = TrimPlan::SplitSegment {
4369            segment_id: trim_spawn_id,
4370            left_trim_coords,
4371            right_trim_coords,
4372            original_end_coords,
4373            left_side: Box::new(left_side.clone()),
4374            right_side: Box::new(right_side.clone()),
4375            left_side_coincident_data: CoincidentData {
4376                intersecting_seg_id: left_intersecting_seg_id,
4377                intersecting_endpoint_point_id: left_coincident_data.intersecting_endpoint_point_id,
4378                existing_point_segment_constraint_id: left_coincident_data.existing_point_segment_constraint_id,
4379            },
4380            right_side_coincident_data: CoincidentData {
4381                intersecting_seg_id: right_intersecting_seg_id,
4382                intersecting_endpoint_point_id: right_coincident_data.intersecting_endpoint_point_id,
4383                existing_point_segment_constraint_id: right_coincident_data.existing_point_segment_constraint_id,
4384            },
4385            constraints_to_migrate,
4386            constraints_to_delete,
4387        };
4388
4389        return Ok(plan);
4390    }
4391
4392    // Only three strategy cases should exist: simple trim (endpoint/endpoint),
4393    // tail cut (intersection+endpoint), or split (intersection+intersection).
4394    // If we get here, trim termination pairing was unexpected or a new variant
4395    // was added without updating the strategy mapping.
4396    Err(format!(
4397        "Unsupported trim termination combination: left={:?} right={:?}",
4398        left_side, right_side
4399    ))
4400}
4401
4402/// Execute the trim operations determined by the trim strategy
4403///
4404/// Once we have a trim strategy, it then needs to be executed. This function is separate just to keep
4405/// one phase just collecting info (`build_trim_plan` + `lower_trim_plan`), and the other actually mutating things.
4406///
4407/// This function takes the list of trim operations from `lower_trim_plan` and executes them, which may include:
4408/// - Deleting segments (SimpleTrim)
4409/// - Editing segment endpoints (EditSegment)
4410/// - Adding coincident constraints (AddCoincidentConstraint)
4411/// - Splitting segments (SplitSegment)
4412/// - Migrating constraints (MigrateConstraint)
4413pub(crate) async fn execute_trim_operations_simple(
4414    strategy: Vec<TrimOperation>,
4415    current_scene_graph_delta: &crate::frontend::api::SceneGraphDelta,
4416    frontend: &mut crate::frontend::FrontendState,
4417    ctx: &crate::ExecutorContext,
4418    version: crate::frontend::api::Version,
4419    sketch_id: ObjectId,
4420) -> Result<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta), String> {
4421    use crate::frontend::SketchApi;
4422    use crate::frontend::sketch::Constraint;
4423    use crate::frontend::sketch::ExistingSegmentCtor;
4424    use crate::frontend::sketch::SegmentCtor;
4425
4426    let default_unit = frontend.default_length_unit();
4427
4428    let mut op_index = 0;
4429    let mut last_result: Option<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta)> = None;
4430    let mut invalidates_ids = false;
4431
4432    while op_index < strategy.len() {
4433        let mut consumed_ops = 1;
4434        let operation_result = match &strategy[op_index] {
4435            TrimOperation::SimpleTrim { segment_to_trim_id } => {
4436                // Delete the segment
4437                frontend
4438                    .delete_objects(
4439                        ctx,
4440                        version,
4441                        sketch_id,
4442                        Vec::new(),                // constraint_ids
4443                        vec![*segment_to_trim_id], // segment_ids
4444                    )
4445                    .await
4446                    .map_err(|e| format!("Failed to delete segment: {}", e.error.message()))
4447            }
4448            TrimOperation::EditSegment {
4449                segment_id,
4450                ctor,
4451                endpoint_changed,
4452                additional_edited_segment_ids,
4453            } => {
4454                // Try to batch tail-cut sequence: EditSegment + AddCoincidentConstraint (+ DeleteConstraints)
4455                // This matches the batching logic in kcl-wasm-lib/src/api.rs
4456                if op_index + 1 < strategy.len() {
4457                    if let TrimOperation::AddCoincidentConstraint {
4458                        segment_id: coincident_seg_id,
4459                        endpoint_changed: coincident_endpoint_changed,
4460                        segment_or_point_to_make_coincident_to,
4461                        intersecting_endpoint_point_id,
4462                    } = &strategy[op_index + 1]
4463                    {
4464                        if segment_id == coincident_seg_id && endpoint_changed == coincident_endpoint_changed {
4465                            // This is a tail-cut sequence - batch it!
4466                            let mut delete_constraint_ids: Vec<ObjectId> = Vec::new();
4467                            consumed_ops = 2;
4468
4469                            if op_index + 2 < strategy.len()
4470                                && let TrimOperation::DeleteConstraints { constraint_ids } = &strategy[op_index + 2]
4471                            {
4472                                delete_constraint_ids = constraint_ids.to_vec();
4473                                consumed_ops = 3;
4474                            }
4475
4476                            // Use ctor directly
4477                            let segment_ctor = ctor.clone();
4478
4479                            // Get endpoint point id from current scene graph (IDs stay the same after edit)
4480                            let edited_segment = current_scene_graph_delta
4481                                .new_graph
4482                                .objects
4483                                .iter()
4484                                .find(|obj| obj.id == *segment_id)
4485                                .ok_or_else(|| format!("Failed to find segment {} for tail-cut batch", segment_id.0))?;
4486
4487                            let endpoint_point_id = match &edited_segment.kind {
4488                                crate::frontend::api::ObjectKind::Segment { segment } => match segment {
4489                                    crate::frontend::sketch::Segment::Line(line) => {
4490                                        if *endpoint_changed == EndpointChanged::Start {
4491                                            line.start
4492                                        } else {
4493                                            line.end
4494                                        }
4495                                    }
4496                                    crate::frontend::sketch::Segment::Arc(arc) => {
4497                                        if *endpoint_changed == EndpointChanged::Start {
4498                                            arc.start
4499                                        } else {
4500                                            arc.end
4501                                        }
4502                                    }
4503                                    _ => {
4504                                        return Err("Unsupported segment type for tail-cut batch".to_string());
4505                                    }
4506                                },
4507                                _ => {
4508                                    return Err("Edited object is not a segment (tail-cut batch)".to_string());
4509                                }
4510                            };
4511
4512                            let coincident_segments = if let Some(point_id) = intersecting_endpoint_point_id {
4513                                vec![endpoint_point_id.into(), (*point_id).into()]
4514                            } else {
4515                                vec![
4516                                    endpoint_point_id.into(),
4517                                    (*segment_or_point_to_make_coincident_to).into(),
4518                                ]
4519                            };
4520
4521                            let constraint = Constraint::Coincident(crate::frontend::sketch::Coincident {
4522                                segments: coincident_segments,
4523                            });
4524
4525                            let segment_to_edit = ExistingSegmentCtor {
4526                                id: *segment_id,
4527                                ctor: segment_ctor,
4528                            };
4529
4530                            // Batch the operations - this is the key optimization!
4531                            // Note: consumed_ops is set above (2 or 3), and we'll use it after the match
4532                            frontend
4533                                .batch_tail_cut_operations(
4534                                    ctx,
4535                                    version,
4536                                    sketch_id,
4537                                    vec![segment_to_edit],
4538                                    vec![constraint],
4539                                    delete_constraint_ids,
4540                                    additional_edited_segment_ids.clone(),
4541                                )
4542                                .await
4543                                .map_err(|e| format!("Failed to batch tail-cut operations: {}", e.error.message()))
4544                        } else {
4545                            // Not same segment/endpoint - execute EditSegment normally
4546                            let segment_to_edit = ExistingSegmentCtor {
4547                                id: *segment_id,
4548                                ctor: ctor.clone(),
4549                            };
4550
4551                            frontend
4552                                .edit_segments(ctx, version, sketch_id, vec![segment_to_edit])
4553                                .await
4554                                .map_err(|e| format!("Failed to edit segment: {}", e.error.message()))
4555                        }
4556                    } else {
4557                        // Not followed by AddCoincidentConstraint - execute EditSegment normally
4558                        let segment_to_edit = ExistingSegmentCtor {
4559                            id: *segment_id,
4560                            ctor: ctor.clone(),
4561                        };
4562
4563                        frontend
4564                            .edit_segments(ctx, version, sketch_id, vec![segment_to_edit])
4565                            .await
4566                            .map_err(|e| format!("Failed to edit segment: {}", e.error.message()))
4567                    }
4568                } else {
4569                    // No following op to batch with - execute EditSegment normally
4570                    let segment_to_edit = ExistingSegmentCtor {
4571                        id: *segment_id,
4572                        ctor: ctor.clone(),
4573                    };
4574
4575                    frontend
4576                        .edit_segments(ctx, version, sketch_id, vec![segment_to_edit])
4577                        .await
4578                        .map_err(|e| format!("Failed to edit segment: {}", e.error.message()))
4579                }
4580            }
4581            TrimOperation::AddCoincidentConstraint {
4582                segment_id,
4583                endpoint_changed,
4584                segment_or_point_to_make_coincident_to,
4585                intersecting_endpoint_point_id,
4586            } => {
4587                // Find the edited segment to get the endpoint point ID
4588                let edited_segment = current_scene_graph_delta
4589                    .new_graph
4590                    .objects
4591                    .iter()
4592                    .find(|obj| obj.id == *segment_id)
4593                    .ok_or_else(|| format!("Failed to find edited segment {}", segment_id.0))?;
4594
4595                // Get the endpoint ID after editing
4596                let new_segment_endpoint_point_id = match &edited_segment.kind {
4597                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
4598                        crate::frontend::sketch::Segment::Line(line) => {
4599                            if *endpoint_changed == EndpointChanged::Start {
4600                                line.start
4601                            } else {
4602                                line.end
4603                            }
4604                        }
4605                        crate::frontend::sketch::Segment::Arc(arc) => {
4606                            if *endpoint_changed == EndpointChanged::Start {
4607                                arc.start
4608                            } else {
4609                                arc.end
4610                            }
4611                        }
4612                        _ => {
4613                            return Err("Unsupported segment type for addCoincidentConstraint".to_string());
4614                        }
4615                    },
4616                    _ => {
4617                        return Err("Edited object is not a segment".to_string());
4618                    }
4619                };
4620
4621                // Determine coincident segments
4622                let coincident_segments = if let Some(point_id) = intersecting_endpoint_point_id {
4623                    vec![new_segment_endpoint_point_id.into(), (*point_id).into()]
4624                } else {
4625                    vec![
4626                        new_segment_endpoint_point_id.into(),
4627                        (*segment_or_point_to_make_coincident_to).into(),
4628                    ]
4629                };
4630
4631                let constraint = Constraint::Coincident(crate::frontend::sketch::Coincident {
4632                    segments: coincident_segments,
4633                });
4634
4635                frontend
4636                    .add_constraint(ctx, version, sketch_id, constraint)
4637                    .await
4638                    .map_err(|e| format!("Failed to add constraint: {}", e.error.message()))
4639            }
4640            TrimOperation::DeleteConstraints { constraint_ids } => {
4641                // Delete constraints
4642                let constraint_object_ids: Vec<ObjectId> = constraint_ids.to_vec();
4643
4644                frontend
4645                    .delete_objects(
4646                        ctx,
4647                        version,
4648                        sketch_id,
4649                        constraint_object_ids,
4650                        Vec::new(), // segment_ids
4651                    )
4652                    .await
4653                    .map_err(|e| format!("Failed to delete constraints: {}", e.error.message()))
4654            }
4655            TrimOperation::ReplaceCircleWithArc {
4656                circle_id,
4657                arc_start_coords,
4658                arc_end_coords,
4659                arc_start_termination,
4660                arc_end_termination,
4661            } => {
4662                // Replace a circle with a single arc and re-attach coincident constraints.
4663                let original_circle = current_scene_graph_delta
4664                    .new_graph
4665                    .objects
4666                    .iter()
4667                    .find(|obj| obj.id == *circle_id)
4668                    .ok_or_else(|| format!("Failed to find original circle {}", circle_id.0))?;
4669
4670                let (original_circle_start_id, original_circle_center_id, circle_ctor) = match &original_circle.kind {
4671                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
4672                        crate::frontend::sketch::Segment::Circle(circle) => match &circle.ctor {
4673                            SegmentCtor::Circle(circle_ctor) => (circle.start, circle.center, circle_ctor.clone()),
4674                            _ => return Err("Circle does not have a Circle ctor".to_string()),
4675                        },
4676                        _ => return Err("Original segment is not a circle".to_string()),
4677                    },
4678                    _ => return Err("Original object is not a segment".to_string()),
4679                };
4680
4681                let units = match &circle_ctor.start.x {
4682                    crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
4683                    _ => crate::pretty::NumericSuffix::Mm,
4684                };
4685
4686                let coords_to_point_expr = |coords: Coords2d| crate::frontend::sketch::Point2d {
4687                    x: crate::frontend::api::Expr::Var(unit_to_number(coords.x, default_unit, units)),
4688                    y: crate::frontend::api::Expr::Var(unit_to_number(coords.y, default_unit, units)),
4689                };
4690
4691                let arc_ctor = SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
4692                    start: coords_to_point_expr(*arc_start_coords),
4693                    end: coords_to_point_expr(*arc_end_coords),
4694                    center: circle_ctor.center.clone(),
4695                    construction: circle_ctor.construction,
4696                });
4697
4698                let (_add_source_delta, add_scene_graph_delta) = frontend
4699                    .add_segment(ctx, version, sketch_id, arc_ctor, None)
4700                    .await
4701                    .map_err(|e| format!("Failed to add arc while replacing circle: {}", e.error.message()))?;
4702                invalidates_ids = invalidates_ids || add_scene_graph_delta.invalidates_ids;
4703
4704                let new_arc_id = *add_scene_graph_delta
4705                    .new_objects
4706                    .iter()
4707                    .find(|&id| {
4708                        add_scene_graph_delta
4709                            .new_graph
4710                            .objects
4711                            .iter()
4712                            .find(|o| o.id == *id)
4713                            .is_some_and(|obj| {
4714                                matches!(
4715                                    &obj.kind,
4716                                    crate::frontend::api::ObjectKind::Segment { segment }
4717                                        if matches!(segment, crate::frontend::sketch::Segment::Arc(_))
4718                                )
4719                            })
4720                    })
4721                    .ok_or_else(|| "Failed to find newly created arc segment".to_string())?;
4722
4723                let new_arc_obj = add_scene_graph_delta
4724                    .new_graph
4725                    .objects
4726                    .iter()
4727                    .find(|obj| obj.id == new_arc_id)
4728                    .ok_or_else(|| format!("New arc segment not found {}", new_arc_id.0))?;
4729                let (new_arc_start_id, new_arc_end_id, new_arc_center_id) = match &new_arc_obj.kind {
4730                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
4731                        crate::frontend::sketch::Segment::Arc(arc) => (arc.start, arc.end, arc.center),
4732                        _ => return Err("New segment is not an arc".to_string()),
4733                    },
4734                    _ => return Err("New arc object is not a segment".to_string()),
4735                };
4736
4737                let constraint_segments_for =
4738                    |arc_endpoint_id: ObjectId,
4739                     term: &TrimTermination|
4740                     -> Result<Vec<crate::frontend::sketch::ConstraintSegment>, String> {
4741                        match term {
4742                            TrimTermination::Intersection {
4743                                intersecting_seg_id, ..
4744                            } => Ok(vec![arc_endpoint_id.into(), (*intersecting_seg_id).into()]),
4745                            TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
4746                                other_segment_point_id,
4747                                ..
4748                            } => Ok(vec![arc_endpoint_id.into(), (*other_segment_point_id).into()]),
4749                            TrimTermination::SegEndPoint { .. } => {
4750                                Err("Circle replacement endpoint cannot terminate at seg endpoint".to_string())
4751                            }
4752                        }
4753                    };
4754
4755                let start_constraint = Constraint::Coincident(crate::frontend::sketch::Coincident {
4756                    segments: constraint_segments_for(new_arc_start_id, arc_start_termination)?,
4757                });
4758                let (_c1_source_delta, c1_scene_graph_delta) = frontend
4759                    .add_constraint(ctx, version, sketch_id, start_constraint)
4760                    .await
4761                    .map_err(|e| format!("Failed to add start coincident on replaced arc: {}", e.error.message()))?;
4762                invalidates_ids = invalidates_ids || c1_scene_graph_delta.invalidates_ids;
4763
4764                let end_constraint = Constraint::Coincident(crate::frontend::sketch::Coincident {
4765                    segments: constraint_segments_for(new_arc_end_id, arc_end_termination)?,
4766                });
4767                let (_c2_source_delta, c2_scene_graph_delta) = frontend
4768                    .add_constraint(ctx, version, sketch_id, end_constraint)
4769                    .await
4770                    .map_err(|e| format!("Failed to add end coincident on replaced arc: {}", e.error.message()))?;
4771                invalidates_ids = invalidates_ids || c2_scene_graph_delta.invalidates_ids;
4772
4773                let mut termination_point_ids: Vec<ObjectId> = Vec::new();
4774                for term in [arc_start_termination, arc_end_termination] {
4775                    if let TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
4776                        other_segment_point_id,
4777                        ..
4778                    } = term.as_ref()
4779                    {
4780                        termination_point_ids.push(*other_segment_point_id);
4781                    }
4782                }
4783
4784                // Migrate constraints that reference the original circle segment or points.
4785                // This preserves authored constraints (e.g. radius/tangent/coincident) when
4786                // a trim converts a circle into an arc.
4787                let rewrite_map = std::collections::HashMap::from([
4788                    (*circle_id, new_arc_id),
4789                    (original_circle_center_id, new_arc_center_id),
4790                    (original_circle_start_id, new_arc_start_id),
4791                ]);
4792                let rewrite_ids: std::collections::HashSet<ObjectId> = rewrite_map.keys().copied().collect();
4793
4794                let mut migrated_constraints: Vec<Constraint> = Vec::new();
4795                for obj in &current_scene_graph_delta.new_graph.objects {
4796                    let crate::frontend::api::ObjectKind::Constraint { constraint } = &obj.kind else {
4797                        continue;
4798                    };
4799
4800                    // Keep this exhaustive so new constraints must declare how
4801                    // circle-to-arc trim should migrate or ignore them.
4802                    match constraint {
4803                        Constraint::Coincident(coincident) => {
4804                            if !constraint_segments_reference_any(&coincident.segments, &rewrite_ids) {
4805                                continue;
4806                            }
4807
4808                            // If the original coincident is circle<->point for a point that is
4809                            // already used as a trim termination, endpoint coincident constraints
4810                            // already preserve that relationship.
4811                            if coincident.contains_segment(*circle_id)
4812                                && coincident
4813                                    .segment_ids()
4814                                    .filter(|id| *id != *circle_id)
4815                                    .any(|id| termination_point_ids.contains(&id))
4816                            {
4817                                continue;
4818                            }
4819
4820                            let Some(Constraint::Coincident(migrated_coincident)) =
4821                                rewrite_constraint_with_map(constraint, &rewrite_map)
4822                            else {
4823                                continue;
4824                            };
4825
4826                            // Skip redundant migration when a previous point-segment circle
4827                            // coincident would become point-segment arc coincident at an arc
4828                            // endpoint that is already handled by explicit endpoint constraints.
4829                            let migrated_ids: Vec<ObjectId> = migrated_coincident
4830                                .segments
4831                                .iter()
4832                                .filter_map(|segment| match segment {
4833                                    crate::frontend::sketch::ConstraintSegment::Segment(id) => Some(*id),
4834                                    crate::frontend::sketch::ConstraintSegment::Origin(_) => None,
4835                                })
4836                                .collect();
4837                            if migrated_ids.contains(&new_arc_id)
4838                                && (migrated_ids.contains(&new_arc_start_id) || migrated_ids.contains(&new_arc_end_id))
4839                            {
4840                                continue;
4841                            }
4842
4843                            migrated_constraints.push(Constraint::Coincident(migrated_coincident));
4844                        }
4845                        Constraint::Distance(distance) => {
4846                            if !constraint_segments_reference_any(&distance.points, &rewrite_ids) {
4847                                continue;
4848                            }
4849                            if let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map) {
4850                                migrated_constraints.push(migrated);
4851                            }
4852                        }
4853                        Constraint::HorizontalDistance(distance) => {
4854                            if !constraint_segments_reference_any(&distance.points, &rewrite_ids) {
4855                                continue;
4856                            }
4857                            if let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map) {
4858                                migrated_constraints.push(migrated);
4859                            }
4860                        }
4861                        Constraint::VerticalDistance(distance) => {
4862                            if !constraint_segments_reference_any(&distance.points, &rewrite_ids) {
4863                                continue;
4864                            }
4865                            if let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map) {
4866                                migrated_constraints.push(migrated);
4867                            }
4868                        }
4869                        Constraint::Radius(radius) => {
4870                            if radius.arc == *circle_id
4871                                && let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map)
4872                            {
4873                                migrated_constraints.push(migrated);
4874                            }
4875                        }
4876                        Constraint::Diameter(diameter) => {
4877                            if diameter.arc == *circle_id
4878                                && let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map)
4879                            {
4880                                migrated_constraints.push(migrated);
4881                            }
4882                        }
4883                        Constraint::EqualRadius(equal_radius) => {
4884                            if equal_radius.input.contains(circle_id)
4885                                && let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map)
4886                            {
4887                                migrated_constraints.push(migrated);
4888                            }
4889                        }
4890                        Constraint::Tangent(tangent) => {
4891                            if tangent.input.contains(circle_id)
4892                                && let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map)
4893                            {
4894                                migrated_constraints.push(migrated);
4895                            }
4896                        }
4897                        Constraint::Angle(_)
4898                        | Constraint::Fixed(_)
4899                        | Constraint::Horizontal(_)
4900                        | Constraint::LinesEqualLength(_)
4901                        | Constraint::Midpoint(_)
4902                        | Constraint::Parallel(_)
4903                        | Constraint::Perpendicular(_)
4904                        | Constraint::Symmetric(_)
4905                        | Constraint::Vertical(_) => {}
4906                    }
4907                }
4908
4909                for constraint in migrated_constraints {
4910                    let (_source_delta, migrated_scene_graph_delta) = frontend
4911                        .add_constraint(ctx, version, sketch_id, constraint)
4912                        .await
4913                        .map_err(|e| format!("Failed to migrate circle constraint to arc: {}", e.error.message()))?;
4914                    invalidates_ids = invalidates_ids || migrated_scene_graph_delta.invalidates_ids;
4915                }
4916
4917                frontend
4918                    .delete_objects(ctx, version, sketch_id, Vec::new(), vec![*circle_id])
4919                    .await
4920                    .map_err(|e| format!("Failed to delete circle after arc replacement: {}", e.error.message()))
4921            }
4922            TrimOperation::SplitSegment {
4923                segment_id,
4924                left_trim_coords,
4925                right_trim_coords,
4926                original_end_coords,
4927                left_side,
4928                right_side,
4929                constraints_to_migrate,
4930                constraints_to_delete,
4931                ..
4932            } => {
4933                // SplitSegment is a complex multi-step operation
4934                // Ported from kcl-wasm-lib/src/api.rs execute_trim function
4935
4936                // Step 1: Find and validate original segment
4937                let original_segment = current_scene_graph_delta
4938                    .new_graph
4939                    .objects
4940                    .iter()
4941                    .find(|obj| obj.id == *segment_id)
4942                    .ok_or_else(|| format!("Failed to find original segment {}", segment_id.0))?;
4943
4944                // Extract point IDs from original segment
4945                let (original_segment_start_point_id, original_segment_end_point_id, original_segment_center_point_id) =
4946                    match &original_segment.kind {
4947                        crate::frontend::api::ObjectKind::Segment { segment } => match segment {
4948                            crate::frontend::sketch::Segment::Line(line) => (Some(line.start), Some(line.end), None),
4949                            crate::frontend::sketch::Segment::Arc(arc) => {
4950                                (Some(arc.start), Some(arc.end), Some(arc.center))
4951                            }
4952                            _ => (None, None, None),
4953                        },
4954                        _ => (None, None, None),
4955                    };
4956
4957                // Store center point constraints to migrate BEFORE edit_segments modifies the scene graph
4958                let mut center_point_constraints_to_migrate: Vec<(Constraint, ObjectId)> = Vec::new();
4959                if let Some(original_center_id) = original_segment_center_point_id {
4960                    for obj in &current_scene_graph_delta.new_graph.objects {
4961                        let crate::frontend::api::ObjectKind::Constraint { constraint } = &obj.kind else {
4962                            continue;
4963                        };
4964
4965                        // Find coincident constraints that reference the original center point
4966                        if let Constraint::Coincident(coincident) = constraint
4967                            && coincident.contains_segment(original_center_id)
4968                        {
4969                            center_point_constraints_to_migrate.push((constraint.clone(), original_center_id));
4970                        }
4971
4972                        // Find distance constraints that reference the original center point
4973                        if let Constraint::Distance(distance) = constraint
4974                            && distance.contains_point(original_center_id)
4975                        {
4976                            center_point_constraints_to_migrate.push((constraint.clone(), original_center_id));
4977                        }
4978                    }
4979                }
4980
4981                // Extract segment and ctor
4982                let (_segment_type, original_ctor) = match &original_segment.kind {
4983                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
4984                        crate::frontend::sketch::Segment::Line(line) => ("Line", line.ctor.clone()),
4985                        crate::frontend::sketch::Segment::Arc(arc) => ("Arc", arc.ctor.clone()),
4986                        _ => {
4987                            return Err("Original segment is not a Line or Arc".to_string());
4988                        }
4989                    },
4990                    _ => {
4991                        return Err("Original object is not a segment".to_string());
4992                    }
4993                };
4994
4995                // Extract units from the existing ctor
4996                let units = match &original_ctor {
4997                    SegmentCtor::Line(line_ctor) => match &line_ctor.start.x {
4998                        crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
4999                        _ => crate::pretty::NumericSuffix::Mm,
5000                    },
5001                    SegmentCtor::Arc(arc_ctor) => match &arc_ctor.start.x {
5002                        crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
5003                        _ => crate::pretty::NumericSuffix::Mm,
5004                    },
5005                    _ => crate::pretty::NumericSuffix::Mm,
5006                };
5007
5008                // Helper to convert Coords2d (current trim unit) to Point2d in segment units.
5009                // No rounding here; rounding happens at final conversion to output if needed.
5010                let coords_to_point =
5011                    |coords: Coords2d| -> crate::frontend::sketch::Point2d<crate::frontend::api::Number> {
5012                        crate::frontend::sketch::Point2d {
5013                            x: unit_to_number(coords.x, default_unit, units),
5014                            y: unit_to_number(coords.y, default_unit, units),
5015                        }
5016                    };
5017
5018                // Convert Point2d<Number> to Point2d<Expr> for SegmentCtor
5019                let point_to_expr = |point: crate::frontend::sketch::Point2d<crate::frontend::api::Number>| -> crate::frontend::sketch::Point2d<crate::frontend::api::Expr> {
5020                    crate::frontend::sketch::Point2d {
5021                        x: crate::frontend::api::Expr::Var(point.x),
5022                        y: crate::frontend::api::Expr::Var(point.y),
5023                    }
5024                };
5025
5026                // Step 2: Create new segment (right side) first to get its IDs
5027                let new_segment_ctor = match &original_ctor {
5028                    SegmentCtor::Line(line_ctor) => SegmentCtor::Line(crate::frontend::sketch::LineCtor {
5029                        start: point_to_expr(coords_to_point(*right_trim_coords)),
5030                        end: point_to_expr(coords_to_point(*original_end_coords)),
5031                        construction: line_ctor.construction,
5032                    }),
5033                    SegmentCtor::Arc(arc_ctor) => SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
5034                        start: point_to_expr(coords_to_point(*right_trim_coords)),
5035                        end: point_to_expr(coords_to_point(*original_end_coords)),
5036                        center: arc_ctor.center.clone(),
5037                        construction: arc_ctor.construction,
5038                    }),
5039                    _ => {
5040                        return Err("Unsupported segment type for new segment".to_string());
5041                    }
5042                };
5043
5044                let (_add_source_delta, add_scene_graph_delta) = frontend
5045                    .add_segment(ctx, version, sketch_id, new_segment_ctor, None)
5046                    .await
5047                    .map_err(|e| format!("Failed to add new segment: {}", e.error.message()))?;
5048
5049                // Step 3: Find the newly created segment
5050                let new_segment_id = *add_scene_graph_delta
5051                    .new_objects
5052                    .iter()
5053                    .find(|&id| {
5054                        if let Some(obj) = add_scene_graph_delta.new_graph.objects.iter().find(|o| o.id == *id) {
5055                            matches!(
5056                                &obj.kind,
5057                                crate::frontend::api::ObjectKind::Segment { segment }
5058                                    if matches!(segment, crate::frontend::sketch::Segment::Line(_) | crate::frontend::sketch::Segment::Arc(_))
5059                            )
5060                        } else {
5061                            false
5062                        }
5063                    })
5064                    .ok_or_else(|| "Failed to find newly created segment".to_string())?;
5065
5066                let new_segment = add_scene_graph_delta
5067                    .new_graph
5068                    .objects
5069                    .iter()
5070                    .find(|o| o.id == new_segment_id)
5071                    .ok_or_else(|| format!("New segment not found with id {}", new_segment_id.0))?;
5072
5073                // Extract endpoint IDs
5074                let (new_segment_start_point_id, new_segment_end_point_id, new_segment_center_point_id) =
5075                    match &new_segment.kind {
5076                        crate::frontend::api::ObjectKind::Segment { segment } => match segment {
5077                            crate::frontend::sketch::Segment::Line(line) => (line.start, line.end, None),
5078                            crate::frontend::sketch::Segment::Arc(arc) => (arc.start, arc.end, Some(arc.center)),
5079                            _ => {
5080                                return Err("New segment is not a Line or Arc".to_string());
5081                            }
5082                        },
5083                        _ => {
5084                            return Err("New segment is not a segment".to_string());
5085                        }
5086                    };
5087
5088                // Step 4: Edit the original segment (trim left side)
5089                let edited_ctor = match &original_ctor {
5090                    SegmentCtor::Line(line_ctor) => SegmentCtor::Line(crate::frontend::sketch::LineCtor {
5091                        start: line_ctor.start.clone(),
5092                        end: point_to_expr(coords_to_point(*left_trim_coords)),
5093                        construction: line_ctor.construction,
5094                    }),
5095                    SegmentCtor::Arc(arc_ctor) => SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
5096                        start: arc_ctor.start.clone(),
5097                        end: point_to_expr(coords_to_point(*left_trim_coords)),
5098                        center: arc_ctor.center.clone(),
5099                        construction: arc_ctor.construction,
5100                    }),
5101                    _ => {
5102                        return Err("Unsupported segment type for split".to_string());
5103                    }
5104                };
5105
5106                let (_edit_source_delta, edit_scene_graph_delta) = frontend
5107                    .edit_segments(
5108                        ctx,
5109                        version,
5110                        sketch_id,
5111                        vec![ExistingSegmentCtor {
5112                            id: *segment_id,
5113                            ctor: edited_ctor,
5114                        }],
5115                    )
5116                    .await
5117                    .map_err(|e| format!("Failed to edit segment: {}", e.error.message()))?;
5118                // Track invalidates_ids from edit_segments call
5119                invalidates_ids = invalidates_ids || edit_scene_graph_delta.invalidates_ids;
5120
5121                // Get left endpoint ID from edited segment
5122                let edited_segment = edit_scene_graph_delta
5123                    .new_graph
5124                    .objects
5125                    .iter()
5126                    .find(|obj| obj.id == *segment_id)
5127                    .ok_or_else(|| format!("Failed to find edited segment {}", segment_id.0))?;
5128
5129                let left_side_endpoint_point_id = match &edited_segment.kind {
5130                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
5131                        crate::frontend::sketch::Segment::Line(line) => line.end,
5132                        crate::frontend::sketch::Segment::Arc(arc) => arc.end,
5133                        _ => {
5134                            return Err("Edited segment is not a Line or Arc".to_string());
5135                        }
5136                    },
5137                    _ => {
5138                        return Err("Edited segment is not a segment".to_string());
5139                    }
5140                };
5141
5142                // Step 5: Prepare constraints for batch
5143                let mut batch_constraints = Vec::new();
5144
5145                // Left constraint
5146                let left_intersecting_seg_id = match &**left_side {
5147                    TrimTermination::Intersection {
5148                        intersecting_seg_id, ..
5149                    }
5150                    | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
5151                        intersecting_seg_id, ..
5152                    } => *intersecting_seg_id,
5153                    _ => {
5154                        return Err("Left side is not an intersection or coincident".to_string());
5155                    }
5156                };
5157                let left_coincident_segments = match &**left_side {
5158                    TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
5159                        other_segment_point_id,
5160                        ..
5161                    } => {
5162                        vec![left_side_endpoint_point_id.into(), (*other_segment_point_id).into()]
5163                    }
5164                    _ => {
5165                        vec![left_side_endpoint_point_id.into(), left_intersecting_seg_id.into()]
5166                    }
5167                };
5168                batch_constraints.push(Constraint::Coincident(crate::frontend::sketch::Coincident {
5169                    segments: left_coincident_segments,
5170                }));
5171
5172                // Right constraint - need to check if intersection is at endpoint
5173                let right_intersecting_seg_id = match &**right_side {
5174                    TrimTermination::Intersection {
5175                        intersecting_seg_id, ..
5176                    }
5177                    | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
5178                        intersecting_seg_id, ..
5179                    } => *intersecting_seg_id,
5180                    _ => {
5181                        return Err("Right side is not an intersection or coincident".to_string());
5182                    }
5183                };
5184
5185                let mut intersection_point_id: Option<ObjectId> = None;
5186                if matches!(&**right_side, TrimTermination::Intersection { .. }) {
5187                    let intersecting_seg = edit_scene_graph_delta
5188                        .new_graph
5189                        .objects
5190                        .iter()
5191                        .find(|obj| obj.id == right_intersecting_seg_id);
5192
5193                    if let Some(seg) = intersecting_seg {
5194                        let endpoint_epsilon = 1e-3; // In current trim unit
5195                        let right_trim_coords_value = *right_trim_coords;
5196
5197                        if let crate::frontend::api::ObjectKind::Segment { segment } = &seg.kind {
5198                            match segment {
5199                                crate::frontend::sketch::Segment::Line(_) => {
5200                                    if let (Some(start_coords), Some(end_coords)) = (
5201                                        crate::frontend::trim::get_position_coords_for_line(
5202                                            seg,
5203                                            crate::frontend::trim::LineEndpoint::Start,
5204                                            &edit_scene_graph_delta.new_graph.objects,
5205                                            default_unit,
5206                                        ),
5207                                        crate::frontend::trim::get_position_coords_for_line(
5208                                            seg,
5209                                            crate::frontend::trim::LineEndpoint::End,
5210                                            &edit_scene_graph_delta.new_graph.objects,
5211                                            default_unit,
5212                                        ),
5213                                    ) {
5214                                        let dist_to_start = ((right_trim_coords_value.x - start_coords.x)
5215                                            * (right_trim_coords_value.x - start_coords.x)
5216                                            + (right_trim_coords_value.y - start_coords.y)
5217                                                * (right_trim_coords_value.y - start_coords.y))
5218                                            .sqrt();
5219                                        if dist_to_start < endpoint_epsilon {
5220                                            if let crate::frontend::sketch::Segment::Line(line) = segment {
5221                                                intersection_point_id = Some(line.start);
5222                                            }
5223                                        } else {
5224                                            let dist_to_end = ((right_trim_coords_value.x - end_coords.x)
5225                                                * (right_trim_coords_value.x - end_coords.x)
5226                                                + (right_trim_coords_value.y - end_coords.y)
5227                                                    * (right_trim_coords_value.y - end_coords.y))
5228                                                .sqrt();
5229                                            if dist_to_end < endpoint_epsilon
5230                                                && let crate::frontend::sketch::Segment::Line(line) = segment
5231                                            {
5232                                                intersection_point_id = Some(line.end);
5233                                            }
5234                                        }
5235                                    }
5236                                }
5237                                crate::frontend::sketch::Segment::Arc(_) => {
5238                                    if let (Some(start_coords), Some(end_coords)) = (
5239                                        crate::frontend::trim::get_position_coords_from_arc(
5240                                            seg,
5241                                            crate::frontend::trim::ArcPoint::Start,
5242                                            &edit_scene_graph_delta.new_graph.objects,
5243                                            default_unit,
5244                                        ),
5245                                        crate::frontend::trim::get_position_coords_from_arc(
5246                                            seg,
5247                                            crate::frontend::trim::ArcPoint::End,
5248                                            &edit_scene_graph_delta.new_graph.objects,
5249                                            default_unit,
5250                                        ),
5251                                    ) {
5252                                        let dist_to_start = ((right_trim_coords_value.x - start_coords.x)
5253                                            * (right_trim_coords_value.x - start_coords.x)
5254                                            + (right_trim_coords_value.y - start_coords.y)
5255                                                * (right_trim_coords_value.y - start_coords.y))
5256                                            .sqrt();
5257                                        if dist_to_start < endpoint_epsilon {
5258                                            if let crate::frontend::sketch::Segment::Arc(arc) = segment {
5259                                                intersection_point_id = Some(arc.start);
5260                                            }
5261                                        } else {
5262                                            let dist_to_end = ((right_trim_coords_value.x - end_coords.x)
5263                                                * (right_trim_coords_value.x - end_coords.x)
5264                                                + (right_trim_coords_value.y - end_coords.y)
5265                                                    * (right_trim_coords_value.y - end_coords.y))
5266                                                .sqrt();
5267                                            if dist_to_end < endpoint_epsilon
5268                                                && let crate::frontend::sketch::Segment::Arc(arc) = segment
5269                                            {
5270                                                intersection_point_id = Some(arc.end);
5271                                            }
5272                                        }
5273                                    }
5274                                }
5275                                _ => {}
5276                            }
5277                        }
5278                    }
5279                }
5280
5281                let right_coincident_segments = if let Some(point_id) = intersection_point_id {
5282                    vec![new_segment_start_point_id.into(), point_id.into()]
5283                } else if let TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
5284                    other_segment_point_id,
5285                    ..
5286                } = &**right_side
5287                {
5288                    vec![new_segment_start_point_id.into(), (*other_segment_point_id).into()]
5289                } else {
5290                    vec![new_segment_start_point_id.into(), right_intersecting_seg_id.into()]
5291                };
5292                batch_constraints.push(Constraint::Coincident(crate::frontend::sketch::Coincident {
5293                    segments: right_coincident_segments,
5294                }));
5295
5296                // Migrate constraints
5297                let mut points_constrained_to_new_segment_start = std::collections::HashSet::new();
5298                let mut points_constrained_to_new_segment_end = std::collections::HashSet::new();
5299
5300                if let TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
5301                    other_segment_point_id,
5302                    ..
5303                } = &**right_side
5304                {
5305                    points_constrained_to_new_segment_start.insert(other_segment_point_id);
5306                }
5307
5308                for constraint_to_migrate in constraints_to_migrate.iter() {
5309                    if constraint_to_migrate.attach_to_endpoint == AttachToEndpoint::End
5310                        && constraint_to_migrate.is_point_point
5311                    {
5312                        points_constrained_to_new_segment_end.insert(constraint_to_migrate.other_entity_id);
5313                    }
5314                }
5315
5316                for constraint_to_migrate in constraints_to_migrate.iter() {
5317                    // Skip migrating point-segment constraints if the point is already constrained
5318                    if constraint_to_migrate.attach_to_endpoint == AttachToEndpoint::Segment
5319                        && (points_constrained_to_new_segment_start.contains(&constraint_to_migrate.other_entity_id)
5320                            || points_constrained_to_new_segment_end.contains(&constraint_to_migrate.other_entity_id))
5321                    {
5322                        continue; // Skip redundant constraint
5323                    }
5324
5325                    let constraint_segments = if constraint_to_migrate.attach_to_endpoint == AttachToEndpoint::Segment {
5326                        vec![constraint_to_migrate.other_entity_id.into(), new_segment_id.into()]
5327                    } else {
5328                        let target_endpoint_id = if constraint_to_migrate.attach_to_endpoint == AttachToEndpoint::Start
5329                        {
5330                            new_segment_start_point_id
5331                        } else {
5332                            new_segment_end_point_id
5333                        };
5334                        vec![target_endpoint_id.into(), constraint_to_migrate.other_entity_id.into()]
5335                    };
5336                    batch_constraints.push(Constraint::Coincident(crate::frontend::sketch::Coincident {
5337                        segments: constraint_segments,
5338                    }));
5339                }
5340
5341                // Find distance constraints that reference both endpoints of the original segment
5342                let mut distance_constraints_to_re_add: Vec<(
5343                    crate::frontend::api::Number,
5344                    Option<crate::frontend::sketch::Point2d<crate::frontend::api::Number>>,
5345                    crate::frontend::sketch::ConstraintSource,
5346                )> = Vec::new();
5347                if let (Some(original_start_id), Some(original_end_id)) =
5348                    (original_segment_start_point_id, original_segment_end_point_id)
5349                {
5350                    for obj in &edit_scene_graph_delta.new_graph.objects {
5351                        let crate::frontend::api::ObjectKind::Constraint { constraint } = &obj.kind else {
5352                            continue;
5353                        };
5354
5355                        let Constraint::Distance(distance) = constraint else {
5356                            continue;
5357                        };
5358
5359                        let references_start = distance.contains_point(original_start_id);
5360                        let references_end = distance.contains_point(original_end_id);
5361
5362                        if references_start && references_end {
5363                            distance_constraints_to_re_add.push((
5364                                distance.distance,
5365                                distance.label_position.clone(),
5366                                distance.source.clone(),
5367                            ));
5368                        }
5369                    }
5370                }
5371
5372                // Re-add distance constraints
5373                if let Some(original_start_id) = original_segment_start_point_id {
5374                    for (distance_value, label_position, source) in distance_constraints_to_re_add {
5375                        batch_constraints.push(Constraint::Distance(crate::frontend::sketch::Distance {
5376                            points: vec![original_start_id.into(), new_segment_end_point_id.into()],
5377                            distance: distance_value,
5378                            label_position,
5379                            source,
5380                        }));
5381                    }
5382                }
5383
5384                // Migrate center point constraints for arcs
5385                if let Some(new_center_id) = new_segment_center_point_id {
5386                    for (constraint, original_center_id) in center_point_constraints_to_migrate {
5387                        let center_rewrite_map = std::collections::HashMap::from([(original_center_id, new_center_id)]);
5388                        if let Some(rewritten) = rewrite_constraint_with_map(&constraint, &center_rewrite_map)
5389                            && matches!(rewritten, Constraint::Coincident(_) | Constraint::Distance(_))
5390                        {
5391                            batch_constraints.push(rewritten);
5392                        }
5393                    }
5394                }
5395
5396                // Re-add angle constraints (Parallel, Perpendicular, Horizontal, Vertical)
5397                let mut angle_rewrite_map = std::collections::HashMap::from([(*segment_id, new_segment_id)]);
5398                if let Some(original_end_id) = original_segment_end_point_id {
5399                    angle_rewrite_map.insert(original_end_id, new_segment_end_point_id);
5400                }
5401                for obj in &edit_scene_graph_delta.new_graph.objects {
5402                    let crate::frontend::api::ObjectKind::Constraint { constraint } = &obj.kind else {
5403                        continue;
5404                    };
5405
5406                    // Keep this exhaustive so new constraints must declare
5407                    // whether split trim should migrate them to the new segment.
5408                    let should_migrate = match constraint {
5409                        Constraint::Parallel(parallel) => parallel.lines.contains(segment_id),
5410                        Constraint::Perpendicular(perpendicular) => perpendicular.lines.contains(segment_id),
5411                        Constraint::Horizontal(Horizontal::Line { line }) => line == segment_id,
5412                        Constraint::Horizontal(Horizontal::Points { points }) => original_segment_end_point_id
5413                            .is_some_and(|end_id| points.contains(&ConstraintSegment::from(end_id))),
5414                        Constraint::Vertical(Vertical::Line { line }) => line == segment_id,
5415                        Constraint::Vertical(Vertical::Points { points }) => original_segment_end_point_id
5416                            .is_some_and(|end_id| points.contains(&ConstraintSegment::from(end_id))),
5417                        Constraint::Angle(_)
5418                        | Constraint::Coincident(_)
5419                        | Constraint::Diameter(_)
5420                        | Constraint::Distance(_)
5421                        | Constraint::EqualRadius(_)
5422                        | Constraint::Fixed(_)
5423                        | Constraint::HorizontalDistance(_)
5424                        | Constraint::LinesEqualLength(_)
5425                        | Constraint::Midpoint(_)
5426                        | Constraint::Radius(_)
5427                        | Constraint::Symmetric(_)
5428                        | Constraint::Tangent(_)
5429                        | Constraint::VerticalDistance(_) => false,
5430                    };
5431
5432                    if should_migrate
5433                        && let Some(migrated_constraint) = rewrite_constraint_with_map(constraint, &angle_rewrite_map)
5434                        && matches!(
5435                            migrated_constraint,
5436                            Constraint::Parallel(_)
5437                                | Constraint::Perpendicular(_)
5438                                | Constraint::Horizontal(_)
5439                                | Constraint::Vertical(_)
5440                        )
5441                    {
5442                        batch_constraints.push(migrated_constraint);
5443                    }
5444                }
5445
5446                // Step 6: Batch all remaining operations
5447                let constraint_object_ids: Vec<ObjectId> = constraints_to_delete.to_vec();
5448
5449                let batch_result = frontend
5450                    .batch_split_segment_operations(
5451                        ctx,
5452                        version,
5453                        sketch_id,
5454                        Vec::new(), // edit_segments already done
5455                        batch_constraints,
5456                        constraint_object_ids,
5457                        crate::frontend::sketch::NewSegmentInfo {
5458                            segment_id: new_segment_id,
5459                            start_point_id: new_segment_start_point_id,
5460                            end_point_id: new_segment_end_point_id,
5461                            center_point_id: new_segment_center_point_id,
5462                        },
5463                    )
5464                    .await
5465                    .map_err(|e| format!("Failed to batch split segment operations: {}", e.error.message()));
5466                // Track invalidates_ids from batch_split_segment_operations call
5467                if let Ok((_, ref batch_delta)) = batch_result {
5468                    invalidates_ids = invalidates_ids || batch_delta.invalidates_ids;
5469                }
5470                batch_result
5471            }
5472        };
5473
5474        match operation_result {
5475            Ok((source_delta, scene_graph_delta)) => {
5476                // Track invalidates_ids from each operation result
5477                invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
5478                last_result = Some((source_delta, scene_graph_delta.clone()));
5479            }
5480            Err(e) => {
5481                crate::logln!("Error executing trim operation {}: {}", op_index, e);
5482                // Continue to next operation
5483            }
5484        }
5485
5486        op_index += consumed_ops;
5487    }
5488
5489    let (source_delta, mut scene_graph_delta) =
5490        last_result.ok_or_else(|| "No operations were executed successfully".to_string())?;
5491    // Set invalidates_ids if any operation invalidated IDs
5492    scene_graph_delta.invalidates_ids = invalidates_ids;
5493    Ok((source_delta, scene_graph_delta))
5494}