acadrust 0.3.4

A pure Rust library for reading and writing CAD files in DXF format (ASCII and Binary) and DWG format (Binary).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
//! MultiLeader entity implementation.
//!
//! The MultiLeader (MLEADER) entity is an advanced annotation object that can have
//! multiple leader lines connecting to text (MText), block, or tolerance content.

use crate::entities::{Entity, EntityCommon};
use crate::types::{BoundingBox3D, Color, Handle, LineWeight, Transparency, Vector3};

use bitflags::bitflags;

// ============================================================================
// Enums
// ============================================================================

/// Content type for multileader annotation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum LeaderContentType {
    /// No content (leader only).
    None = 0,
    /// Content is a block reference.
    Block = 1,
    /// Content is multiline text.
    #[default]
    MText = 2,
    /// Content is a tolerance frame.
    Tolerance = 3,
}

impl From<i16> for LeaderContentType {
    fn from(value: i16) -> Self {
        match value {
            0 => Self::None,
            1 => Self::Block,
            2 => Self::MText,
            3 => Self::Tolerance,
            _ => Self::None,
        }
    }
}

/// Leader path type (line style).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum MultiLeaderPathType {
    /// Leader is invisible.
    Invisible = 0,
    /// Straight line segments (polyline).
    #[default]
    StraightLineSegments = 1,
    /// Spline curve.
    Spline = 2,
}

impl From<i16> for MultiLeaderPathType {
    fn from(value: i16) -> Self {
        match value {
            0 => Self::Invisible,
            1 => Self::StraightLineSegments,
            2 => Self::Spline,
            _ => Self::StraightLineSegments,
        }
    }
}

/// Text attachment point relative to landing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum TextAttachmentType {
    /// Top of top line.
    TopOfTopLine = 0,
    /// Middle of top line.
    MiddleOfTopLine = 1,
    /// Middle of text (vertical center).
    #[default]
    MiddleOfText = 2,
    /// Middle of bottom line.
    MiddleOfBottomLine = 3,
    /// Bottom of bottom line.
    BottomOfBottomLine = 4,
    /// Bottom line.
    BottomLine = 5,
    /// Bottom of top line, underline bottom line.
    BottomOfTopLineUnderlineBottomLine = 6,
    /// Bottom of top line, underline top line.
    BottomOfTopLineUnderlineTopLine = 7,
    /// Bottom of top line, underline all.
    BottomOfTopLineUnderlineAll = 8,
    /// Center of text (for vertical attachment).
    CenterOfText = 9,
    /// Center of text with overline (for vertical attachment).
    CenterOfTextOverline = 10,
}

impl From<i16> for TextAttachmentType {
    fn from(value: i16) -> Self {
        match value {
            0 => Self::TopOfTopLine,
            1 => Self::MiddleOfTopLine,
            2 => Self::MiddleOfText,
            3 => Self::MiddleOfBottomLine,
            4 => Self::BottomOfBottomLine,
            5 => Self::BottomLine,
            6 => Self::BottomOfTopLineUnderlineBottomLine,
            7 => Self::BottomOfTopLineUnderlineTopLine,
            8 => Self::BottomOfTopLineUnderlineAll,
            9 => Self::CenterOfText,
            10 => Self::CenterOfTextOverline,
            _ => Self::MiddleOfText,
        }
    }
}

/// Text angle type for leader content.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum TextAngleType {
    /// Text angle parallel to last leader line segment.
    ParallelToLastLeaderLine = 0,
    /// Text is always horizontal.
    #[default]
    Horizontal = 1,
    /// Like parallel, but rotated 180° if needed for readability.
    Optimized = 2,
}

impl From<i16> for TextAngleType {
    fn from(value: i16) -> Self {
        match value {
            0 => Self::ParallelToLastLeaderLine,
            1 => Self::Horizontal,
            2 => Self::Optimized,
            _ => Self::Horizontal,
        }
    }
}

/// Block content connection type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum BlockContentConnectionType {
    /// Connect to block extents.
    #[default]
    BlockExtents = 0,
    /// Connect to block base point.
    BasePoint = 1,
}

impl From<i16> for BlockContentConnectionType {
    fn from(value: i16) -> Self {
        match value {
            0 => Self::BlockExtents,
            1 => Self::BasePoint,
            _ => Self::BlockExtents,
        }
    }
}

/// Text attachment direction (horizontal or vertical).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum TextAttachmentDirectionType {
    /// Leaders attach to left/right of content.
    #[default]
    Horizontal = 0,
    /// Leaders attach to top/bottom of content.
    Vertical = 1,
}

impl From<i16> for TextAttachmentDirectionType {
    fn from(value: i16) -> Self {
        match value {
            0 => Self::Horizontal,
            1 => Self::Vertical,
            _ => Self::Horizontal,
        }
    }
}

/// Text attachment point type (left/center/right).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum TextAttachmentPointType {
    /// Attach to left.
    Left = 1,
    /// Attach to center.
    #[default]
    Center = 2,
    /// Attach to right.
    Right = 3,
}

impl From<i16> for TextAttachmentPointType {
    fn from(value: i16) -> Self {
        match value {
            1 => Self::Left,
            2 => Self::Center,
            3 => Self::Right,
            _ => Self::Center,
        }
    }
}

/// Text alignment type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum TextAlignmentType {
    /// Left alignment.
    #[default]
    Left = 0,
    /// Center alignment.
    Center = 1,
    /// Right alignment.
    Right = 2,
}

