ass-editor 0.1.1

High-performance, ergonomic editor layer for ASS subtitles
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
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
//! Main document type for the editor
//!
//! Provides the `EditorDocument` struct which manages ASS script content
//! with direct access to parsed ASS structures and efficient text editing.

use super::errors::{EditorError, Result};
use super::history::UndoManager;
use super::position::{LineColumn, Position, Range};
use crate::commands::CommandResult;
#[cfg(feature = "stream")]
use ass_core::parser::script::ScriptDeltaOwned;
use ass_core::parser::{ast::Section, Script};
use core::ops::Range as StdRange;

#[cfg(feature = "std")]
use std::sync::Arc;

#[cfg(not(feature = "std"))]
use alloc::{
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};

#[cfg(feature = "std")]
use std::sync::mpsc::Sender;

#[cfg(feature = "std")]
use crate::events::DocumentEvent;

#[cfg(feature = "std")]
type EventSender = Sender<DocumentEvent>;

/// Main document container for editing ASS scripts
///
/// Manages both text content and parsed ASS structures with direct access to
/// events, styles, and script info without manual parsing.
#[derive(Debug)]
pub struct EditorDocument {
    /// Rope for efficient text editing operations
    #[cfg(feature = "rope")]
    text_rope: ropey::Rope,

    /// Raw text content (fallback when rope feature is disabled)
    #[cfg(not(feature = "rope"))]
    text_content: String,

    /// Document identifier for session management
    id: String,

    /// Whether document has unsaved changes
    modified: bool,

    /// Optional file path if loaded from/saved to disk
    file_path: Option<String>,

    /// Extension registry integration for tag and section handling
    #[cfg(feature = "plugins")]
    registry_integration: Option<Arc<crate::extensions::registry_integration::RegistryIntegration>>,

    /// Undo/redo manager
    history: UndoManager,

    /// Event channel for sending document events
    #[cfg(feature = "std")]
    event_tx: Option<EventSender>,

    /// Incremental parser for efficient updates
    #[cfg(feature = "stream")]
    incremental_parser: crate::core::incremental::IncrementalParser,

    /// Lazy validator for on-demand validation
    validator: crate::utils::validator::LazyValidator,
}

impl EditorDocument {
    /// Create a new empty document
    pub fn new() -> Self {
        Self {
            #[cfg(feature = "rope")]
            text_rope: ropey::Rope::new(),
            #[cfg(not(feature = "rope"))]
            text_content: String::new(),
            id: Self::generate_id(),
            modified: false,
            file_path: None,
            #[cfg(feature = "plugins")]
            registry_integration: None,
            history: UndoManager::new(),
            #[cfg(feature = "std")]
            event_tx: None,
            #[cfg(feature = "stream")]
            incremental_parser: crate::core::incremental::IncrementalParser::new(),
            validator: crate::utils::validator::LazyValidator::new(),
        }
    }

    /// Create a new document with event channel
    #[cfg(feature = "std")]
    pub fn with_event_channel(event_tx: EventSender) -> Self {
        let mut doc = Self::new();
        doc.event_tx = Some(event_tx);
        doc
    }

    /// Create document from file path
    #[cfg(feature = "std")]
    pub fn from_file(path: &str) -> Result<Self> {
        use std::fs;
        let content = fs::read_to_string(path).map_err(|e| EditorError::IoError(e.to_string()))?;
        let mut doc = Self::from_content(&content)?;
        doc.file_path = Some(path.to_string());
        Ok(doc)
    }

    /// Save document to file
    #[cfg(feature = "std")]
    pub fn save(&mut self) -> Result<()> {
        if let Some(path) = self.file_path.clone() {
            self.save_to_file(&path)
        } else {
            Err(EditorError::IoError(
                "No file path set for document".to_string(),
            ))
        }
    }

    /// Save document to specific file path
    #[cfg(feature = "std")]
    pub fn save_to_file(&mut self, path: &str) -> Result<()> {
        use std::fs;
        let content = self.text();
        fs::write(path, content).map_err(|e| EditorError::IoError(e.to_string()))?;
        self.modified = false;
        self.file_path = Some(path.to_string());
        Ok(())
    }

    /// Create document with specific ID
    pub fn with_id(id: String) -> Self {
        let mut doc = Self::new();
        doc.id = id;
        doc
    }

    /// Emit an event to the event channel
    #[cfg(feature = "std")]
    fn emit(&mut self, event: DocumentEvent) {
        if let Some(tx) = &mut self.event_tx {
            let _ = tx.send(event);
        }
    }

    /// Set the event channel for this document
    #[cfg(feature = "std")]
    pub fn set_event_channel(&mut self, event_tx: EventSender) {
        self.event_tx = Some(event_tx);
    }

    /// Check if document has an event channel
    #[cfg(feature = "std")]
    pub fn has_event_channel(&self) -> bool {
        self.event_tx.is_some()
    }

    /// Load document from string content
    ///
    /// Creates a new `EditorDocument` from ASS subtitle content. The content
    /// is validated during creation to ensure it's parseable.
    ///
    /// # Examples
    ///
    /// ```
    /// use ass_editor::EditorDocument;
    ///
    /// let content = r#"
    /// [Script Info]
    /// Title: My Subtitle
    ///
    /// [V4+ Styles]
    /// Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
    /// Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1
    ///
    /// [Events]
    /// Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
    /// Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,Hello World
    /// "#;
    ///
    /// let doc = EditorDocument::from_content(content).unwrap();
    /// assert!(doc.text().contains("Hello World"));
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `Err` if the content cannot be parsed as valid ASS format.
    pub fn from_content(content: &str) -> Result<Self> {
        // Validate that content can be parsed
        let _ = Script::parse(content).map_err(EditorError::from)?;

        #[cfg(feature = "stream")]
        let mut incremental_parser = crate::core::incremental::IncrementalParser::new();
        #[cfg(feature = "stream")]
        incremental_parser.initialize_cache(content);

        Ok(Self {
            #[cfg(feature = "rope")]
            text_rope: ropey::Rope::from_str(content),
            #[cfg(not(feature = "rope"))]
            text_content: content.to_string(),
            id: Self::generate_id(),
            modified: false,
            file_path: None,
            #[cfg(feature = "plugins")]
            registry_integration: None,
            history: UndoManager::new(),
            #[cfg(feature = "std")]
            event_tx: None,
            #[cfg(feature = "stream")]
            incremental_parser,
            validator: crate::utils::validator::LazyValidator::new(),
        })
    }

    /// Parse the current document content into a Script
    ///
    /// Returns a boxed closure that provides the parsed Script.
    /// This avoids lifetime issues by ensuring the content outlives the Script.
    pub fn parse_script_with<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce(&Script) -> R,
    {
        let content = self.text();
        match Script::parse(&content) {
            Ok(script) => Ok(f(&script)),
            Err(e) => Err(EditorError::from(e)),
        }
    }

    /// Validate the document content can be parsed as valid ASS
    /// This is the basic validation that just checks parsing
    pub fn validate(&self) -> Result<()> {
        let content = self.text();
        Script::parse(&content).map_err(EditorError::from)?;
        Ok(())
    }

    /// Execute a command with proper history recording
    ///
    /// This method ensures that commands are properly recorded in the undo history.
    /// Use this instead of calling command.execute() directly if you want undo support.
    ///
    /// For BatchCommand, this creates a synthetic undo operation that captures
    /// the aggregate effect of all sub-commands.
    pub fn execute_command(
        &mut self,
        command: &dyn crate::commands::EditorCommand,
    ) -> Result<crate::commands::CommandResult> {
        use crate::core::history::Operation;

        // Get the cursor position before
        let _cursor_before = self.cursor_position();

        // Execute the command
        let result = command.execute(self)?;

        // Only record if the command changed content
        if result.content_changed {
            // Determine the operation based on the result
            let operation = if let Some(range) = result.modified_range {
                if range.is_empty() {
                    // This was an insertion
                    let inserted_text = self.text_range(Range::new(
                        range.start,
                        Position::new(
                            range.start.offset
                                + result
                                    .new_cursor
                                    .map_or(0, |c| c.offset - range.start.offset),
                        ),
                    ))?;
                    Operation::Insert {
                        position: range.start,
                        text: inserted_text,
                    }
                } else {
                    // For batch commands and complex operations, we need to be more careful
                    // Store enough information to properly undo
                    // This is a simplified approach - ideally each command would handle its own undo
                    let cmd_desc = command.description();
                    if cmd_desc.contains("batch") || cmd_desc.contains("Multiple") {
                        // For batch operations, we don't have enough info
                        // Just use a simple insert operation
                        Operation::Insert {
                            position: range.start,
                            text: String::new(),
                        }
                    } else {
                        // For simple operations, use the range info
                        Operation::Replace {
                            range,
                            old_text: String::new(), // We don't have the old text
                            new_text: self.text_range(range).unwrap_or_default(),
                        }
                    }
                }
            } else {
                // No range info - create a generic operation
                Operation::Insert {
                    position: Position::new(0),
                    text: String::new(),
                }
            };

            // Update cursor if needed
            if let Some(new_cursor) = result.new_cursor {
                self.set_cursor_position(Some(new_cursor));
            }

            // Record in history
            self.history
                .record_operation(operation, command.description().to_string(), &result);

            // Clear validation cache since content changed
            self.validator.clear_cache();
        }

        Ok(result)
    }

    /// Perform comprehensive validation using the LazyValidator
    /// Returns detailed validation results including warnings and suggestions
    ///
    /// Note: Returns a cloned result to avoid borrow checker issues
    pub fn validate_comprehensive(&mut self) -> Result<crate::utils::validator::ValidationResult> {
        // Create a temporary document reference for validation
        // This is needed because we can't pass &self while mutably borrowing validator
        let temp_doc = EditorDocument::from_content(&self.text())?;
        let result = self.validator.validate(&temp_doc)?;
        Ok(result.clone())
    }

    /// Force revalidation even if cached results exist
    pub fn force_validate(&mut self) -> Result<crate::utils::validator::ValidationResult> {
        // Create a temporary document reference for validation
        let temp_doc = EditorDocument::from_content(&self.text())?;
        let result = self.validator.force_validate(&temp_doc)?;
        Ok(result.clone())
    }

    /// Check if document is valid (quick check using cache if available)
    pub fn is_valid_cached(&mut self) -> Result<bool> {
        // Create a temporary document reference for validation
        let temp_doc = EditorDocument::from_content(&self.text())?;
        self.validator.is_valid(&temp_doc)
    }

    /// Get cached validation result without revalidating
    pub fn validation_result(&self) -> Option<&crate::utils::validator::ValidationResult> {
        self.validator.cached_result()
    }

    /// Configure the validator
    pub fn set_validator_config(&mut self, config: crate::utils::validator::ValidatorConfig) {
        self.validator.set_config(config);
    }

    /// Get mutable access to the validator
    pub fn validator_mut(&mut self) -> &mut crate::utils::validator::LazyValidator {
        &mut self.validator
    }

    /// Get document ID
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get file path if document is associated with a file
    #[must_use]
    pub fn file_path(&self) -> Option<&str> {
        self.file_path.as_deref()
    }

    /// Set file path for the document
    pub fn set_file_path(&mut self, path: Option<String>) {
        self.file_path = path;
    }

    /// Import content from another subtitle format
    #[cfg(feature = "formats")]
    pub fn import_format(
        content: &str,
        format: Option<crate::utils::formats::SubtitleFormat>,
    ) -> Result<Self> {
        let ass_content = crate::utils::formats::FormatConverter::import(content, format)?;
        Self::from_content(&ass_content)
    }

    /// Export document to another subtitle format
    #[cfg(feature = "formats")]
    pub fn export_format(
        &self,
        format: crate::utils::formats::SubtitleFormat,
        options: &crate::utils::formats::ConversionOptions,
    ) -> Result<String> {
        crate::utils::formats::FormatConverter::export(self, format, options)
    }

    /// Check if document has unsaved changes
    #[must_use]
    pub const fn is_modified(&self) -> bool {
        self.modified
    }

    /// Get current cursor position (if tracked)
    #[must_use]
    pub fn cursor_position(&self) -> Option<Position> {
        self.history.cursor_position()
    }

    /// Set current cursor position for tracking
    pub fn set_cursor_position(&mut self, position: Option<Position>) {
        self.history.set_cursor(position);
    }

    /// Mark document as modified
    pub fn set_modified(&mut self, modified: bool) {
        self.modified = modified;
    }

    /// Get total length in bytes
    #[must_use]
    pub fn len_bytes(&self) -> usize {
        #[cfg(feature = "rope")]
        {
            self.text_rope.len_bytes()
        }
        #[cfg(not(feature = "rope"))]
        {
            self.text_content.len()
        }
    }

    /// Get total number of lines
    #[must_use]
    pub fn len_lines(&self) -> usize {
        #[cfg(feature = "rope")]
        {
            self.text_rope.len_lines()
        }
        #[cfg(not(feature = "rope"))]
        {
            self.text_content.lines().count().max(1)
        }
    }