impl From<i16> for TextAlignmentType {
    fn from(value: i16) -> Self {
        match value {
            0 => Self::Left,
            1 => Self::Center,
            2 => Self::Right,
            _ => Self::Left,
        }
    }
}

/// Flow direction for text columns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum FlowDirectionType {
    /// Horizontal flow.
    #[default]
    Horizontal = 1,
    /// Vertical flow.
    Vertical = 3,
    /// Use style setting.
    ByStyle = 5,
}

impl From<i16> for FlowDirectionType {
    fn from(value: i16) -> Self {
        match value {
            1 => Self::Horizontal,
            3 => Self::Vertical,
            5 => Self::ByStyle,
            _ => Self::Horizontal,
        }
    }
}

/// Line spacing style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum LineSpacingStyle {
    /// At least the specified spacing.
    #[default]
    AtLeast = 1,
    /// Exactly the specified spacing.
    Exactly = 2,
}

impl From<i16> for LineSpacingStyle {
    fn from(value: i16) -> Self {
        match value {
            1 => Self::AtLeast,
            2 => Self::Exactly,
            _ => Self::AtLeast,
        }
    }
}

// ============================================================================
// Bitflags
// ============================================================================

bitflags! {
    /// Property override flags for MultiLeader.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct MultiLeaderPropertyOverrideFlags: u32 {
        /// No overrides.
        const NONE = 0;
        /// Override path type.
        const PATH_TYPE = 0x1;
        /// Override line color.
        const LINE_COLOR = 0x2;
        /// Override leader line type.
        const LEADER_LINE_TYPE = 0x4;
        /// Override leader line weight.
        const LEADER_LINE_WEIGHT = 0x8;
        /// Override enable landing.
        const ENABLE_LANDING = 0x10;
        /// Override landing gap.
        const LANDING_GAP = 0x20;
        /// Override enable dogleg.
        const ENABLE_DOGLEG = 0x40;
        /// Override landing distance.
        const LANDING_DISTANCE = 0x80;
        /// Override arrowhead.
        const ARROWHEAD = 0x100;
        /// Override arrowhead size.
        const ARROWHEAD_SIZE = 0x200;
        /// Override content type.
        const CONTENT_TYPE = 0x400;
        /// Override text style.
        const TEXT_STYLE = 0x800;
        /// Override text left attachment.
        const TEXT_LEFT_ATTACHMENT = 0x1000;
        /// Override text angle.
        const TEXT_ANGLE = 0x2000;
        /// Override text alignment.
        const TEXT_ALIGNMENT = 0x4000;
        /// Override text color.
        const TEXT_COLOR = 0x8000;
        /// Override text height.
        const TEXT_HEIGHT = 0x10000;
        /// Override text frame.
        const TEXT_FRAME = 0x20000;
        /// Override use default MText.
        const ENABLE_USE_DEFAULT_MTEXT = 0x40000;
        /// Override block content.
        const BLOCK_CONTENT = 0x80000;
        /// Override block content color.
        const BLOCK_CONTENT_COLOR = 0x100000;
        /// Override block content scale.
        const BLOCK_CONTENT_SCALE = 0x200000;
        /// Override block content rotation.
        const BLOCK_CONTENT_ROTATION = 0x400000;
        /// Override block content connection.
        const BLOCK_CONTENT_CONNECTION = 0x800000;
        /// Override scale factor.
        const SCALE_FACTOR = 0x1000000;
        /// Override text right attachment.
        const TEXT_RIGHT_ATTACHMENT = 0x2000000;
        /// Override text switch alignment type.
        const TEXT_SWITCH_ALIGNMENT_TYPE = 0x4000000;
        /// Override text attachment direction.
        const TEXT_ATTACHMENT_DIRECTION = 0x8000000;
        /// Override text top attachment.
        const TEXT_TOP_ATTACHMENT = 0x10000000;
        /// Override text bottom attachment.
        const TEXT_BOTTOM_ATTACHMENT = 0x20000000;
    }
}

bitflags! {
    /// Property override flags for individual leader lines.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct LeaderLinePropertyOverrideFlags: u32 {
        /// No overrides.
        const NONE = 0;
        /// Override path type.
        const PATH_TYPE = 1;
        /// Override line color.
        const LINE_COLOR = 2;
        /// Override line type.
        const LINE_TYPE = 4;
        /// Override line weight.
        const LINE_WEIGHT = 8;
        /// Override arrowhead size.
        const ARROWHEAD_SIZE = 16;
        /// Override arrowhead.
        const ARROWHEAD = 32;
    }
}

// ============================================================================
// Support Structures
// ============================================================================

/// Start/end point pair for leader line breaks.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StartEndPointPair {
    /// Break start point.
    pub start_point: Vector3,
    /// Break end point.
    pub end_point: Vector3,
}

impl StartEndPointPair {
    /// Creates a new start/end point pair.
    pub fn new(start_point: Vector3, end_point: Vector3) -> Self {
        Self {
            start_point,
            end_point,
        }
    }
}

impl Default for StartEndPointPair {
    fn default() -> Self {
        Self {
            start_point: Vector3::ZERO,
            end_point: Vector3::ZERO,
        }
    }
}

/// A single leader line with vertices.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LeaderLine {
    /// Index of this leader line.
    pub index: i32,
    /// Segment index.
    pub segment_index: i32,
    /// Points (vertices) along the leader line.
    pub points: Vec<Vector3>,
    /// Break start/end point pairs.
    pub break_points: Vec<StartEndPointPair>,
    /// Number of break info entries.
    pub break_info_count: i32,
    /// Path type (straight, spline, invisible).
    pub path_type: MultiLeaderPathType,
    /// Line color override.
    pub line_color: Color,
    /// Line type handle.
    pub line_type_handle: Option<Handle>,
    /// Line weight override.
    pub line_weight: LineWeight,
    /// Arrowhead block handle.
    pub arrowhead_handle: Option<Handle>,
    /// Arrowhead size.
    pub arrowhead_size: f64,
    /// Property override flags.
    pub override_flags: LeaderLinePropertyOverrideFlags,
}

impl LeaderLine {
    /// Creates a new leader line with the given index.
    pub fn new(index: i32) -> Self {
        Self {
            index,
            segment_index: 0,
            points: Vec::new(),
            break_points: Vec::new(),
            break_info_count: 0,
            path_type: MultiLeaderPathType::StraightLineSegments,
            line_color: Color::ByBlock,
            line_type_handle: None,
            line_weight: LineWeight::ByLayer,
            arrowhead_handle: None,
            arrowhead_size: 0.18,
            override_flags: LeaderLinePropertyOverrideFlags::NONE,
        }
    }

    /// Creates a leader line from a list of points.
    pub fn from_points(index: i32, points: Vec<Vector3>) -> Self {
        let mut line = Self::new(index);
        line.points = points;
        line
    }

    /// Adds a point to the leader line.
    pub fn add_point(&mut self, point: Vector3) {
        self.points.push(point);
    }

    /// Returns the number of points.
    pub fn point_count(&self) -> usize {
        self.points.len()
    }

    /// Gets the start point (first point).
    pub fn start_point(&self) -> Option<Vector3> {
        self.points.first().copied()
    }

    /// Gets the end point (last point).
    pub fn end_point(&self) -> Option<Vector3> {
        self.points.last().copied()
    }

    /// Calculates the total length of the leader line.
    pub fn length(&self) -> f64 {
        if self.points.len() < 2 {
            return 0.0;
        }
        self.points
            .windows(2)
            .map(|w| (w[1] - w[0]).length())
            .sum()
    }
}

impl Default for LeaderLine {
    fn default() -> Self {
        Self::new(0)
    }
}

/// A leader root containing one or more leader lines.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LeaderRoot {
    /// Index of this leader root.
    pub leader_index: i32,
    /// Whether content is valid.
    pub content_valid: bool,
    /// Unknown flag (ODA writes true).
    pub unknown: bool,
    /// Connection point at content.
    pub connection_point: Vector3,
    /// Direction from connection point.
    pub direction: Vector3,
    /// Break start/end point pairs.
    pub break_points: Vec<StartEndPointPair>,
    /// Leader lines in this root.
    pub lines: Vec<LeaderLine>,
    /// Landing distance (dogleg length).
    pub landing_distance: f64,
    /// Text attachment direction (R2010+).
    pub text_attachment_direction: TextAttachmentDirectionType,
}

impl LeaderRoot {
    /// Creates a new leader root with the given index.
    pub fn new(index: i32) -> Self {
        Self {
            leader_index: index,
            content_valid: true,
            unknown: true,
            connection_point: Vector3::ZERO,
            direction: Vector3::new(1.0, 0.0, 0.0),
            break_points: Vec::new(),
            lines: Vec::new(),
            landing_distance: 0.36,
            text_attachment_direction: TextAttachmentDirectionType::Horizontal,
        }
    }

    /// Adds a leader line to this root.
    pub fn add_line(&mut self, line: LeaderLine) {
        self.lines.push(line);
    }

    /// Creates a leader line and adds it to this root.
    pub fn create_line(&mut self, points: Vec<Vector3>) -> &mut LeaderLine {
        let index = self.lines.len() as i32;
        let line = LeaderLine::from_points(index, points);
        self.lines.push(line);
        self.lines.last_mut().unwrap()
    }

    /// Returns the number of leader lines.
    pub fn line_count(&self) -> usize {
        self.lines.len()
    }
}

impl Default for LeaderRoot {
    fn default() -> Self {
        Self::new(0)
    }
}

/// Block attribute for block content.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BlockAttribute {
    /// Handle to the attribute definition.
    pub attribute_definition_handle: Option<Handle>,
    /// Attribute index.
    pub index: i16,
    /// Attribute width.
    pub width: f64,
    /// Attribute text value.
    pub text: String,
}

impl BlockAttribute {
    /// Creates a new block attribute.
    pub fn new(text: &str) -> Self {
        Self {
            attribute_definition_handle: None,
            index: 0,
            width: 0.0,
            text: text.to_string(),
        }
    }
}

impl Default for BlockAttribute {
    fn default() -> Self {
        Self::new("")
    }
}

// ============================================================================
// MultiLeader Context Data
// ============================================================================