    /// Check if document is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len_bytes() == 0
    }

    /// Get text content as string
    #[must_use]
    pub fn text(&self) -> String {
        #[cfg(feature = "rope")]
        {
            self.text_rope.to_string()
        }
        #[cfg(not(feature = "rope"))]
        {
            self.text_content.clone()
        }
    }

    /// Get direct access to the rope for advanced operations
    #[cfg(feature = "rope")]
    #[must_use]
    pub fn rope(&self) -> &ropey::Rope {
        &self.text_rope
    }

    /// Get the length of the document in bytes
    #[must_use]
    pub fn len(&self) -> usize {
        #[cfg(feature = "rope")]
        {
            self.text_rope.len_bytes()
        }
        #[cfg(not(feature = "rope"))]
        {
            self.text_content.len()
        }
    }

    /// Get text content for a range
    pub fn text_range(&self, range: Range) -> Result<String> {
        let start = range.start.offset;
        let end = range.end.offset;

        if end > self.len_bytes() {
            return Err(EditorError::InvalidRange {
                start,
                end,
                length: self.len_bytes(),
            });
        }

        #[cfg(feature = "rope")]
        {
            // Convert byte offsets to char indices for rope operations
            let start_char = self.text_rope.byte_to_char(start);
            let end_char = self.text_rope.byte_to_char(end);
            Ok(self.text_rope.slice(start_char..end_char).to_string())
        }
        #[cfg(not(feature = "rope"))]
        {
            Ok(self.text_content[start..end].to_string())
        }
    }

    /// Convert byte position to line/column
    #[cfg(feature = "rope")]
    pub fn position_to_line_column(&self, pos: Position) -> Result<LineColumn> {
        if pos.offset > self.len_bytes() {
            return Err(EditorError::PositionOutOfBounds {
                position: pos.offset,
                length: self.len_bytes(),
            });
        }

        let line_idx = self.text_rope.byte_to_line(pos.offset);
        let line_start = self.text_rope.line_to_byte(line_idx);
        let col_offset = pos.offset - line_start;

        // Convert byte offset to character offset within line
        let line = self.text_rope.line(line_idx);
        let mut char_col = 0;
        let mut byte_count = 0;

        for ch in line.chars() {
            if byte_count >= col_offset {
                break;
            }
            byte_count += ch.len_utf8();
            char_col += 1;
        }

        // Convert to 1-indexed
        LineColumn::new(line_idx + 1, char_col + 1)
    }

    /// Convert byte position to line/column (without rope)
    #[cfg(not(feature = "rope"))]
    pub fn position_to_line_column(&self, pos: Position) -> Result<LineColumn> {
        if pos.offset > self.len_bytes() {
            return Err(EditorError::PositionOutOfBounds {
                position: pos.offset,
                length: self.len_bytes(),
            });
        }

        let mut line = 1;
        let mut col = 1;
        let mut byte_pos = 0;

        for ch in self.text_content.chars() {
            if byte_pos >= pos.offset {
                break;
            }

            if ch == '\n' {
                line += 1;
                col = 1;
            } else {
                col += 1;
            }

            byte_pos += ch.len_utf8();
        }

        LineColumn::new(line, col)
    }

    /// Insert text at position (low-level operation without undo)
    pub(crate) fn insert_raw(&mut self, pos: Position, text: &str) -> Result<()> {
        if pos.offset > self.len_bytes() {
            return Err(EditorError::PositionOutOfBounds {
                position: pos.offset,
                length: self.len_bytes(),
            });
        }

        #[cfg(feature = "rope")]
        {
            // Convert byte offset to char index for rope operations
            let char_idx = self.text_rope.byte_to_char(pos.offset);
            self.text_rope.insert(char_idx, text);
        }
        #[cfg(not(feature = "rope"))]
        {
            self.text_content.insert_str(pos.offset, text);
        }

        self.modified = true;
        Ok(())
    }

    /// Insert text at position with undo support
    ///
    /// Inserts text at the given position, automatically updating the underlying
    /// text representation and recording the operation in the undo history.
    ///
    /// # Examples
    ///
    /// ```
    /// use ass_editor::{EditorDocument, Position};
    ///
    /// let mut doc = EditorDocument::from_content("Hello World").unwrap();
    /// let pos = Position::new(5); // Insert after "Hello"
    /// doc.insert(pos, " there").unwrap();
    ///
    /// assert_eq!(doc.text(), "Hello there World");
    ///
    /// // Can undo the operation
    /// doc.undo().unwrap();
    /// assert_eq!(doc.text(), "Hello World");
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `Err` if the position is beyond the document bounds.
    pub fn insert(&mut self, pos: Position, text: &str) -> Result<()> {
        use crate::commands::{EditorCommand, InsertTextCommand};
        use crate::core::history::Operation;

        let command = InsertTextCommand::new(pos, text.to_string());
        let result = command.execute(self)?;

        // Record the operation in history
        let operation = Operation::Insert {
            position: pos,
            text: text.to_string(),
        };
        self.history
            .record_operation(operation, command.description().to_string(), &result);

        // Clear validation cache since content changed
        self.validator.clear_cache();

        // Emit event
        #[cfg(feature = "std")]
        self.emit(DocumentEvent::TextInserted {
            position: pos,
            text: text.to_string(),
            length: text.len(),
        });

        Ok(())
    }

    /// Delete text in range with undo support
    pub fn delete(&mut self, range: Range) -> Result<()> {
        use crate::commands::{DeleteTextCommand, EditorCommand};
        use crate::core::history::Operation;

        // Capture the text that will be deleted BEFORE deletion
        let deleted_text = self.text_range(range)?;

        let command = DeleteTextCommand::new(range);
        let result = command.execute(self)?;

        // Record the operation in history
        let operation = Operation::Delete {
            range,
            deleted_text: deleted_text.clone(),
        };
        self.history
            .record_operation(operation, command.description().to_string(), &result);

        // Clear validation cache since content changed
        self.validator.clear_cache();

        // Emit event
        #[cfg(feature = "std")]
        self.emit(DocumentEvent::TextDeleted {
            range,
            deleted_text,
        });

        Ok(())
    }

    /// Replace text in range with undo support
    pub fn replace(&mut self, range: Range, text: &str) -> Result<()> {
        use crate::commands::{EditorCommand, ReplaceTextCommand};
        use crate::core::history::Operation;

        // Capture the old text BEFORE replacement
        let old_text = self.text_range(range)?;

        let command = ReplaceTextCommand::new(range, text.to_string());
        let result = command.execute(self)?;

        // Record the operation in history
        let operation = Operation::Replace {
            range,
            old_text: old_text.clone(),
            new_text: text.to_string(),
        };
        self.history
            .record_operation(operation, command.description().to_string(), &result);

        // Clear validation cache since content changed
        self.validator.clear_cache();

        // Emit event
        #[cfg(feature = "std")]
        self.emit(DocumentEvent::TextReplaced {
            range,
            old_text,
            new_text: text.to_string(),
        });

        Ok(())
    }

    /// Generate unique document ID
    fn generate_id() -> String {
        // Simple ID generation - in production might use UUID
        #[cfg(feature = "std")]
        {
            use std::time::{SystemTime, UNIX_EPOCH};
            let timestamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos();
            format!("doc_{timestamp}")
        }
        #[cfg(not(feature = "std"))]
        {
            static mut COUNTER: u32 = 0;
            #[allow(static_mut_refs)]
            unsafe {
                COUNTER += 1;
                format!("doc_{COUNTER}")
            }
        }
    }

    // === ASS-Aware APIs ===

    /// Get number of events without manual parsing  
    pub fn events_count(&self) -> Result<usize> {
        self.parse_script_with(|script| {
            let mut count = 0;
            for section in script.sections() {
                if let Section::Events(events) = section {
                    count += events.len();
                }
            }
            count
        })
    }

    /// Get number of styles without manual parsing
    pub fn styles_count(&self) -> Result<usize> {
        self.parse_script_with(|script| {
            let mut count = 0;
            for section in script.sections() {
                if let Section::Styles(styles) = section {
                    count += styles.len();
                }
            }
            count
        })
    }

    /// Get script info field names
    pub fn script_info_fields(&self) -> Result<Vec<String>> {
        self.parse_script_with(|script| {
            let mut fields = Vec::new();
            for section in script.sections() {
                if let Section::ScriptInfo(info) = section {
                    for (key, _) in &info.fields {
                        fields.push(key.to_string());
                    }
                }
            }
            fields
        })
    }

    /// Get number of sections
    pub fn sections_count(&self) -> Result<usize> {
        self.parse_script_with(|script| script.sections().len())
    }

    /// Check if document has events section
    pub fn has_events(&self) -> Result<bool> {
        self.parse_script_with(|script| {
            script
                .sections()
                .iter()
                .any(|section| matches!(section, Section::Events(_)))
        })
    }

    /// Check if document has styles section
    pub fn has_styles(&self) -> Result<bool> {
        self.parse_script_with(|script| {
            script
                .sections()
                .iter()
                .any(|section| matches!(section, Section::Styles(_)))
        })
    }

    /// Get event text by line pattern (simplified search)
    pub fn find_event_text(&self, pattern: &str) -> Result<Vec<String>> {
        self.parse_script_with(|script| {
            let mut matches = Vec::new();
            for section in script.sections() {
                if let Section::Events(events) = section {
                    for event in events {
                        if event.text.contains(pattern) {
                            matches.push(event.text.to_string());
                        }
                    }
                }
            }
            matches
        })
    }

    /// Edit event by index with full field support
    ///
    /// Allows structured editing of specific event fields by index.
    /// Returns the modified event line for undo support.
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based index of the event to edit
    /// * `update_fn` - Function that receives the current event and returns modifications
    ///
    /// # Example
    ///
    /// ```rust
    /// # use ass_editor::core::EditorDocument;
    /// # let content = r#"[Script Info]
    /// # Title: Test
    /// #
    /// # [Events]
    /// # Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
    /// # Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,Original text"#;
    /// # let mut doc = EditorDocument::from_content(content).unwrap();
    /// doc.edit_event_by_index(0, |event| {
    ///     vec![
    ///         ("text", "New dialogue text".to_string()),
    ///         ("style", "NewStyle".to_string()),
    ///     ]
    /// })?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn edit_event_by_index<F>(&mut self, index: usize, update_fn: F) -> Result<String>
    where
        F: for<'a> FnOnce(&ass_core::parser::ast::Event<'a>) -> Vec<(&'static str, String)>,
    {
        let content = self.text();
        let mut event_info = None;
        let mut event_count = 0;

        // Find the event and its location in the document
        self.parse_script_with(|script| -> Result<()> {
            for section in script.sections() {
                if let Section::Events(events) = section {
                    for event in events {
                        if event_count == index {
                            // Get the modifications from the update function
                            let modifications = update_fn(event);

                            // Build a pattern to search for this specific event
                            let event_type_str = event.event_type.as_str();
                            let pattern = format!(
                                "{}: {},{},{}",
                                event_type_str, event.layer, event.start, event.end
                            );

                            let event_line = if let Some(pos) = content.find(&pattern) {
                                let line_end = content[pos..]
                                    .find('\n')
                                    .map(|n| pos + n)
                                    .unwrap_or(content.len());
                                let line = content[pos..line_end].to_string();
                                (pos, line_end, line)
                            } else {
                                return Err(EditorError::ValidationError {
                                    message: "Could not find event line in document".to_string(),
                                });
                            };

                            // Store the event data we need instead of cloning
                            let event_data = (
                                event.event_type,
                                event.layer.to_string(),
                                event.start.to_string(),
                                event.end.to_string(),
                                event.style.to_string(),
                                event.name.to_string(),
                                event.margin_l.to_string(),
                                event.margin_r.to_string(),
                                event.margin_v.to_string(),
                                event.effect.to_string(),
                                event.text.to_string(),
                            );
                            event_info = Some((event_data, event_line, modifications));
                            return Ok(());
                        }
                        event_count += 1;
                    }
                }
            }
            Ok(())
        })??;

        if let Some((event_data, (line_start, line_end, original_line), modifications)) = event_info
        {
            // Build the new event line with modifications
            let new_line = self.build_modified_event_line_from_data(
                event_data,
                &original_line,
                modifications,
            )?;

            // Replace the line in the document
            let range = Range::new(Position::new(line_start), Position::new(line_end));
            self.replace(range, &new_line)?;

            Ok(new_line)
        } else {
            Err(EditorError::InvalidRange {
                start: index,
                end: index + 1,
                length: event_count,
            })
        }
    }

    /// Helper to build a modified event line from event data
    fn build_modified_event_line_from_data(
        &self,
        event_data: (
            ass_core::parser::ast::EventType,
            String,
            String,
            String,
            String,
            String,
            String,
            String,
            String,
            String,
            String,
        ),
        _original_line: &str,
        modifications: Vec<(&'static str, String)>,
    ) -> Result<String> {
        let (
            event_type,
            layer,
            start,
            end,
            style,
            name,
            margin_l,
            margin_r,
            margin_v,
            effect,
            text,
        ) = event_data;

        // Apply modifications
        let mut layer = layer;
        let mut start = start;
        let mut end = end;
        let mut style = style;
        let mut name = name;
        let mut margin_l = margin_l;
        let mut margin_r = margin_r;
        let mut margin_v = margin_v;
        let mut effect = effect;
        let mut text = text;

        for (field, value) in modifications {
            match field {
                "layer" => layer = value,
                "start" => start = value,
                "end" => end = value,
                "style" => style = value,
                "name" => name = value,
                "margin_l" => margin_l = value,
                "margin_r" => margin_r = value,
                "margin_v" => margin_v = value,
                "effect" => effect = value,
                "text" => text = value,
                _ => {
                    return Err(EditorError::ValidationError {
                        message: format!("Unknown event field: {field}"),
                    });
                }
            }
        }

        // Rebuild the line
        let event_type_str = event_type.as_str();
        Ok(format!("{event_type_str}: {layer},{start},{end},{style},{name},{margin_l},{margin_r},{margin_v},{effect},{text}"))
    }

    /// Add event line to document
    pub fn add_event_line(&mut self, event_line: &str) -> Result<()> {
        let content = self.text();
        if let Some(events_pos) = content.find("[Events]") {
            // Find end of format line and add after it
            let format_start = content[events_pos..].find("Format:").unwrap_or(0) + events_pos;
            let line_end = content[format_start..].find('\n').unwrap_or(0) + format_start + 1;

            let insert_pos = Position::new(line_end);
            self.insert(insert_pos, &format!("{event_line}\n"))
        } else {
            // Add Events section if it doesn't exist
            let content_len = self.len_bytes();
            let events_section = format!("\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n{event_line}\n");
            self.insert(Position::new(content_len), &events_section)
        }
    }

    /// Edit style line
    pub fn edit_style_line(&mut self, style_name: &str, new_style_line: &str) -> Result<()> {
        let content = self.text();
        let pattern = format!("Style: {style_name},");

        if let Some(pos) = content.find(&pattern) {
            // Find end of line
            let line_end = content[pos..].find('\n').map_or(content.len(), |n| pos + n);
            let range = Range::new(Position::new(pos), Position::new(line_end));
            self.replace(range, new_style_line)
        } else {
            // Add style if it doesn't exist
            self.add_style_line(new_style_line)
        }
    }

    /// Add style line to document
    pub fn add_style_line(&mut self, style_line: &str) -> Result<()> {
        let content = self.text();
        if let Some(styles_pos) = content
            .find("[V4+ Styles]")
            .or_else(|| content.find("[V4 Styles]"))
        {
            // Find end of format line and add after it
            let format_start = content[styles_pos..].find("Format:").unwrap_or(0) + styles_pos;
            let line_end = content[format_start..].find('\n').unwrap_or(0) + format_start + 1;

            let insert_pos = Position::new(line_end);
            self.insert(insert_pos, &format!("{style_line}\n"))
        } else {
            // Add Styles section if it doesn't exist
            let script_info_end = content.find("\n[Events]").unwrap_or(content.len());
            let styles_section = format!("\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n{style_line}\n");
            self.insert(Position::new(script_info_end), &styles_section)
        }
    }

    // === INCREMENTAL PARSING WITH CORE INTEGRATION ===

    /// Perform incremental edit using core's parse_partial for optimal performance
    ///
    /// Includes error recovery with fallback strategies:
    /// 1. Try incremental parsing with Script::parse_partial()
    /// 2. On failure, fall back to full reparse
    /// 3. On repeated failures, reset parser state and retry
    #[cfg(feature = "stream")]
    pub fn edit_incremental(&mut self, range: Range, new_text: &str) -> Result<ScriptDeltaOwned> {
        use crate::core::history::Operation;

        // Fast path for simple edits that don't require full parsing
        let is_simple_edit = new_text.len() <= 100 && // Small to medium edits
            !new_text.contains('[') && // No new sections
            new_text.matches('\n').count() <= 1 && // At most one line break
            range.len() <= 50; // Small replacements

        if is_simple_edit {
            return self.edit_fast_path(range, new_text);
        }

        // Get the old text for undo data
        #[cfg(feature = "std")]
        let old_text = self.text_range(range)?;
        #[cfg(not(feature = "std"))]
        let _old_text = self.text_range(range)?;

        // Apply change with incremental parsing (includes fallback to full parse)
        let current_text = self.text();
        let delta = match self
            .incremental_parser
            .apply_change(&current_text, range, new_text)
        {
            Ok(delta) => delta,
            Err(_e) => {
                // Log the error for debugging
                #[cfg(feature = "std")]
                eprintln!("Incremental parsing failed, attempting recovery: {_e}");

                // If incremental parsing fails repeatedly, reset the parser
                if self.incremental_parser.should_reparse() {
                    self.incremental_parser.clear_cache();
                }

                // Try one more time with a fresh parser state
                match self
                    .incremental_parser
                    .apply_change(&current_text, range, new_text)
                {
                    Ok(delta) => delta,
                    Err(_) => {
                        // Final fallback: return a minimal delta indicating the change
                        ScriptDeltaOwned {
                            added: Vec::new(),
                            modified: vec![(0, "Script modified".to_string())],
                            removed: Vec::new(),
                            new_issues: Vec::new(),
                        }
                    }
                }
            }
        };

        // Create undo data from the delta (must be captured BEFORE applying changes)
        let undo_data = self.capture_delta_undo_data(&delta)?;

        // Create delta operation for history
        let operation = Operation::Delta {
            forward: delta.clone(),
            undo_data,
        };

        // Create command result
        let result = CommandResult::success_with_change(
            range,
            Position::new(range.start.offset + new_text.len()),
        );

        // Record in history
        let result_with_delta = result.with_delta(delta.clone());
        self.history.record_operation(
            operation,
            format!("Incremental edit at {}", range.start.offset),
            &result_with_delta,
        );

        // Apply the text change
        self.replace_raw(range, new_text)?;

        // Mark as modified
        self.modified = true;

        // Emit event
        #[cfg(feature = "std")]
        self.emit(DocumentEvent::TextReplaced {
            range,
            old_text,
            new_text: new_text.to_string(),
        });

        Ok(delta)
    }

    /// Insert text with incremental parsing (< 1ms target)
    #[cfg(feature = "stream")]
    pub fn insert_incremental(&mut self, pos: Position, text: &str) -> Result<ScriptDeltaOwned> {
        let range = Range::new(pos, pos); // Zero-length range for insertion
        self.edit_incremental(range, text)
    }

    /// Delete text with incremental parsing
    #[cfg(feature = "stream")]
    pub fn delete_incremental(&mut self, range: Range) -> Result<ScriptDeltaOwned> {
        self.edit_incremental(range, "")
    }

    /// Fast path for simple edits that avoids heavy parsing
    #[cfg(feature = "stream")]
    fn edit_fast_path(&mut self, range: Range, new_text: &str) -> Result<ScriptDeltaOwned> {
        use crate::core::history::Operation;

        // Validate that range boundaries are on valid UTF-8 char boundaries
        let text = self.text();
        if !text.is_char_boundary(range.start.offset) || !text.is_char_boundary(range.end.offset) {
            // Fall back to regular incremental parsing for invalid boundaries
            return self.edit_incremental_fallback(range, new_text);
        }

        // Get old text for undo
        let old_text = if range.is_empty() {
            String::new()
        } else {
            self.text_range(range)?
        };

        // Simple text replacement without parsing
        self.replace_raw(range, new_text)?;

        // Create minimal undo operation
        let operation = Operation::Replace {
            range,
            new_text: new_text.to_string(),
            old_text,
        };

        // Create result
        let result = CommandResult::success_with_change(
            range,
            Position::new(range.start.offset + new_text.len()),
        );

        // Record in history (without delta)
        self.history
            .record_operation(operation, "Fast character insert".to_string(), &result);

        // Mark as modified
        self.modified = true;

        // Return minimal delta
        Ok(ScriptDeltaOwned {
            added: Vec::new(),
            modified: Vec::new(),
            removed: Vec::new(),
            new_issues: Vec::new(),
        })
    }

    /// Fallback for edit_incremental that avoids infinite recursion
    #[cfg(feature = "stream")]
    fn edit_incremental_fallback(
        &mut self,
        range: Range,
        new_text: &str,
    ) -> Result<ScriptDeltaOwned> {
        // Just do a simple replace without the fast path
        self.replace(range, new_text)?;

        // Return minimal delta
        Ok(ScriptDeltaOwned {
            added: Vec::new(),
            modified: Vec::new(),
            removed: Vec::new(),
            new_issues: Vec::new(),
        })
    }

    /// Safe edit with automatic fallback to regular replace on error
    ///
    /// This method tries incremental parsing first for performance,
    /// but falls back to regular replace if incremental parsing is unavailable
    /// or fails. This ensures edits always succeed.
    pub fn edit_safe(&mut self, range: Range, new_text: &str) -> Result<()> {
        #[cfg(feature = "stream")]
        {
            // Try incremental parsing first
            match self.edit_incremental(range, new_text) {
                Ok(_) => return Ok(()),
                Err(_e) => {
                    #[cfg(feature = "std")]
                    eprintln!("Incremental edit failed, falling back to regular replace: {_e}");
                }
            }
        }

        // Fallback to regular replace
        self.replace(range, new_text)
    }

    /// Edit event using incremental parsing for performance
    #[cfg(feature = "stream")]
    pub fn edit_event_incremental(
        &mut self,
        event_text: &str,
        new_text: &str,
    ) -> Result<ScriptDeltaOwned> {
        let content = self.text();
        if let Some(pos) = content.find(event_text) {
            let range = Range::new(Position::new(pos), Position::new(pos + event_text.len()));
            self.edit_incremental(range, new_text)
        } else {
            Err(EditorError::ValidationError {
                message: format!("Event text not found: {event_text}"),
            })
        }
    }

    /// Parse with delta tracking for command system integration
    #[cfg(feature = "stream")]
    pub fn parse_with_delta_tracking<F, R>(
        &self,
        range: Option<StdRange<usize>>,
        new_text: Option<&str>,
        f: F,
    ) -> Result<R>
    where
        F: FnOnce(&Script, Option<&ScriptDeltaOwned>) -> R,
    {
        let content = self.text();
        let script = Script::parse(&content).map_err(EditorError::from)?;

        if let (Some(range), Some(text)) = (range, new_text) {
            // Get delta for the change
            match script.parse_partial(range, text) {
                Ok(delta) => Ok(f(&script, Some(&delta))),
                Err(_) => {
                    // Fallback to full re-parse if incremental fails
                    Ok(f(&script, None))
                }
            }
        } else {
            Ok(f(&script, None))
        }
    }

    /// Edit event using a builder for structured modifications
    ///
    /// Allows editing events using the EventBuilder fluent API. The builder
    /// is pre-populated with the current event's values, allowing selective
    /// field updates.
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based index of the event to edit  
    /// * `builder_fn` - Function that receives a pre-populated EventBuilder
    ///
    /// # Example
    ///
    /// ```rust
    /// # use ass_editor::core::EditorDocument;
    /// # let content = r#"[Script Info]
    /// # Title: Test
    /// #
    /// # [Events]
    /// # Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
    /// # Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,Original text"#;
    /// # let mut doc = EditorDocument::from_content(content).unwrap();
    /// # use ass_editor::core::builders::EventBuilder;
    /// doc.edit_event_with_builder(0, |builder| {
    ///     builder
    ///         .text("New dialogue text")
    ///         .style("NewStyle")
    ///         .end_time("0:00:10.00")
    /// })?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn edit_event_with_builder<F>(&mut self, index: usize, builder_fn: F) -> Result<String>
    where
        F: for<'a> FnOnce(
            crate::core::builders::EventBuilder,
        ) -> crate::core::builders::EventBuilder,
    {
        use crate::core::builders::EventBuilder;

        let content = self.text();
        let mut event_info = None;
        let mut event_count = 0;
        let mut format_line = None;

        // Find the event and extract format line
        self.parse_script_with(|script| -> Result<()> {
            for section in script.sections() {
                if let Section::Events(events) = section {
                    // Get format line if available
                    if format_line.is_none() {
                        // Find Events section header and format line in raw text
                        if let Some(events_pos) = content.find("[Events]") {
                            let after_header = &content[events_pos + 8..];
                            if let Some(format_pos) = after_header.find("Format:") {
                                let format_start = events_pos + 8 + format_pos + 7; // Skip "Format:"
                                if let Some(format_end) = content[format_start..].find('\n') {
                                    let format_str =
                                        content[format_start..format_start + format_end].trim();
                                    let fields: Vec<&str> =
                                        format_str.split(',').map(str::trim).collect();
                                    format_line = Some(fields);
                                }
                            }
                        }
                    }

                    for event in events {
                        if event_count == index {
                            // Create a builder pre-populated with current values
                            let mut builder = match event.event_type {
                                ass_core::parser::ast::EventType::Dialogue => {
                                    EventBuilder::dialogue()
                                }
                                ass_core::parser::ast::EventType::Comment => {
                                    EventBuilder::comment()
                                }
                                _ => EventBuilder::new(),
                            };

                            // Pre-populate builder with current event values
                            builder = builder
                                .layer(event.layer.parse::<u32>().unwrap_or(0))
                                .start_time(event.start)
                                .end_time(event.end)
                                .style(event.style)
                                .speaker(event.name)
                                .margin_left(event.margin_l.parse::<u32>().unwrap_or(0))
                                .margin_right(event.margin_r.parse::<u32>().unwrap_or(0))
                                .margin_vertical(event.margin_v.parse::<u32>().unwrap_or(0))
                                .effect(event.effect)
                                .text(event.text);

                            if let Some(margin_t) = event.margin_t {
                                builder = builder.margin_top(margin_t.parse::<u32>().unwrap_or(0));
                            }
                            if let Some(margin_b) = event.margin_b {
                                builder =
                                    builder.margin_bottom(margin_b.parse::<u32>().unwrap_or(0));
                            }

                            // Apply user modifications
                            let modified_builder = builder_fn(builder);

                            // Build the new event line
                            let new_line = if let Some(ref format_fields) = format_line {
                                modified_builder.build_with_format(format_fields)?
                            } else {
                                modified_builder.build()?
                            };

                            // Find the event line in the raw text
                            let event_type_str = event.event_type.as_str();
                            let pattern = format!(
                                "{}: {},{},{}",
                                event_type_str, event.layer, event.start, event.end
                            );

                            let event_line = if let Some(pos) = content.find(&pattern) {
                                let line_end = content[pos..]
                                    .find('\n')
                                    .map(|n| pos + n)
                                    .unwrap_or(content.len());
                                (pos, line_end)
                            } else {
                                return Err(EditorError::ValidationError {
                                    message: "Could not find event line in document".to_string(),
                                });
                            };

                            event_info = Some((event_line, new_line));
                            return Ok(());
                        }
                        event_count += 1;
                    }
                }
            }
            Ok(())
        })??;

        if let Some(((line_start, line_end), new_line)) = event_info {
            // Replace the line in the document
            let range = Range::new(Position::new(line_start), Position::new(line_end));
            self.replace(range, &new_line)?;

            Ok(new_line)
        } else {
            Err(EditorError::InvalidRange {
                start: index,
                end: index + 1,
                length: event_count,
            })
        }
    }

    /// Edit an event by finding and replacing text (simplified ASS-aware editing)
    pub fn edit_event_text(&mut self, old_text: &str, new_text: &str) -> Result<()> {
        let content = self.text();

        if let Some(pos) = content.find(old_text) {
            let range = Range::new(Position::new(pos), Position::new(pos + old_text.len()));
            self.replace(range, new_text)?;
        }

        Ok(())
    }

    /// Get script info field value by key
    pub fn get_script_info_field(&self, key: &str) -> Result<Option<String>> {
        self.parse_script_with(|script| {
            script.sections().iter().find_map(|section| {
                if let Section::ScriptInfo(info) = section {
                    info.fields
                        .iter()
                        .find(|(k, _)| *k == key)
                        .map(|(_, v)| v.to_string())
                } else {
                    None
                }
            })
        })
    }

    /// Set script info field (ASS-aware editing)
    pub fn set_script_info_field(&mut self, key: &str, value: &str) -> Result<()> {
        // Simplified implementation - find and replace the field
        let content = self.text();
        let field_pattern = format!("{key}:");

        if let Some(pos) = content.find(&field_pattern) {
            // Find end of line
            let line_start = pos;
            let line_end = content[pos..].find('\n').map_or(content.len(), |n| pos + n);

            let range = Range::new(Position::new(line_start), Position::new(line_end));

            let new_line = format!("{key}: {value}");
            self.replace(range, &new_line)?;
        }

        Ok(())
    }

    /// Perform an undo operation
    ///
    /// Retrieves the most recent operation from the undo stack and reverses it.
    /// If the operation includes a script delta, it will be applied for efficient updates.
    pub fn undo(&mut self) -> Result<CommandResult> {
        use crate::core::history::Operation;

        // Pop from undo stack
        if let Some(entry) = self.history.pop_undo_entry() {
            let mut result = CommandResult::success();
            result.content_changed = true;

            // Execute the inverse of the operation
            match &entry.operation {
                Operation::Insert { position, text } => {
                    // Undo insert by deleting the inserted text
                    let end_pos = Position::new(position.offset + text.len());
                    let range = Range::new(*position, end_pos);
                    self.delete_raw(range)?;
                    result.modified_range = Some(Range::new(*position, *position));
                    result.new_cursor = entry.cursor_before;
                }
                Operation::Delete {
                    range,
                    deleted_text,
                } => {
                    // Undo delete by inserting the deleted text
                    self.insert_raw(range.start, deleted_text)?;
                    let end_pos = Position::new(range.start.offset + deleted_text.len());
                    result.modified_range = Some(Range::new(range.start, end_pos));
                    result.new_cursor = entry.cursor_before;
                }
                Operation::Replace {
                    range, old_text, ..
                } => {
                    // Undo replace by restoring old text
                    self.replace_raw(*range, old_text)?;
                    let end_pos = Position::new(range.start.offset + old_text.len());
                    result.modified_range = Some(Range::new(range.start, end_pos));
                    result.new_cursor = entry.cursor_before;
                }
                #[cfg(feature = "stream")]
                Operation::Delta { forward, undo_data } => {
                    // Restore removed sections
                    for (index, section_text) in undo_data.removed_sections.iter() {
                        self.insert_section_at(*index, section_text)?;
                    }

                    // Restore modified sections
                    for (index, original_text) in undo_data.modified_sections.iter() {
                        self.replace_section(*index, original_text)?;
                    }

                    // Remove added sections
                    for _ in 0..forward.added.len() {
                        self.remove_last_section()?;
                    }

                    result.message = Some("Delta operation undone".to_string());
                }
            }

            // Push to redo stack for future redo
            self.history.push_redo_entry(entry);

            // Apply script delta if available
            #[cfg(feature = "stream")]
            if let Some(delta) = result.script_delta.as_ref() {
                self.apply_script_delta(delta.clone())?;
            }

            result.message = Some("Undo successful".to_string());
            Ok(result)
        } else {
            Err(EditorError::NothingToUndo)
        }
    }

    /// Perform a redo operation
    ///
    /// Retrieves the most recent operation from the redo stack and re-executes it.
    /// If the operation includes a script delta, it will be applied for efficient updates.
    pub fn redo(&mut self) -> Result<CommandResult> {
        use crate::core::history::Operation;

        // Pop from redo stack
        if let Some(entry) = self.history.pop_redo_entry() {
            let mut result = CommandResult::success();
            result.content_changed = true;

            // Re-execute the original operation
            match &entry.operation {
                Operation::Insert { position, text } => {
                    // Redo insert
                    self.insert_raw(*position, text)?;
                    let end_pos = Position::new(position.offset + text.len());
                    result.modified_range = Some(Range::new(*position, end_pos));
                    result.new_cursor = entry.cursor_after;
                }
                Operation::Delete { range, .. } => {
                    // Redo delete
                    self.delete_raw(*range)?;
                    result.modified_range = Some(Range::new(range.start, range.start));
                    result.new_cursor = entry.cursor_after;
                }
                Operation::Replace {
                    range, new_text, ..
                } => {
                    // Redo replace
                    self.replace_raw(*range, new_text)?;
                    let end_pos = Position::new(range.start.offset + new_text.len());
                    result.modified_range = Some(Range::new(range.start, end_pos));
                    result.new_cursor = entry.cursor_after;
                }
                #[cfg(feature = "stream")]
                Operation::Delta {
                    forward,
                    undo_data: _,
                } => {
                    // Re-apply the delta
                    self.apply_script_delta(forward.clone())?;
                    result.message = Some("Delta re-applied".to_string());
                }
            }

            // Record in history without using the public methods (to avoid recursion)
            // We need to manually update the history manager's cursor
            if let Some(cursor) = result.new_cursor {
                self.history.set_cursor(Some(cursor));
            }

            // Create a new history entry for the redo operation
            let new_entry = crate::core::history::HistoryEntry::new(
                entry.operation,
                entry.description,
                &result,
                entry.cursor_before,
            );

            // Push back to undo stack
            self.history.stack_mut().push(new_entry);

            result.message = Some("Redo successful".to_string());
            Ok(result)
        } else {
            Err(EditorError::NothingToRedo)
        }
    }

    /// Check if undo is available
    pub fn can_undo(&self) -> bool {
        self.history.can_undo()
    }

    /// Check if redo is available
    pub fn can_redo(&self) -> bool {
        self.history.can_redo()
    }

    /// Get description of the next undo operation
    pub fn next_undo_description(&self) -> Option<&str> {
        self.history.next_undo_description()
    }

    /// Get description of the next redo operation
    pub fn next_redo_description(&self) -> Option<&str> {
        self.history.next_redo_description()
    }

    /// Get mutable reference to the undo manager for configuration
    pub fn undo_manager_mut(&mut self) -> &mut UndoManager {
        &mut self.history
    }

    /// Get reference to the undo manager
    pub fn undo_manager(&self) -> &UndoManager {
        &self.history
    }

    /// Apply a script delta and record it with undo data
    #[cfg(feature = "stream")]
    pub fn apply_script_delta(&mut self, delta: ScriptDeltaOwned) -> Result<()> {
        use crate::core::history::Operation;

        // Capture undo data before applying
        let undo_data = self.capture_delta_undo_data(&delta)?;

        // Apply delta
        self.apply_script_delta_internal(delta.clone())?;

        // Record with undo data
        let operation = Operation::Delta {
            forward: delta,
            undo_data,
        };

        let result = CommandResult::success();
        self.history
            .record_operation(operation, "Apply delta".to_string(), &result);

        Ok(())
    }

    /// Capture undo data before applying a delta
    #[cfg(feature = "stream")]
    fn capture_delta_undo_data(
        &self,
        delta: &ScriptDeltaOwned,
    ) -> Result<crate::core::history::DeltaUndoData> {
        let mut removed_sections = Vec::new();
        let mut modified_sections = Vec::new();

        // First, get the current content for section extraction
        let content = self.text();

        // For incremental edits, use simplified undo data to avoid expensive full parsing
        // Only do detailed section analysis for larger operations
        #[cfg(feature = "stream")]
        let is_small_edit = delta.added.len() + delta.removed.len() + delta.modified.len() <= 2;
        #[cfg(not(feature = "stream"))]
        let is_small_edit = false;

        if is_small_edit {
            // For small incremental edits, skip expensive undo data capture
            // The basic text-based undo in edit_incremental will handle this
        } else {
            // For larger operations, do full undo data capture
            let _ = self.parse_script_with(|script| {
                // Capture removed sections
                for &index in &delta.removed {
                    if let Some(section) = script.sections().get(index) {
                        match self.extract_section_text(&content, section) {
                            Ok(section_text) => removed_sections.push((index, section_text)),
                            Err(_) => {
                                // If we can't extract the section text, store a placeholder
                                removed_sections.push((index, String::new()));
                            }
                        }
                    }
                }

                // Capture original state of modified sections
                for (index, _) in &delta.modified {
                    if let Some(section) = script.sections().get(*index) {
                        match self.extract_section_text(&content, section) {
                            Ok(section_text) => modified_sections.push((*index, section_text)),
                            Err(_) => {
                                // If we can't extract the section text, store a placeholder
                                modified_sections.push((*index, String::new()));
                            }
                        }
                    }
                }

                Ok::<(), EditorError>(())
            })?;
        }

        Ok(crate::core::history::DeltaUndoData {
            removed_sections,
            modified_sections,
        })
    }

    /// Extract section text from content
    #[cfg(feature = "stream")]
    fn extract_section_text(&self, content: &str, section: &Section) -> Result<String> {
        let header = match section {
            Section::ScriptInfo(_) => "[Script Info]",
            Section::Styles(_) => "[V4+ Styles]",
            Section::Events(_) => "[Events]",
            Section::Fonts(_) => "[Fonts]",
            Section::Graphics(_) => "[Graphics]",
        };

        // Find the header in the content
        let start = content
            .find(header)
            .ok_or_else(|| EditorError::SectionNotFound {
                section: header.to_string(),
            })?;

        // Find the next section header or end of document
        let section_headers = [
            "[Script Info]",
            "[V4+ Styles]",
            "[Events]",
            "[Fonts]",
            "[Graphics]",
        ];

        let end = content[start + header.len()..]
            .find(|_c: char| {
                for sh in &section_headers {
                    if content[start + header.len()..].starts_with(sh) {
                        return true;
                    }
                }
                false
            })
            .map(|pos| start + header.len() + pos)
            .unwrap_or(content.len());

        Ok(content[start..end].to_string())
    }

    /// Apply a script delta for efficient incremental parsing (internal)
    #[cfg(feature = "stream")]
    fn apply_script_delta_internal(&mut self, delta: ScriptDeltaOwned) -> Result<()> {
        // Parse the current script to get sections
        let current_content = self.text();
        let script = Script::parse(&current_content).map_err(EditorError::from)?;

        // Apply removals first (in reverse order to maintain indices)
        let mut removed_indices = delta.removed.clone();
        removed_indices.sort_by(|a, b| b.cmp(a)); // Sort descending

        for index in removed_indices {
            if index < script.sections().len() {
                // Find the section's text range and remove it
                let section = &script.sections()[index];
                let start_offset = self.find_section_start(section)?;
                let end_offset = self.find_section_end(section)?;

                self.delete_raw(Range::new(
                    Position::new(start_offset),
                    Position::new(end_offset),
                ))?;
            }
        }

        // Apply modifications
        for (index, new_section_text) in delta.modified {
            if index < script.sections().len() {
                // Find the section's text range
                let section = &script.sections()[index];
                let start_offset = self.find_section_start(section)?;
                let end_offset = self.find_section_end(section)?;

                // Replace with new section text
                self.replace_raw(
                    Range::new(Position::new(start_offset), Position::new(end_offset)),
                    &new_section_text,
                )?;
            }
        }

        // Apply additions
        for section_text in delta.added {
            // Add new sections at the end of the document
            let end_pos = Position::new(self.len_bytes());

            // Ensure proper newline before new section
            if self.len_bytes() > 0 && !self.text().ends_with('\n') {
                self.insert_raw(end_pos, "\n")?;
            }

            self.insert_raw(Position::new(self.len_bytes()), &section_text)?;

            // Ensure trailing newline
            if !section_text.ends_with('\n') {
                self.insert_raw(Position::new(self.len_bytes()), "\n")?;
            }
        }

        // Validate the result
        let _ = Script::parse(&self.text()).map_err(EditorError::from)?;

        Ok(())
    }

    /// Find the start offset of a section in the document
    #[cfg(feature = "stream")]
    fn find_section_start(&self, section: &Section) -> Result<usize> {
        // Get the section header text
        let header = match section {
            Section::ScriptInfo(_) => "[Script Info]",
            Section::Styles(_) => "[V4+ Styles]",
            Section::Events(_) => "[Events]",
            Section::Fonts(_) => "[Fonts]",
            Section::Graphics(_) => "[Graphics]",
        };

        // Find the header in the document
        if let Some(pos) = self.text().find(header) {
            Ok(pos)
        } else {
            Err(EditorError::SectionNotFound {
                section: header.to_string(),
            })
        }
    }

    /// Find the end offset of a section in the document
    #[cfg(feature = "stream")]
    fn find_section_end(&self, section: &Section) -> Result<usize> {
        let start = self.find_section_start(section)?;
        let content = &self.text()[start..];

        // Find the next section header or end of document
        let section_headers = [
            "[Script Info]",
            "[V4+ Styles]",
            "[Events]",
            "[Fonts]",
            "[Graphics]",
        ];

        let mut end_offset = content.len();
        for header in &section_headers {
            if let Some(pos) = content.find(header) {
                if pos > 0 {
                    end_offset = end_offset.min(pos);
                }
            }
        }

        Ok(start + end_offset)
    }

    /// Delete text in range (low-level operation without undo)
    pub(crate) fn delete_raw(&mut self, range: Range) -> Result<()> {
        if range.end.offset > self.len_bytes() {
            return Err(EditorError::InvalidRange {
                start: range.start.offset,
                end: range.end.offset,
                length: self.len_bytes(),
            });
        }

        #[cfg(feature = "rope")]
        {
            // Convert byte offsets to char indices for rope operations
            let start_char = self.text_rope.byte_to_char(range.start.offset);
            let end_char = self.text_rope.byte_to_char(range.end.offset);
            self.text_rope.remove(start_char..end_char);
        }
        #[cfg(not(feature = "rope"))]
        {
            self.text_content
                .drain(range.start.offset..range.end.offset);
        }

        self.modified = true;
        Ok(())
    }

    /// Replace text in range (low-level operation without undo)
    pub(crate) fn replace_raw(&mut self, range: Range, text: &str) -> Result<()> {
        self.delete_raw(range)?;
        self.insert_raw(range.start, text)?;
        Ok(())
    }

    // === Delta undo/redo helper methods ===

    /// Insert a section at a specific index
    #[cfg(feature = "stream")]
    fn insert_section_at(&mut self, index: usize, section_text: &str) -> Result<()> {
        // Get the current sections count
        let section_count = self.parse_script_with(|script| script.sections().len())?;

        // If index is beyond current sections, append to end
        if index >= section_count {
            let end_pos = Position::new(self.len_bytes());

            // Ensure proper newline before new section
            if self.len_bytes() > 0 && !self.text().ends_with('\n') {
                self.insert_raw(end_pos, "\n")?;
            }

            self.insert_raw(Position::new(self.len_bytes()), section_text)?;

            // Ensure trailing newline
            if !section_text.ends_with('\n') {
                self.insert_raw(Position::new(self.len_bytes()), "\n")?;
            }

            return Ok(());
        }

        // Find the position where to insert the new section
        let content = self.text();
        let insert_pos = self.parse_script_with(|script| -> Result<usize> {
            if let Some(section) = script.sections().get(index) {
                // Find the start of this section to insert before it
                let header = match section {
                    Section::ScriptInfo(_) => "[Script Info]",
                    Section::Styles(_) => "[V4+ Styles]",
                    Section::Events(_) => "[Events]",
                    Section::Fonts(_) => "[Fonts]",
                    Section::Graphics(_) => "[Graphics]",
                };

                if let Some(pos) = content.find(header) {
                    Ok(pos)
                } else {
                    Err(EditorError::SectionNotFound {
                        section: header.to_string(),
                    })
                }
            } else {
                // Append to end if index is out of bounds
                Ok(content.len())
            }
        })??;

        // Insert the section at the found position
        let mut text_to_insert = section_text.to_string();

        // Ensure section ends with newline
        if !text_to_insert.ends_with('\n') {
            text_to_insert.push('\n');
        }

        // Add extra newline if needed to separate from next section
        if insert_pos < content.len() {
            text_to_insert.push('\n');
        }

        self.insert_raw(Position::new(insert_pos), &text_to_insert)?;

        Ok(())
    }

    /// Replace a section at a specific index
    #[cfg(feature = "stream")]
    fn replace_section(&mut self, index: usize, new_text: &str) -> Result<()> {
        // Parse to find the section and get its boundaries
        // Get the section to replace
        let content = self.text();
        let section_info: Result<Option<&str>> = self.parse_script_with(|script| {
            if let Some(section) = script.sections().get(index) {
                let header = match section {
                    Section::ScriptInfo(_) => "[Script Info]",
                    Section::Styles(_) => "[V4+ Styles]",
                    Section::Events(_) => "[Events]",
                    Section::Fonts(_) => "[Fonts]",
                    Section::Graphics(_) => "[Graphics]",
                };
                Ok(Some(header))
            } else {
                Ok(None)
            }
        })?;

        if let Some(header) = section_info? {
            let start = self.find_section_start_by_header(&content, header)?;
            let end = self.find_section_end_from_start(&content, start)?;

            self.replace_raw(
                Range::new(Position::new(start), Position::new(end)),
                new_text,
            )?;
        }

        Ok(())
    }

    /// Remove the last section
    #[cfg(feature = "stream")]
    fn remove_last_section(&mut self) -> Result<()> {
        // Parse to find the last section and get its boundaries
        // Get the last section
        let content = self.text();
        let section_info: Result<Option<&str>> = self.parse_script_with(|script| {
            if let Some(section) = script.sections().last() {
                let header = match section {
                    Section::ScriptInfo(_) => "[Script Info]",
                    Section::Styles(_) => "[V4+ Styles]",
                    Section::Events(_) => "[Events]",
                    Section::Fonts(_) => "[Fonts]",
                    Section::Graphics(_) => "[Graphics]",
                };
                Ok(Some(header))
            } else {
                Ok(None)
            }
        })?;

        if let Some(header) = section_info? {
            let start = self.find_section_start_by_header(&content, header)?;
            let end = self.find_section_end_from_start(&content, start)?;

            self.delete_raw(Range::new(Position::new(start), Position::new(end)))?;
        }

        Ok(())
    }

    /// Find section start by header
    #[cfg(feature = "stream")]
    fn find_section_start_by_header(&self, content: &str, header: &str) -> Result<usize> {
        content
            .find(header)
            .ok_or_else(|| EditorError::SectionNotFound {
                section: header.to_string(),
            })
    }

    /// Find section end from start position
    #[cfg(feature = "stream")]
    fn find_section_end_from_start(&self, content: &str, start: usize) -> Result<usize> {
        let section_headers = [
            "[Script Info]",
            "[V4+ Styles]",
            "[Events]",
            "[Fonts]",
            "[Graphics]",
        ];

        // Find the next section header after start
        let mut end = content.len();
        for header in &section_headers {
            if let Some(pos) = content[start + 1..].find(header) {
                let actual_pos = start + 1 + pos;
                if actual_pos < end {
                    end = actual_pos;
                }
            }
        }

        Ok(end)
    }
}

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