/// Context data for MultiLeader annotation (geometry and content).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MultiLeaderAnnotContext {
    /// Leader roots (each can have multiple leader lines).
    pub leader_roots: Vec<LeaderRoot>,

    // Scale and positioning
    /// Overall scale factor.
    pub scale_factor: f64,
    /// Content base point.
    pub content_base_point: Vector3,

    // Text content properties
    /// Whether there is text content.
    pub has_text_contents: bool,
    /// Text string (may contain MTEXT markup).
    pub text_string: String,
    /// Text normal vector.
    pub text_normal: Vector3,
    /// Text location.
    pub text_location: Vector3,
    /// Text direction.
    pub text_direction: Vector3,
    /// Text rotation in radians.
    pub text_rotation: f64,
    /// Text height (scaled).
    pub text_height: f64,
    /// Text width boundary.
    pub text_width: f64,
    /// Text height boundary.
    pub text_boundary_height: f64,
    /// Line spacing factor.
    pub line_spacing_factor: f64,
    /// Line spacing style.
    pub line_spacing_style: LineSpacingStyle,
    /// Text color.
    pub text_color: Color,
    /// Text attachment point.
    pub text_attachment_point: TextAttachmentPointType,
    /// Text flow direction.
    pub text_flow_direction: FlowDirectionType,
    /// Text alignment.
    pub text_alignment: TextAlignmentType,
    /// Text left attachment type.
    pub text_left_attachment: TextAttachmentType,
    /// Text right attachment type.
    pub text_right_attachment: TextAttachmentType,
    /// Text top attachment type.
    pub text_top_attachment: TextAttachmentType,
    /// Text bottom attachment type.
    pub text_bottom_attachment: TextAttachmentType,
    /// Whether text height is automatic.
    pub text_height_automatic: bool,
    /// Word break enabled.
    pub word_break: bool,
    /// Text style handle.
    pub text_style_handle: Option<Handle>,

    // Block content properties
    /// Whether there is block content.
    pub has_block_contents: bool,
    /// Block content handle.
    pub block_content_handle: Option<Handle>,
    /// Block content normal.
    pub block_content_normal: Vector3,
    /// Block content location.
    pub block_content_location: Vector3,
    /// Block content scale.
    pub block_content_scale: Vector3,
    /// Block rotation in radians.
    pub block_rotation: f64,
    /// Block content color.
    pub block_content_color: Color,
    /// Block connection type.
    pub block_connection_type: BlockContentConnectionType,

    // Column properties
    /// Column type.
    pub column_type: i16,
    /// Column width.
    pub column_width: f64,
    /// Column gutter.
    pub column_gutter: f64,
    /// Column flow reversed.
    pub column_flow_reversed: bool,
    /// Column sizes.
    pub column_sizes: Vec<f64>,

    // Background fill
    /// Background fill enabled.
    pub background_fill_enabled: bool,
    /// Background mask fill on.
    pub background_mask_fill_on: bool,
    /// Background fill color.
    pub background_fill_color: Color,
    /// Background scale factor.
    pub background_scale_factor: f64,
    /// Background transparency.
    pub background_transparency: i32,

    // Transformation
    /// Base point.
    pub base_point: Vector3,
    /// Base direction vector.
    pub base_direction: Vector3,
    /// Base vertical vector.
    pub base_vertical: Vector3,
    /// Normal reversed.
    pub normal_reversed: bool,

    // Arrowhead
    /// Arrowhead size (scaled).
    pub arrowhead_size: f64,
    /// Landing gap.
    pub landing_gap: f64,

    // Transformation matrix (4x4)
    /// Transformation matrix (16 values, column-major).
    pub transform_matrix: [f64; 16],

    /// Scale object handle.
    pub scale_handle: Option<Handle>,
}

impl MultiLeaderAnnotContext {
    /// Creates a new annotation context with defaults.
    pub fn new() -> Self {
        // Identity matrix
        let mut transform_matrix = [0.0; 16];
        transform_matrix[0] = 1.0;
        transform_matrix[5] = 1.0;
        transform_matrix[10] = 1.0;
        transform_matrix[15] = 1.0;

        Self {
            leader_roots: Vec::new(),
            scale_factor: 1.0,
            content_base_point: Vector3::ZERO,
            has_text_contents: false,
            text_string: String::new(),
            text_normal: Vector3::new(0.0, 0.0, 1.0),
            text_location: Vector3::ZERO,
            text_direction: Vector3::new(1.0, 0.0, 0.0),
            text_rotation: 0.0,
            text_height: 0.18,
            text_width: 0.0,
            text_boundary_height: 0.0,
            line_spacing_factor: 1.0,
            line_spacing_style: LineSpacingStyle::AtLeast,
            text_color: Color::ByBlock,
            text_attachment_point: TextAttachmentPointType::Center,
            text_flow_direction: FlowDirectionType::Horizontal,
            text_alignment: TextAlignmentType::Left,
            text_left_attachment: TextAttachmentType::MiddleOfText,
            text_right_attachment: TextAttachmentType::MiddleOfText,
            text_top_attachment: TextAttachmentType::CenterOfText,
            text_bottom_attachment: TextAttachmentType::CenterOfText,
            text_height_automatic: false,
            word_break: true,
            text_style_handle: None,
            has_block_contents: false,
            block_content_handle: None,
            block_content_normal: Vector3::new(0.0, 0.0, 1.0),
            block_content_location: Vector3::ZERO,
            block_content_scale: Vector3::new(1.0, 1.0, 1.0),
            block_rotation: 0.0,
            block_content_color: Color::ByBlock,
            block_connection_type: BlockContentConnectionType::BlockExtents,
            column_type: 0,
            column_width: 0.0,
            column_gutter: 0.0,
            column_flow_reversed: false,
            column_sizes: Vec::new(),
            background_fill_enabled: false,
            background_mask_fill_on: false,
            background_fill_color: Color::ByBlock,
            background_scale_factor: 1.5,
            background_transparency: 0,
            base_point: Vector3::ZERO,
            base_direction: Vector3::new(1.0, 0.0, 0.0),
            base_vertical: Vector3::new(0.0, 1.0, 0.0),
            normal_reversed: false,
            arrowhead_size: 0.18,
            landing_gap: 0.09,
            transform_matrix,
            scale_handle: None,
        }
    }

    /// Adds a leader root and returns a mutable reference.
    pub fn add_leader_root(&mut self) -> &mut LeaderRoot {
        let index = self.leader_roots.len() as i32;
        self.leader_roots.push(LeaderRoot::new(index));
        self.leader_roots.last_mut().unwrap()
    }

    /// Gets the number of leader roots.
    pub fn leader_root_count(&self) -> usize {
        self.leader_roots.len()
    }

    /// Sets text content.
    pub fn set_text_content(&mut self, text: &str, location: Vector3) {
        self.has_text_contents = true;
        self.text_string = text.to_string();
        self.text_location = location;
        self.content_base_point = location;
    }

    /// Sets block content.
    pub fn set_block_content(&mut self, block_handle: Handle, location: Vector3) {
        self.has_block_contents = true;
        self.block_content_handle = Some(block_handle);
        self.block_content_location = location;
        self.content_base_point = location;
    }
}

impl Default for MultiLeaderAnnotContext {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// MultiLeader Entity
// ============================================================================

/// MultiLeader (MLEADER) entity.
///
/// An advanced annotation object with multiple leader lines connecting to
/// text (MText), block, or tolerance content.
///
/// # Example
///
/// ```ignore
/// use acadrust::entities::MultiLeader;
/// use acadrust::types::Vector3;
///
/// // Create a multileader with text content
/// let mut mleader = MultiLeader::new();
/// mleader.set_text_content("Note", Vector3::new(10.0, 10.0, 0.0));
///
/// // Add a leader from (0,0) to (5,5) to (10,10)
/// let root = mleader.add_leader_root();
/// root.create_line(vec![
///     Vector3::new(0.0, 0.0, 0.0),
///     Vector3::new(5.0, 5.0, 0.0),
/// ]);
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MultiLeader {
    /// Common entity data.
    pub common: EntityCommon,

    // Style reference
    /// Handle to MultiLeader style.
    pub style_handle: Option<Handle>,

    // Content settings
    /// Content type (None, Block, MText, Tolerance).
    pub content_type: LeaderContentType,
    /// Context data (geometry and content).
    pub context: MultiLeaderAnnotContext,
    /// Block attributes (for block content).
    pub block_attributes: Vec<BlockAttribute>,

    // Leader line settings
    /// Path type (straight, spline, invisible).
    pub path_type: MultiLeaderPathType,
    /// Leader line color.
    pub line_color: Color,
    /// Leader line type handle.
    pub line_type_handle: Option<Handle>,
    /// Leader line weight.
    pub line_weight: LineWeight,
    /// Enable landing.
    pub enable_landing: bool,
    /// Enable dogleg.
    pub enable_dogleg: bool,
    /// Dogleg length.
    pub dogleg_length: f64,
    /// Arrowhead block handle.
    pub arrowhead_handle: Option<Handle>,
    /// Arrowhead size.
    pub arrowhead_size: f64,

    // Text settings
    /// Text style handle.
    pub text_style_handle: Option<Handle>,
    /// Text color.
    pub text_color: Color,
    /// Draw text with frame.
    pub text_frame: bool,
    /// Text height.
    pub text_height: f64,
    /// Text left attachment type.
    pub text_left_attachment: TextAttachmentType,
    /// Text right attachment type.
    pub text_right_attachment: TextAttachmentType,
    /// Text top attachment type.
    pub text_top_attachment: TextAttachmentType,
    /// Text bottom attachment type.
    pub text_bottom_attachment: TextAttachmentType,
    /// Text attachment direction.
    pub text_attachment_direction: TextAttachmentDirectionType,
    /// Text attachment point.
    pub text_attachment_point: TextAttachmentPointType,
    /// Text alignment.
    pub text_alignment: TextAlignmentType,
    /// Text angle type.
    pub text_angle_type: TextAngleType,
    /// Text direction negative.
    pub text_direction_negative: bool,
    /// Text align in IPE.
    pub text_align_in_ipe: i16,

    // Block settings
    /// Block content handle.
    pub block_content_handle: Option<Handle>,
    /// Block content color.
    pub block_content_color: Color,
    /// Block content connection type.
    pub block_connection_type: BlockContentConnectionType,
    /// Block rotation in radians.
    pub block_rotation: f64,
    /// Block scale.
    pub block_scale: Vector3,

    // General settings
    /// Scale factor.
    pub scale_factor: f64,
    /// Property override flags.
    pub property_override_flags: MultiLeaderPropertyOverrideFlags,
    /// Enable annotation scale.
    pub enable_annotation_scale: bool,
    /// Extend leader to text.
    pub extend_leader_to_text: bool,
}

impl MultiLeader {
    /// Creates a new MultiLeader with default settings.
    pub fn new() -> Self {
        Self {
            common: EntityCommon::default(),
            style_handle: None,
            content_type: LeaderContentType::MText,
            context: MultiLeaderAnnotContext::new(),
            block_attributes: Vec::new(),
            path_type: MultiLeaderPathType::StraightLineSegments,
            line_color: Color::ByBlock,
            line_type_handle: None,
            line_weight: LineWeight::ByLayer,
            enable_landing: true,
            enable_dogleg: true,
            dogleg_length: 0.36,
            arrowhead_handle: None,
            arrowhead_size: 0.18,
            text_style_handle: None,
            text_color: Color::ByBlock,
            text_frame: false,
            text_height: 0.18,
            text_left_attachment: TextAttachmentType::MiddleOfText,
            text_right_attachment: TextAttachmentType::MiddleOfText,
            text_top_attachment: TextAttachmentType::CenterOfText,
            text_bottom_attachment: TextAttachmentType::CenterOfText,
            text_attachment_direction: TextAttachmentDirectionType::Horizontal,
            text_attachment_point: TextAttachmentPointType::Center,
            text_alignment: TextAlignmentType::Left,
            text_angle_type: TextAngleType::Horizontal,
            text_direction_negative: false,
            text_align_in_ipe: 0,
            block_content_handle: None,
            block_content_color: Color::ByBlock,
            block_connection_type: BlockContentConnectionType::BlockExtents,
            block_rotation: 0.0,
            block_scale: Vector3::new(1.0, 1.0, 1.0),
            scale_factor: 1.0,
            property_override_flags: MultiLeaderPropertyOverrideFlags::NONE,
            enable_annotation_scale: true,
            extend_leader_to_text: false,
        }
    }