/// Fluent position API for editor operations
pub struct DocumentPosition<'a> {
    document: &'a mut EditorDocument,
    position: Position,
}

impl<'a> DocumentPosition<'a> {
    /// Insert text at this position
    pub fn insert_text(self, text: &str) -> Result<()> {
        self.document.insert(self.position, text)
    }

    /// Delete text range starting from this position
    pub fn delete_range(self, len: usize) -> Result<()> {
        let end_pos = Position::new(self.position.offset + len);
        let range = Range::new(self.position, end_pos);
        self.document.delete(range)
    }

    /// Replace text at this position
    pub fn replace_text(self, len: usize, new_text: &str) -> Result<()> {
        let end_pos = Position::new(self.position.offset + len);
        let range = Range::new(self.position, end_pos);
        self.document.replace(range, new_text)
    }
}

impl EditorDocument {
    /// Get fluent API for position-based operations
    pub fn at(&mut self, pos: Position) -> DocumentPosition {
        DocumentPosition {
            document: self,
            position: pos,
        }
    }

    /// Initialize the extension registry with built-in handlers
    #[cfg(feature = "plugins")]
    pub fn initialize_registry(&mut self) -> Result<()> {
        use crate::extensions::registry_integration::RegistryIntegration;

        let mut integration = RegistryIntegration::new();

        // Register all built-in extensions using the function from the builtin module
        crate::extensions::builtin::register_builtin_extensions(&mut integration)?;

        self.registry_integration = Some(Arc::new(integration));
        Ok(())
    }