    /// Creates a MultiLeader with text content.
    pub fn with_text(text: &str, text_location: Vector3, leader_points: Vec<Vector3>) -> Self {
        let mut mleader = Self::new();
        mleader.set_text_content(text, text_location);

        // Add leader root and line
        let root = mleader.add_leader_root();
        root.connection_point = text_location;
        if !leader_points.is_empty() {
            root.create_line(leader_points);
        }

        mleader
    }

    /// Sets text content.
    pub fn set_text_content(&mut self, text: &str, location: Vector3) {
        self.content_type = LeaderContentType::MText;
        self.context.set_text_content(text, location);
    }

    /// Sets block content.
    pub fn set_block_content(&mut self, block_handle: Handle, location: Vector3) {
        self.content_type = LeaderContentType::Block;
        self.block_content_handle = Some(block_handle);
        self.context.set_block_content(block_handle, location);
    }

    /// Adds a leader root.
    pub fn add_leader_root(&mut self) -> &mut LeaderRoot {
        self.context.add_leader_root()
    }

    /// Gets the number of leader roots.
    pub fn leader_root_count(&self) -> usize {
        self.context.leader_root_count()
    }

    /// Gets the total number of leader lines across all roots.
    pub fn total_leader_line_count(&self) -> usize {
        self.context
            .leader_roots
            .iter()
            .map(|r| r.line_count())
            .sum()
    }

    /// Gets the content text (if text content).
    pub fn text(&self) -> Option<&str> {
        if self.content_type == LeaderContentType::MText && self.context.has_text_contents {
            Some(&self.context.text_string)
        } else {
            None
        }
    }

    /// Sets the text content string.
    pub fn set_text(&mut self, text: &str) {
        if self.content_type == LeaderContentType::MText {
            self.context.text_string = text.to_string();
            self.context.has_text_contents = true;
        }
    }

    /// Translates the multileader by the given offset.
    pub fn translate(&mut self, offset: Vector3) {
        // Translate context points
        self.context.content_base_point = self.context.content_base_point + offset;
        self.context.text_location = self.context.text_location + offset;
        self.context.block_content_location = self.context.block_content_location + offset;
        self.context.base_point = self.context.base_point + offset;

        // Translate all leader roots and lines
        for root in &mut self.context.leader_roots {
            root.connection_point = root.connection_point + offset;
            for bp in &mut root.break_points {
                bp.start_point = bp.start_point + offset;
                bp.end_point = bp.end_point + offset;
            }
            for line in &mut root.lines {
                for point in &mut line.points {
                    *point = *point + offset;
                }
                for bp in &mut line.break_points {
                    bp.start_point = bp.start_point + offset;
                    bp.end_point = bp.end_point + offset;
                }
            }
        }
    }

    /// Returns the bounding box of all leader line points and content.
    pub fn bounding_box(&self) -> Option<(Vector3, Vector3)> {
        let mut points: Vec<Vector3> = Vec::new();

        // Add content point
        points.push(self.context.content_base_point);

        // Add all leader line points
        for root in &self.context.leader_roots {
            points.push(root.connection_point);
            for line in &root.lines {
                points.extend(&line.points);
            }
        }

        if points.is_empty() {
            return None;
        }

        let mut min = points[0];
        let mut max = points[0];

        for p in &points[1..] {
            min.x = min.x.min(p.x);
            min.y = min.y.min(p.y);
            min.z = min.z.min(p.z);
            max.x = max.x.max(p.x);
            max.y = max.y.max(p.y);
            max.z = max.z.max(p.z);
        }

        Some((min, max))
    }
}

impl Default for MultiLeader {
    fn default() -> Self {
        Self::new()
    }
}

impl Entity for MultiLeader {
    fn handle(&self) -> Handle {
        self.common.handle
    }

    fn set_handle(&mut self, handle: Handle) {
        self.common.handle = handle;
    }

    fn layer(&self) -> &str {
        &self.common.layer
    }

    fn set_layer(&mut self, layer: String) {
        self.common.layer = layer;
    }

    fn color(&self) -> Color {
        self.common.color
    }

    fn set_color(&mut self, color: Color) {
        self.common.color = color;
    }

    fn line_weight(&self) -> LineWeight {
        self.common.line_weight
    }

    fn set_line_weight(&mut self, line_weight: LineWeight) {
        self.common.line_weight = line_weight;
    }

    fn transparency(&self) -> Transparency {
        self.common.transparency
    }

    fn set_transparency(&mut self, transparency: Transparency) {
        self.common.transparency = transparency;
    }

    fn is_invisible(&self) -> bool {
        self.common.invisible
    }

    fn set_invisible(&mut self, invisible: bool) {
        self.common.invisible = invisible;
    }