    /// Get the extension registry for use in parsing
    #[cfg(feature = "plugins")]
    pub fn registry(&self) -> Option<&ass_core::plugin::ExtensionRegistry> {
        self.registry_integration
            .as_ref()
            .map(|integration| integration.registry())
    }

    /// Parse the document content with extension support and process it with a callback
    ///
    /// Since Script<'a> requires the source text to outlive it, this method uses a callback
    /// pattern to process the script while the content is still in scope.
    #[cfg(feature = "plugins")]
    pub fn parse_with_extensions<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce(&ass_core::parser::Script) -> R,
    {
        let content = self.text();

        if let Some(integration) = &self.registry_integration {
            // Parse with the extension registry using the builder pattern
            let script = ass_core::parser::Script::builder()
                .with_registry(integration.registry())
                .parse(&content)
                .map_err(EditorError::Core)?;
            Ok(f(&script))
        } else {
            // No registry, parse normally
            let script = ass_core::parser::Script::parse(&content).map_err(EditorError::Core)?;
            Ok(f(&script))
        }
    }

    /// Register a custom tag handler
    #[cfg(feature = "plugins")]
    pub fn register_tag_handler(
        &mut self,
        extension_name: String,
        handler: Box<dyn ass_core::plugin::TagHandler>,
    ) -> Result<()> {
        if self.registry_integration.is_none() {
            self.initialize_registry()?;
        }

        let registry_ref =
            self.registry_integration
                .as_mut()
                .ok_or_else(|| EditorError::ExtensionError {
                    extension: extension_name.clone(),
                    message: "Registry integration not available".to_string(),
                })?;

        if let Some(integration) = Arc::get_mut(registry_ref) {
            integration.register_custom_tag_handler(extension_name, handler)
        } else {
            Err(EditorError::ExtensionError {
                extension: extension_name,
                message: "Cannot modify shared registry integration".to_string(),
            })
        }
    }

    /// Register a custom section processor
    #[cfg(feature = "plugins")]
    pub fn register_section_processor(
        &mut self,
        extension_name: String,
        processor: Box<dyn ass_core::plugin::SectionProcessor>,
    ) -> Result<()> {
        if self.registry_integration.is_none() {
            self.initialize_registry()?;
        }

        let registry_ref =
            self.registry_integration
                .as_mut()
                .ok_or_else(|| EditorError::ExtensionError {
                    extension: extension_name.clone(),
                    message: "Registry integration not available".to_string(),
                })?;

        if let Some(integration) = Arc::get_mut(registry_ref) {
            integration.register_custom_section_processor(extension_name, processor)
        } else {
            Err(EditorError::ExtensionError {
                extension: extension_name,
                message: "Cannot modify shared registry integration".to_string(),
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(not(feature = "std"))]
    use alloc::string::ToString;
    #[cfg(not(feature = "std"))]
    use alloc::vec;

    #[test]
    fn document_creation() {
        let doc = EditorDocument::new();
        assert!(doc.is_empty());
        assert_eq!(doc.len_lines(), 1);
        assert!(!doc.is_modified());
    }

    #[test]
    fn document_from_content() {
        let content = "[Script Info]\nTitle: Test";
        let doc = EditorDocument::from_content(content).unwrap();
        assert_eq!(doc.text(), content);
        assert_eq!(doc.len_bytes(), content.len());
    }

    #[test]
    fn document_modification() {
        let mut doc = EditorDocument::new();
        doc.insert(Position::new(0), "Hello").unwrap();
        assert!(doc.is_modified());
        assert_eq!(doc.text(), "Hello");
    }

    #[test]
    fn position_conversion() {
        let content = "Line 1\nLine 2\nLine 3";
        let doc = EditorDocument::from_content(content).unwrap();

        // Start of second line
        let pos = Position::new(7); // After "Line 1\n"
        let lc = doc.position_to_line_column(pos).unwrap();
        assert_eq!(lc.line, 2);
        assert_eq!(lc.column, 1);
    }

    #[test]
    fn range_operations() {
        let mut doc = EditorDocument::from_content("Hello World").unwrap();

        // Delete "World"
        let range = Range::new(Position::new(6), Position::new(11));
        doc.delete(range).unwrap();
        assert_eq!(doc.text(), "Hello ");

        // Replace with "Rust"
        doc.insert(Position::new(6), "Rust").unwrap();
        assert_eq!(doc.text(), "Hello Rust");
    }

    #[test]
    fn parse_script_test() {
        let content = "[Script Info]\nTitle: Test\n[Events]\nDialogue: test";
        let doc = EditorDocument::from_content(content).unwrap();

        // Validate should succeed
        doc.validate().unwrap();

        // Parse and use script
        let sections_count = doc.sections_count().unwrap();
        assert!(sections_count > 0);
    }

    #[test]
    fn test_edit_event_by_index() {
        let content = r#"[Script Info]
Title: Test

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,First event
Dialogue: 0,0:00:05.00,0:00:10.00,Default,,0,0,0,,Second event
Dialogue: 0,0:00:10.00,0:00:15.00,Default,,0,0,0,,Third event"#;

        let mut doc = EditorDocument::from_content(content).unwrap();

        // Edit the second event (index 1)
        let result = doc.edit_event_by_index(1, |_event| {
            vec![
                ("text", "Modified second event".to_string()),
                ("style", "NewStyle".to_string()),
                ("start", "0:00:06.00".to_string()),
            ]
        });

        assert!(result.is_ok());
        let new_line = result.unwrap();
        assert!(new_line.contains("Modified second event"));
        assert!(new_line.contains("NewStyle"));
        assert!(new_line.contains("0:00:06.00"));

        // Verify the document was updated
        let updated_content = doc.text();
        assert!(updated_content.contains("Modified second event"));
        assert!(updated_content.contains("NewStyle"));
        assert!(updated_content.contains("0:00:06.00"));
        assert!(!updated_content.contains("Second event")); // Old text should be gone
    }

    #[test]
    fn test_edit_event_by_index_out_of_bounds() {
        let content = r#"[Script Info]
Title: Test

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,First event"#;

        let mut doc = EditorDocument::from_content(content).unwrap();

        // Try to edit non-existent event
        let result =
            doc.edit_event_by_index(5, |_event| vec![("text", "This should fail".to_string())]);

        assert!(result.is_err());
        match result.err().unwrap() {
            EditorError::InvalidRange { start, end, length } => {
                assert_eq!(start, 5);
                assert_eq!(end, 6);
                assert_eq!(length, 1); // Only 1 event exists
            }
            _ => panic!("Expected InvalidRange error"),
        }
    }

    #[test]
    fn test_edit_event_with_builder() {
        let content = r#"[Script Info]
Title: Test

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:00.00,0:00:05.00,Default,Speaker,0,0,0,,Original text
Dialogue: 0,0:00:05.00,0:00:10.00,Default,,0,0,0,,Second event"#;

        let mut doc = EditorDocument::from_content(content).unwrap();

        // Edit the first event using builder
        let result = doc.edit_event_with_builder(0, |builder| {
            builder
                .text("Modified with builder")
                .style("NewStyle")
                .end_time("0:00:08.00")
                .speaker("NewSpeaker")
        });

        assert!(result.is_ok());
        let new_line = result.unwrap();
        assert!(new_line.contains("Modified with builder"));
        assert!(new_line.contains("NewStyle"));
        assert!(new_line.contains("0:00:08.00"));
        assert!(new_line.contains("NewSpeaker"));

        // Verify the document was updated
        let updated_content = doc.text();
        assert!(updated_content.contains("Modified with builder"));
        assert!(updated_content.contains("0:00:08.00"));
        assert!(!updated_content.contains("Original text"));
    }

    #[test]
    fn test_edit_event_with_builder_preserves_format() {
        // Test with V4++ format that includes MarginT and MarginB
        let content = r#"[Script Info]
Title: Test

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginT, MarginB, Effect, Text
Dialogue: 0,0:00:00.00,0:00:05.00,Default,,10,20,5,15,fade,Original text"#;

        let mut doc = EditorDocument::from_content(content).unwrap();

        // Edit preserving the V4++ format
        let result = doc.edit_event_with_builder(0, |builder| {
            builder.text("New text").margin_top(30).margin_bottom(40)
        });

        assert!(result.is_ok());
        let new_line = result.unwrap();

        // Should use MarginT and MarginB fields based on format line
        assert!(new_line.contains("30")); // margin_top
        assert!(new_line.contains("40")); // margin_bottom
        assert!(new_line.contains("New text"));
        assert!(new_line.contains("10,20,30,40")); // All margins in correct order
    }

    #[test]
    fn test_edit_event_with_builder_comment() {
        let content = r#"[Script Info]
Title: Test

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Comment: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,This is a comment"#;

        let mut doc = EditorDocument::from_content(content).unwrap();

        // Edit comment event
        let result = doc.edit_event_with_builder(0, |builder| builder.text("Updated comment"));

        assert!(result.is_ok());
        let new_line = result.unwrap();
        assert!(new_line.starts_with("Comment:"));
        assert!(new_line.contains("Updated comment"));
    }

    #[test]
    fn test_edit_event_by_index_all_fields() {
        let content = r#"[Script Info]
Title: Test

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:00.00,0:00:05.00,Default,Speaker,10,20,30,fade,Original text"#;

        let mut doc = EditorDocument::from_content(content).unwrap();

        // Edit all possible fields
        let result = doc.edit_event_by_index(0, |_event| {
            vec![
                ("layer", "1".to_string()),
                ("start", "0:00:01.00".to_string()),
                ("end", "0:00:06.00".to_string()),
                ("style", "Custom".to_string()),
                ("name", "NewSpeaker".to_string()),
                ("margin_l", "15".to_string()),
                ("margin_r", "25".to_string()),
                ("margin_v", "35".to_string()),
                ("effect", "scroll".to_string()),
                ("text", "Completely new text".to_string()),
            ]
        });

        assert!(result.is_ok());
        let new_line = result.unwrap();

        // Verify all fields were updated
        assert!(new_line.contains("Dialogue: 1,"));
        assert!(new_line.contains("0:00:01.00"));
        assert!(new_line.contains("0:00:06.00"));
        assert!(new_line.contains("Custom"));
        assert!(new_line.contains("NewSpeaker"));
        assert!(new_line.contains("15"));
        assert!(new_line.contains("25"));
        assert!(new_line.contains("35"));
        assert!(new_line.contains("scroll"));
        assert!(new_line.contains("Completely new text"));
    }

    #[test]
    fn test_undo_redo_basic() {
        let mut doc = EditorDocument::from_content("[Script Info]\nTitle: Test").unwrap();
        let initial_len = doc.len_bytes();
        // println!(
        //     "Initial doc length: {}, content: {:?}",
        //     initial_len,
        //     doc.text()
        // );

        // Insert some text
        doc.insert(Position::new(initial_len), "\nAuthor: John")
            .unwrap();
        // println!(
        //     "After insert: length: {}, content: {:?}",
        //     doc.len_bytes(),
        //     doc.text()
        // );
        assert!(doc.text().contains("Author: John"));
        assert!(doc.can_undo());
        assert!(!doc.can_redo());

        // Undo the insert
        let result = doc.undo().unwrap();
        // println!(
        //     "After undo: length: {}, content: {:?}",
        //     doc.len_bytes(),
        //     doc.text()
        // );
        assert!(result.success);
        assert!(!doc.text().contains("Author: John"));
        assert!(!doc.can_undo());
        assert!(doc.can_redo());

        // Redo the insert
        // println!("About to redo...");
        let result = doc.redo().unwrap();
        // println!(
        //     "After redo: length: {}, content: {:?}",
        //     doc.len_bytes(),
        //     doc.text()
        // );
        assert!(result.success);
        assert!(doc.text().contains("Author: John"));
        assert!(doc.can_undo());
        assert!(!doc.can_redo());
    }

    #[test]
    fn test_undo_redo_multiple_operations() {
        let mut doc = EditorDocument::from_content("[Script Info]\nTitle: Test").unwrap();

        // Multiple operations
        doc.insert(Position::new(doc.len_bytes()), "\nAuthor: John")
            .unwrap();
        doc.insert(Position::new(doc.len_bytes()), "\nVersion: 1.0")
            .unwrap();
        doc.insert(Position::new(doc.len_bytes()), "\nComment: Test script")
            .unwrap();

        assert!(doc.text().contains("Author: John"));
        assert!(doc.text().contains("Version: 1.0"));
        assert!(doc.text().contains("Comment: Test script"));

        // Undo all operations
        doc.undo().unwrap();
        assert!(!doc.text().contains("Comment: Test script"));

        doc.undo().unwrap();
        assert!(!doc.text().contains("Version: 1.0"));

        doc.undo().unwrap();
        assert!(!doc.text().contains("Author: John"));

        // Redo one operation
        doc.redo().unwrap();
        assert!(doc.text().contains("Author: John"));
        assert!(!doc.text().contains("Version: 1.0"));
    }

    #[test]
    fn test_undo_redo_replace() {
        let mut doc = EditorDocument::from_content("[Script Info]\nTitle: Original").unwrap();

        // Find and replace "Original" with "Modified"
        let start = doc.text().find("Original").unwrap();
        let range = Range::new(Position::new(start), Position::new(start + 8));
        doc.replace(range, "Modified").unwrap();

        assert!(doc.text().contains("Title: Modified"));
        assert!(!doc.text().contains("Original"));

        // Undo the replace
        doc.undo().unwrap();
        assert!(doc.text().contains("Title: Original"));
        assert!(!doc.text().contains("Modified"));

        // Redo the replace
        doc.redo().unwrap();
        assert!(doc.text().contains("Title: Modified"));
        assert!(!doc.text().contains("Original"));
    }

    #[test]
    fn test_validator_integration() {
        let mut doc = EditorDocument::from_content(
            "[Script Info]\nTitle: Test\n\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nDialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,Test"
        ).unwrap();

        // Should have result after comprehensive validation
        let result = doc.validate_comprehensive().unwrap();
        assert!(result.is_valid);

        // Modify document
        doc.insert(Position::new(doc.len_bytes()), "\nComment: Test")
            .unwrap();

        // Force validate should work
        let result2 = doc.force_validate().unwrap();
        assert!(result2.is_valid);
    }

    #[test]
    fn test_validator_configuration() {
        let mut doc = EditorDocument::new();

        // Configure validator
        let config = crate::utils::validator::ValidatorConfig {
            max_issues: 5,
            enable_performance_hints: false,
            ..Default::default()
        };
        doc.set_validator_config(config);

        // Validator should be configured
        // We can't directly check the cache anymore, but configuration should work
        assert!(doc.is_valid_cached().is_ok());
    }

    #[test]
    fn test_validator_with_invalid_document() {
        let mut doc = EditorDocument::from_content("Invalid content").unwrap();

        // Comprehensive validation should find issues
        let result = doc.validate_comprehensive().unwrap();
        assert!(!result.issues.is_empty());

        // Should have warnings about missing sections
        let warnings =
            result.issues_with_severity(crate::utils::validator::ValidationSeverity::Warning);
        assert!(!warnings.is_empty());
    }

    #[test]
    #[cfg(feature = "formats")]
    fn test_format_import_export() {
        // Test SRT import
        let srt_content = "1\n00:00:00,000 --> 00:00:05,000\nHello world!";
        let doc = EditorDocument::import_format(
            srt_content,
            Some(crate::utils::formats::SubtitleFormat::SRT),
        )
        .unwrap();
        assert!(doc.text().contains("Hello world!"));
        assert!(doc.has_events().unwrap());

        // Test export to WebVTT
        let options = crate::utils::formats::ConversionOptions::default();
        let webvtt = doc
            .export_format(crate::utils::formats::SubtitleFormat::WebVTT, &options)
            .unwrap();
        assert!(webvtt.starts_with("WEBVTT"));
        assert!(webvtt.contains("00:00:00.000 --> 00:00:05.000"));
        assert!(webvtt.contains("Hello world!"));
    }

    #[test]
    fn test_undo_redo_delete() {
        let mut doc =
            EditorDocument::from_content("[Script Info]\nTitle: Test\nAuthor: John").unwrap();

        // Delete the Author line
        let start = doc.text().find("\nAuthor: John").unwrap();
        let range = Range::new(Position::new(start), Position::new(start + 13));
        doc.delete(range).unwrap();

        assert!(!doc.text().contains("Author: John"));

        // Undo the delete
        doc.undo().unwrap();
        assert!(doc.text().contains("Author: John"));

        // Redo the delete
        doc.redo().unwrap();
        assert!(!doc.text().contains("Author: John"));
    }

    #[cfg(feature = "plugins")]
    #[test]
    fn test_registry_integration() {
        let mut doc = EditorDocument::new();

        // Initially no registry
        assert!(doc.registry().is_none());

        // Initialize with registry
        doc.initialize_registry().unwrap();
        assert!(doc.registry().is_some());

        // Parse with extensions
        doc.insert(Position::new(0), "[Script Info]\nTitle: Test\n\n[Events]\nDialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,{\\b1}Bold{\\b0} text").unwrap();

        let section_count = doc
            .parse_with_extensions(|script| script.sections().len())
            .unwrap();
        assert_eq!(section_count, 2);
    }

    #[cfg(feature = "plugins")]
    #[test]
    fn test_custom_tag_handler() {
        use ass_core::plugin::{TagHandler, TagResult};

        struct CustomHandler;
        impl TagHandler for CustomHandler {
            fn name(&self) -> &'static str {
                "custom"
            }

            fn process(&self, _args: &str) -> TagResult {
                TagResult::Processed
            }

            fn validate(&self, _args: &str) -> bool {
                true
            }
        }

        let mut doc = EditorDocument::new();
        doc.initialize_registry().unwrap();

        // Register custom tag handler
        assert!(doc
            .register_tag_handler("test-extension".to_string(), Box::new(CustomHandler))
            .is_ok());
    }

    #[cfg(feature = "plugins")]
    #[test]
    fn test_custom_section_processor() {
        use ass_core::plugin::{SectionProcessor, SectionResult};

        struct CustomProcessor;
        impl SectionProcessor for CustomProcessor {
            fn name(&self) -> &'static str {
                "CustomSection"
            }

            fn process(&self, _header: &str, _lines: &[&str]) -> SectionResult {
                SectionResult::Processed
            }

            fn validate(&self, _header: &str, _lines: &[&str]) -> bool {
                true
            }
        }

        let mut doc = EditorDocument::new();
        doc.initialize_registry().unwrap();

        // Register custom section processor
        assert!(doc
            .register_section_processor("test-extension".to_string(), Box::new(CustomProcessor))
            .is_ok());
    }
}