    fn bounding_box(&self) -> BoundingBox3D {
        // Calculate bounding box from all leader line points and content location
        let mut min = Vector3::new(f64::MAX, f64::MAX, f64::MAX);
        let mut max = Vector3::new(f64::MIN, f64::MIN, f64::MIN);
        
        // Include content location
        let loc = &self.context.content_base_point;
        min.x = min.x.min(loc.x);
        min.y = min.y.min(loc.y);
        min.z = min.z.min(loc.z);
        max.x = max.x.max(loc.x);
        max.y = max.y.max(loc.y);
        max.z = max.z.max(loc.z);
        
        // Include all leader line points
        for root in &self.context.leader_roots {
            for line in &root.lines {
                for pt in &line.points {
                    min.x = min.x.min(pt.x);
                    min.y = min.y.min(pt.y);
                    min.z = min.z.min(pt.z);
                    max.x = max.x.max(pt.x);
                    max.y = max.y.max(pt.y);
                    max.z = max.z.max(pt.z);
                }
            }
        }
        
        BoundingBox3D::new(min, max)
    }

    fn translate(&mut self, offset: Vector3) {
        super::translate::translate_multileader(self, offset);
    }

    fn entity_type(&self) -> &'static str {
        "MULTILEADER"
    }
    
    fn apply_transform(&mut self, transform: &crate::types::Transform) {
        super::transform::transform_multileader(self, transform);
    }
}

// ============================================================================
// Builder
// ============================================================================

/// Builder for MultiLeader entities.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MultiLeaderBuilder {
    multileader: MultiLeader,
}

impl MultiLeaderBuilder {
    /// Creates a new builder.
    pub fn new() -> Self {
        Self {
            multileader: MultiLeader::new(),
        }
    }

    /// Sets text content.
    pub fn text(mut self, text: &str, location: Vector3) -> Self {
        self.multileader.set_text_content(text, location);
        self
    }

    /// Sets block content.
    pub fn block(mut self, block_handle: Handle, location: Vector3) -> Self {
        self.multileader.set_block_content(block_handle, location);
        self
    }

    /// Sets content type to None.
    pub fn no_content(mut self) -> Self {
        self.multileader.content_type = LeaderContentType::None;
        self
    }

    /// Adds a leader line.
    pub fn leader_line(mut self, points: Vec<Vector3>) -> Self {
        if self.multileader.context.leader_roots.is_empty() {
            self.multileader.add_leader_root();
        }
        let root = self.multileader.context.leader_roots.last_mut().unwrap();
        root.create_line(points);
        self
    }

    /// Adds a new leader root.
    pub fn new_root(mut self) -> Self {
        self.multileader.add_leader_root();
        self
    }

    /// Sets the path type.
    pub fn path_type(mut self, path_type: MultiLeaderPathType) -> Self {
        self.multileader.path_type = path_type;
        self
    }

    /// Sets the arrowhead size.
    pub fn arrowhead_size(mut self, size: f64) -> Self {
        self.multileader.arrowhead_size = size;
        self.multileader.context.arrowhead_size = size;
        self
    }

    /// Sets the text height.
    pub fn text_height(mut self, height: f64) -> Self {
        self.multileader.text_height = height;
        self.multileader.context.text_height = height;
        self
    }

    /// Sets whether to draw text frame.
    pub fn text_frame(mut self, frame: bool) -> Self {
        self.multileader.text_frame = frame;
        self
    }

    /// Sets the line color.
    pub fn line_color(mut self, color: Color) -> Self {
        self.multileader.line_color = color;
        self
    }

    /// Sets the text color.
    pub fn text_color(mut self, color: Color) -> Self {
        self.multileader.text_color = color;
        self.multileader.context.text_color = color;
        self
    }

    /// Enables or disables landing (dogleg).
    pub fn landing(mut self, enable: bool) -> Self {
        self.multileader.enable_landing = enable;
        self
    }

    /// Sets the dogleg length.
    pub fn dogleg_length(mut self, length: f64) -> Self {
        self.multileader.dogleg_length = length;
        self
    }

    /// Sets the scale factor.
    pub fn scale(mut self, scale: f64) -> Self {
        self.multileader.scale_factor = scale;
        self.multileader.context.scale_factor = scale;
        self
    }

    /// Builds the MultiLeader.
    pub fn build(self) -> MultiLeader {
        self.multileader
    }
}

impl Default for MultiLeaderBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_multileader_creation() {
        let mleader = MultiLeader::new();
        assert_eq!(mleader.content_type, LeaderContentType::MText);
        assert!(mleader.enable_landing);
        assert!(mleader.enable_dogleg);
        assert_eq!(mleader.leader_root_count(), 0);
    }

    #[test]
    fn test_multileader_with_text() {
        let points = vec![
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(5.0, 5.0, 0.0),
        ];
        let mleader = MultiLeader::with_text("Note", Vector3::new(10.0, 10.0, 0.0), points);

        assert_eq!(mleader.content_type, LeaderContentType::MText);
        assert_eq!(mleader.text(), Some("Note"));
        assert_eq!(mleader.leader_root_count(), 1);
        assert_eq!(mleader.total_leader_line_count(), 1);
    }

    #[test]
    fn test_multileader_add_leader_root() {
        let mut mleader = MultiLeader::new();
        let root = mleader.add_leader_root();
        root.create_line(vec![Vector3::ZERO, Vector3::new(1.0, 1.0, 0.0)]);
        root.create_line(vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 0.0)]);

        assert_eq!(mleader.leader_root_count(), 1);
        assert_eq!(mleader.total_leader_line_count(), 2);
    }

    #[test]
    fn test_leader_line() {
        let mut line = LeaderLine::new(0);
        line.add_point(Vector3::new(0.0, 0.0, 0.0));
        line.add_point(Vector3::new(3.0, 4.0, 0.0));

        assert_eq!(line.point_count(), 2);
        assert_eq!(line.start_point(), Some(Vector3::new(0.0, 0.0, 0.0)));
        assert_eq!(line.end_point(), Some(Vector3::new(3.0, 4.0, 0.0)));
        assert!((line.length() - 5.0).abs() < 1e-10);
    }

    #[test]
    fn test_multileader_translate() {
        let mut mleader = MultiLeader::with_text(
            "Note",
            Vector3::new(10.0, 10.0, 0.0),
            vec![Vector3::ZERO, Vector3::new(5.0, 5.0, 0.0)],
        );

        mleader.translate(Vector3::new(5.0, 5.0, 0.0));

        assert_eq!(mleader.context.text_location, Vector3::new(15.0, 15.0, 0.0));
        let root = &mleader.context.leader_roots[0];
        let line = &root.lines[0];
        assert_eq!(line.points[0], Vector3::new(5.0, 5.0, 0.0));
        assert_eq!(line.points[1], Vector3::new(10.0, 10.0, 0.0));
    }

    #[test]
    fn test_multileader_bounding_box() {
        let mleader = MultiLeader::with_text(
            "Note",
            Vector3::new(10.0, 10.0, 0.0),
            vec![
                Vector3::new(0.0, 0.0, 0.0),
                Vector3::new(5.0, 5.0, 0.0),
            ],
        );

        let bbox = mleader.bounding_box().unwrap();
        assert_eq!(bbox.0, Vector3::new(0.0, 0.0, 0.0));
        assert_eq!(bbox.1, Vector3::new(10.0, 10.0, 0.0));
    }

    #[test]
    fn test_content_types() {
        assert_eq!(LeaderContentType::from(0), LeaderContentType::None);
        assert_eq!(LeaderContentType::from(1), LeaderContentType::Block);
        assert_eq!(LeaderContentType::from(2), LeaderContentType::MText);
        assert_eq!(LeaderContentType::from(3), LeaderContentType::Tolerance);
    }

    #[test]
    fn test_path_types() {
        assert_eq!(MultiLeaderPathType::from(0), MultiLeaderPathType::Invisible);
        assert_eq!(MultiLeaderPathType::from(1), MultiLeaderPathType::StraightLineSegments);
        assert_eq!(MultiLeaderPathType::from(2), MultiLeaderPathType::Spline);
    }

    #[test]
    fn test_text_attachment_types() {
        assert_eq!(TextAttachmentType::from(0), TextAttachmentType::TopOfTopLine);
        assert_eq!(TextAttachmentType::from(2), TextAttachmentType::MiddleOfText);
        assert_eq!(TextAttachmentType::from(9), TextAttachmentType::CenterOfText);
    }

    #[test]
    fn test_builder() {
        let mleader = MultiLeaderBuilder::new()
            .text("Note", Vector3::new(10.0, 10.0, 0.0))
            .leader_line(vec![Vector3::ZERO, Vector3::new(5.0, 5.0, 0.0)])
            .arrowhead_size(0.25)
            .text_height(0.2)
            .text_frame(true)
            .scale(2.0)
            .build();

        assert_eq!(mleader.text(), Some("Note"));
        assert_eq!(mleader.arrowhead_size, 0.25);
        assert_eq!(mleader.text_height, 0.2);
        assert!(mleader.text_frame);
        assert_eq!(mleader.scale_factor, 2.0);
    }

    #[test]
    fn test_property_override_flags() {
        let flags = MultiLeaderPropertyOverrideFlags::PATH_TYPE
            | MultiLeaderPropertyOverrideFlags::LINE_COLOR
            | MultiLeaderPropertyOverrideFlags::TEXT_HEIGHT;

        assert!(flags.contains(MultiLeaderPropertyOverrideFlags::PATH_TYPE));
        assert!(flags.contains(MultiLeaderPropertyOverrideFlags::LINE_COLOR));
        assert!(flags.contains(MultiLeaderPropertyOverrideFlags::TEXT_HEIGHT));
        assert!(!flags.contains(MultiLeaderPropertyOverrideFlags::ARROWHEAD));
    }

    #[test]
    fn test_leader_line_override_flags() {
        let flags = LeaderLinePropertyOverrideFlags::LINE_COLOR
            | LeaderLinePropertyOverrideFlags::ARROWHEAD;

        assert!(flags.contains(LeaderLinePropertyOverrideFlags::LINE_COLOR));
        assert!(flags.contains(LeaderLinePropertyOverrideFlags::ARROWHEAD));
        assert!(!flags.contains(LeaderLinePropertyOverrideFlags::PATH_TYPE));
    }

    #[test]
    fn test_block_attribute() {
        let attr = BlockAttribute::new("Value");
        assert_eq!(attr.text, "Value");
        assert_eq!(attr.index, 0);
        assert_eq!(attr.width, 0.0);
    }

    #[test]
    fn test_annot_context_defaults() {
        let ctx = MultiLeaderAnnotContext::new();
        assert_eq!(ctx.scale_factor, 1.0);
        assert_eq!(ctx.text_height, 0.18);
        assert!(!ctx.has_text_contents);
        assert!(!ctx.has_block_contents);
        assert_eq!(ctx.leader_roots.len(), 0);
    }
}