dampen-dev 0.3.2

Development mode tooling for Dampen - hot-reload, file watching, and error overlays
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
//! Hot-reload state preservation and coordination
//!
//! This module handles the hot-reload process, including model snapshotting,
//! state restoration, and error recovery.

use dampen_core::binding::UiBindable;
use dampen_core::parser::error::ParseError;
use dampen_core::state::AppState;
use serde::{Serialize, de::DeserializeOwned};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

/// Cache entry for parsed XML documents
#[derive(Clone)]
struct ParsedDocumentCache {
    /// Cached parsed document
    document: dampen_core::ir::DampenDocument,

    /// Timestamp when cached
    cached_at: Instant,
}

/// Tracks hot-reload state and history for debugging
pub struct HotReloadContext<M> {
    /// Last successful model snapshot (JSON)
    last_model_snapshot: Option<String>,

    /// Timestamp of last reload
    last_reload_timestamp: Instant,

    /// Reload count (for metrics)
    reload_count: usize,

    /// Current error state (if any)
    error: Option<String>,

    /// Cache of parsed XML documents (keyed by content hash)
    /// This avoids re-parsing the same XML content repeatedly
    parse_cache: HashMap<u64, ParsedDocumentCache>,

    /// Maximum number of cached documents
    max_cache_size: usize,

    /// Count of cache hits for hit rate calculation
    cache_hits: AtomicUsize,

    /// Count of cache misses for hit rate calculation
    cache_misses: AtomicUsize,

    _marker: PhantomData<M>,
}

impl<M: UiBindable> HotReloadContext<M> {
    /// Create a new hot-reload context
    pub fn new() -> Self {
        Self {
            last_model_snapshot: None,
            last_reload_timestamp: Instant::now(),
            reload_count: 0,
            error: None,
            parse_cache: HashMap::new(),
            max_cache_size: 10,
            cache_hits: AtomicUsize::new(0),
            cache_misses: AtomicUsize::new(0),
            _marker: PhantomData,
        }
    }

    /// Create a new hot-reload context with custom cache size
    pub fn with_cache_size(cache_size: usize) -> Self {
        Self {
            last_model_snapshot: None,
            last_reload_timestamp: Instant::now(),
            reload_count: 0,
            error: None,
            parse_cache: HashMap::new(),
            max_cache_size: cache_size,
            cache_hits: AtomicUsize::new(0),
            cache_misses: AtomicUsize::new(0),
            _marker: PhantomData,
        }
    }

    /// Compute content hash for caching
    fn compute_content_hash(xml_source: &str) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        xml_source.hash(&mut hasher);
        hasher.finish()
    }

    /// Try to get a parsed document from cache
    fn get_cached_document(&self, xml_source: &str) -> Option<dampen_core::ir::DampenDocument> {
        let content_hash = Self::compute_content_hash(xml_source);

        self.parse_cache
            .get(&content_hash)
            .map(|entry| entry.document.clone())
            .inspect(|_| {
                self.cache_hits.fetch_add(1, Ordering::Relaxed);
            })
            .or_else(|| {
                self.cache_misses.fetch_add(1, Ordering::Relaxed);
                None
            })
    }

    /// Cache a parsed document
    fn cache_document(&mut self, xml_source: &str, document: dampen_core::ir::DampenDocument) {
        // Evict oldest entry if cache is full
        if self.parse_cache.len() >= self.max_cache_size
            && let Some(oldest_key) = self
                .parse_cache
                .iter()
                .min_by_key(|(_, entry)| entry.cached_at)
                .map(|(key, _)| *key)
        {
            self.parse_cache.remove(&oldest_key);
        }

        let content_hash = Self::compute_content_hash(xml_source);

        self.parse_cache.insert(
            content_hash,
            ParsedDocumentCache {
                document,
                cached_at: Instant::now(),
            },
        );
    }

    /// Clear the parse cache
    pub fn clear_cache(&mut self) {
        self.parse_cache.clear();
    }

    /// Get cache statistics
    pub fn cache_stats(&self) -> (usize, usize) {
        (self.parse_cache.len(), self.max_cache_size)
    }

    /// Get detailed performance metrics from the last reload
    pub fn performance_metrics(&self) -> ReloadPerformanceMetrics {
        ReloadPerformanceMetrics {
            reload_count: self.reload_count,
            last_reload_latency: self.last_reload_latency(),
            cache_hit_rate: self.calculate_cache_hit_rate(),
            cache_size: self.parse_cache.len(),
        }
    }

    /// Calculate cache hit rate (0.0 to 1.0)
    fn calculate_cache_hit_rate(&self) -> f64 {
        let hits = self.cache_hits.load(Ordering::Relaxed);
        let misses = self.cache_misses.load(Ordering::Relaxed);
        let total = hits.saturating_add(misses);

        if total == 0 {
            0.0
        } else {
            hits as f64 / total as f64
        }
    }

    /// Snapshot the current model state to JSON
    pub fn snapshot_model(&mut self, model: &M) -> Result<(), String>
    where
        M: Serialize,
    {
        match serde_json::to_string(model) {
            Ok(json) => {
                self.last_model_snapshot = Some(json);
                Ok(())
            }
            Err(e) => Err(format!("Failed to serialize model: {}", e)),
        }
    }

    /// Restore the model from the last snapshot
    pub fn restore_model(&self) -> Result<M, String>
    where
        M: DeserializeOwned,
    {
        match &self.last_model_snapshot {
            Some(json) => serde_json::from_str(json)
                .map_err(|e| format!("Failed to deserialize model: {}", e)),
            None => Err("No model snapshot available".to_string()),
        }
    }

    /// Record a reload attempt
    pub fn record_reload(&mut self, success: bool) {
        self.reload_count += 1;
        self.last_reload_timestamp = Instant::now();
        if !success {
            self.error = Some("Reload failed".to_string());
        } else {
            self.error = None;
        }
    }

    /// Record a reload with timing information
    pub fn record_reload_with_timing(&mut self, success: bool, elapsed: Duration) {
        self.reload_count += 1;
        self.last_reload_timestamp = Instant::now();
        if !success {
            self.error = Some("Reload failed".to_string());
        } else {
            self.error = None;
        }

        // Log performance if it exceeds target
        if success && elapsed.as_millis() > 300 {
            eprintln!(
                "Warning: Hot-reload took {}ms (target: <300ms)",
                elapsed.as_millis()
            );
        }
    }

    /// Get the latency of the last reload
    pub fn last_reload_latency(&self) -> Duration {
        self.last_reload_timestamp.elapsed()
    }
}

impl<M: UiBindable> Default for HotReloadContext<M> {
    fn default() -> Self {
        Self::new()
    }
}

/// Performance metrics for hot-reload operations
#[derive(Debug, Clone, Copy)]
pub struct ReloadPerformanceMetrics {
    /// Total number of reloads performed
    pub reload_count: usize,

    /// Latency of the last reload operation
    pub last_reload_latency: Duration,

    /// Cache hit rate (0.0 to 1.0)
    pub cache_hit_rate: f64,

    /// Current cache size
    pub cache_size: usize,
}

impl ReloadPerformanceMetrics {
    /// Check if the last reload met the performance target (<300ms)
    pub fn meets_target(&self) -> bool {
        self.last_reload_latency.as_millis() < 300
    }

    /// Get latency in milliseconds
    pub fn latency_ms(&self) -> u128 {
        self.last_reload_latency.as_millis()
    }
}

/// Result type for hot-reload attempts with detailed error information
#[derive(Debug)]
pub enum ReloadResult<M: UiBindable> {
    /// Reload succeeded
    Success(AppState<M>),

    /// XML parse error (reject reload)
    ParseError(ParseError),

    /// Schema validation error (reject reload)
    ValidationError(Vec<String>),

    /// Model deserialization failed, using default (accept reload with warning)
    StateRestoreWarning(AppState<M>, String),
}

/// Attempts to hot-reload the UI from a new XML source while preserving application state.
///
/// This function orchestrates the entire hot-reload process:
/// 1. Snapshot the current model state
/// 2. Parse the new XML
/// 3. Rebuild the handler registry
/// 4. Validate the document (all referenced handlers exist)
/// 5. Restore the model (or use default on failure)
/// 6. Create a new AppState with the updated UI
///
/// # Arguments
///
/// * `xml_source` - New XML UI definition as a string
/// * `current_state` - Current application state (for model snapshotting)
/// * `context` - Hot-reload context for state preservation
/// * `create_handlers` - Function to rebuild the handler registry
///
/// # Returns
///
/// A `ReloadResult` indicating success or the specific type of failure:
/// - `Success`: Reload succeeded with model restored
/// - `ParseError`: XML parse failed (reject reload, keep old state)
/// - `ValidationError`: Handler validation failed (reject reload, keep old state)
/// - `StateRestoreWarning`: Reload succeeded but model used default (accept with warning)
///
/// # Error Handling Matrix
///
/// | Error Type | Action | State Preservation |
/// |------------|--------|-------------------|
/// | Parse error | Reject reload | Keep old state completely |
/// | Validation error | Reject reload | Keep old state completely |
/// | Model restore failure | Accept reload | Use M::default() with warning |
///
/// # Example
///
/// ```no_run
/// use dampen_dev::reload::{attempt_hot_reload, HotReloadContext};
/// use dampen_core::{AppState, handler::HandlerRegistry};
/// # use dampen_core::binding::UiBindable;
/// # #[derive(Default, serde::Serialize, serde::Deserialize)]
/// # struct Model;
/// # impl UiBindable for Model {
/// #     fn get_field(&self, _path: &[&str]) -> Option<dampen_core::binding::BindingValue> { None }
/// #     fn available_fields() -> Vec<String> { vec![] }
/// # }
///
/// fn handle_file_change(
///     new_xml: &str,
///     app_state: &AppState<Model>,
///     context: &mut HotReloadContext<Model>,
/// ) {
///     let result = attempt_hot_reload(
///         new_xml,
///         app_state,
///         context,
///         || create_handler_registry(),
///     );
///
///     match result {
///         dampen_dev::reload::ReloadResult::Success(new_state) => {
///             // Apply the new state
///         }
///         dampen_dev::reload::ReloadResult::ParseError(err) => {
///             // Show error overlay, keep old UI
///             eprintln!("Parse error: {}", err.message);
///         }
///         _ => {
///             // Handle other cases
///         }
///     }
/// }
///
/// fn create_handler_registry() -> dampen_core::handler::HandlerRegistry {
///     dampen_core::handler::HandlerRegistry::new()
/// }
/// ```
pub fn attempt_hot_reload<M, F>(
    xml_source: &str,
    current_state: &AppState<M>,
    context: &mut HotReloadContext<M>,
    create_handlers: F,
) -> ReloadResult<M>
where
    M: UiBindable + Serialize + DeserializeOwned + Default,
    F: FnOnce() -> dampen_core::handler::HandlerRegistry,
{
    let reload_start = Instant::now();

    // Step 1: Snapshot current model state
    if let Err(e) = context.snapshot_model(&current_state.model) {
        // If we can't snapshot, continue with reload but warn
        eprintln!("Warning: Failed to snapshot model: {}", e);
    }

    // Step 2: Parse new XML (with caching)
    let new_document = if let Some(cached_doc) = context.get_cached_document(xml_source) {
        // Cache hit - reuse parsed document
        cached_doc
    } else {
        // Cache miss - parse and cache
        match dampen_core::parser::parse(xml_source) {
            Ok(doc) => {
                context.cache_document(xml_source, doc.clone());
                doc
            }
            Err(err) => {
                context.record_reload(false);
                return ReloadResult::ParseError(err);
            }
        }
    };

    // Step 3: Rebuild handler registry (before validation)
    let new_handlers = create_handlers();

    // Step 4: Validate the parsed document against the handler registry
    if let Err(missing_handlers) = validate_handlers(&new_document, &new_handlers) {
        context.record_reload(false);
        let error_messages: Vec<String> = missing_handlers
            .iter()
            .map(|h| format!("Handler '{}' is referenced but not registered", h))
            .collect();
        return ReloadResult::ValidationError(error_messages);
    }

    // Step 5: Restore model from snapshot
    let restored_model = match context.restore_model() {
        Ok(model) => {
            // Successfully restored
            model
        }
        Err(e) => {
            // Failed to restore, use default
            eprintln!("Warning: Failed to restore model ({}), using default", e);

            // Create new state with default model
            let new_state = AppState::with_all(new_document, M::default(), new_handlers);

            context.record_reload(true);
            return ReloadResult::StateRestoreWarning(new_state, e);
        }
    };

    // Step 6: Create new AppState with restored model and new UI
    let new_state = AppState::with_all(new_document, restored_model, new_handlers);

    let elapsed = reload_start.elapsed();
    context.record_reload_with_timing(true, elapsed);
    ReloadResult::Success(new_state)
}

/// Async version of `attempt_hot_reload` that performs XML parsing asynchronously.
///
/// This function is optimized for non-blocking hot-reload by offloading the CPU-intensive
/// XML parsing to a background thread using `tokio::task::spawn_blocking`.
///
/// # Performance Benefits
///
/// - XML parsing happens on a thread pool, avoiding UI blocking
/// - Reduces hot-reload latency for large XML files
/// - Maintains UI responsiveness during reload
///
/// # Arguments
///
/// * `xml_source` - New XML UI definition as a string
/// * `current_state` - Current application state (for model snapshotting)
/// * `context` - Hot-reload context for state preservation
/// * `create_handlers` - Function to rebuild the handler registry
///
/// # Returns
///
/// A `ReloadResult` wrapped in a future, indicating success or failure
///
/// # Example
///
/// ```no_run
/// use dampen_dev::reload::{attempt_hot_reload_async, HotReloadContext};
/// use dampen_core::{AppState, handler::HandlerRegistry};
/// use std::sync::Arc;
/// # use dampen_core::binding::UiBindable;
/// # #[derive(Default, serde::Serialize, serde::Deserialize)]
/// # struct Model;
/// # impl UiBindable for Model {
/// #     fn get_field(&self, _path: &[&str]) -> Option<dampen_core::binding::BindingValue> { None }
/// #     fn available_fields() -> Vec<String> { vec![] }
/// # }
///
/// async fn handle_file_change_async(
///     new_xml: String,
///     app_state: AppState<Model>,
///     mut context: HotReloadContext<Model>,
/// ) {
///     let result = attempt_hot_reload_async(
///         Arc::new(new_xml),
///         &app_state,
///         &mut context,
///         || create_handler_registry(),
///     ).await;
///
///     match result {
///         dampen_dev::reload::ReloadResult::Success(new_state) => {
///             // Apply the new state
///         }
///         _ => {
///             // Handle errors
///         }
///     }
/// }
///
/// fn create_handler_registry() -> dampen_core::handler::HandlerRegistry {
///     dampen_core::handler::HandlerRegistry::new()
/// }
/// ```
pub async fn attempt_hot_reload_async<M, F>(
    xml_source: Arc<String>,
    current_state: &AppState<M>,
    context: &mut HotReloadContext<M>,
    create_handlers: F,
) -> ReloadResult<M>
where
    M: UiBindable + Serialize + DeserializeOwned + Default + Send + 'static,
    F: FnOnce() -> dampen_core::handler::HandlerRegistry + Send + 'static,
{
    let reload_start = Instant::now();

    // Step 1: Snapshot current model state (fast, can do synchronously)
    if let Err(e) = context.snapshot_model(&current_state.model) {
        eprintln!("Warning: Failed to snapshot model: {}", e);
    }

    // Clone snapshot for async context
    let model_snapshot = context.last_model_snapshot.clone();

    // Step 2: Parse new XML asynchronously (CPU-intensive work offloaded, with caching)
    let new_document = if let Some(cached_doc) = context.get_cached_document(&xml_source) {
        // Cache hit - reuse parsed document
        cached_doc
    } else {
        // Cache miss - parse asynchronously and cache
        let xml_for_parse = Arc::clone(&xml_source);
        let parse_result =
            tokio::task::spawn_blocking(move || dampen_core::parser::parse(&xml_for_parse)).await;

        match parse_result {
            Ok(Ok(doc)) => {
                context.cache_document(&xml_source, doc.clone());
                doc
            }
            Ok(Err(err)) => {
                context.record_reload(false);
                return ReloadResult::ParseError(err);
            }
            Err(join_err) => {
                context.record_reload(false);
                let error = ParseError {
                    kind: dampen_core::parser::error::ParseErrorKind::XmlSyntax,
                    span: dampen_core::ir::span::Span::default(),
                    message: format!("Async parsing failed: {}", join_err),
                    suggestion: Some(
                        "Check if the XML file is accessible and not corrupted".to_string(),
                    ),
                };
                return ReloadResult::ParseError(error);
            }
        }
    };

    // Step 3: Rebuild handler registry (before validation)
    let new_handlers = create_handlers();

    // Step 4: Validate the parsed document against the handler registry
    if let Err(missing_handlers) = validate_handlers(&new_document, &new_handlers) {
        context.record_reload(false);
        let error_messages: Vec<String> = missing_handlers
            .iter()
            .map(|h| format!("Handler '{}' is referenced but not registered", h))
            .collect();
        return ReloadResult::ValidationError(error_messages);
    }

    // Step 5: Restore model from snapshot
    let restored_model = match model_snapshot {
        Some(json) => match serde_json::from_str::<M>(&json) {
            Ok(model) => model,
            Err(e) => {
                eprintln!("Warning: Failed to restore model ({}), using default", e);
                let new_state = AppState::with_all(new_document, M::default(), new_handlers);
                context.record_reload(true);
                return ReloadResult::StateRestoreWarning(
                    new_state,
                    format!("Failed to deserialize model: {}", e),
                );
            }
        },
        None => {
            eprintln!("Warning: No model snapshot available, using default");
            let new_state = AppState::with_all(new_document, M::default(), new_handlers);
            context.record_reload(true);
            return ReloadResult::StateRestoreWarning(
                new_state,
                "No model snapshot available".to_string(),
            );
        }
    };

    // Step 6: Create new AppState with restored model and new UI
    let new_state = AppState::with_all(new_document, restored_model, new_handlers);

    let elapsed = reload_start.elapsed();
    context.record_reload_with_timing(true, elapsed);
    ReloadResult::Success(new_state)
}

/// Collects all handler names referenced in a document.
///
/// This function recursively traverses the widget tree and collects all unique
/// handler names from event bindings.
///
/// # Arguments
///
/// * `document` - The parsed UI document to scan
///
/// # Returns
///
/// A vector of unique handler names referenced in the document
fn collect_handler_names(document: &dampen_core::ir::DampenDocument) -> Vec<String> {
    use std::collections::HashSet;

    let mut handlers = HashSet::new();
    collect_handlers_from_node(&document.root, &mut handlers);
    handlers.into_iter().collect()
}

/// Recursively collects handler names from a widget node and its children.
fn collect_handlers_from_node(
    node: &dampen_core::ir::node::WidgetNode,
    handlers: &mut std::collections::HashSet<String>,
) {
    // Collect handlers from events
    for event in &node.events {
        handlers.insert(event.handler.clone());
    }

    // Recursively collect from children
    for child in &node.children {
        collect_handlers_from_node(child, handlers);
    }
}

/// Validates that all handlers referenced in the document exist in the registry.
///
/// # Arguments
///
/// * `document` - The parsed UI document to validate
/// * `registry` - The handler registry to check against
///
/// # Returns
///
/// `Ok(())` if all handlers exist, or `Err(Vec<String>)` with a list of missing handlers
fn validate_handlers(
    document: &dampen_core::ir::DampenDocument,
    registry: &dampen_core::handler::HandlerRegistry,
) -> Result<(), Vec<String>> {
    let referenced_handlers = collect_handler_names(document);
    let mut missing_handlers = Vec::new();

    for handler_name in referenced_handlers {
        if registry.get(&handler_name).is_none() {
            missing_handlers.push(handler_name);
        }
    }

    if missing_handlers.is_empty() {
        Ok(())
    } else {
        Err(missing_handlers)
    }
}

/// Result type for theme hot-reload attempts
#[derive(Debug)]
pub enum ThemeReloadResult {
    /// Reload succeeded
    Success,

    /// Theme file parse error
    ParseError(String),

    /// Theme document validation error
    ValidationError(String),

    /// No theme context to reload
    NoThemeContext,

    /// Theme file not found
    FileNotFound,
}

/// Attempts to hot-reload the theme from a changed theme.dampen file.
///
/// This function handles theme file changes specifically:
/// 1. Read the new theme file content
/// 2. Parse the new ThemeDocument
/// 3. Update the ThemeContext if valid
///
/// # Arguments
///
/// * `theme_path` - Path to the theme.dampen file
/// * `theme_context` - The current ThemeContext to reload
///
/// # Returns
///
/// A `ThemeReloadResult` indicating success or the specific type of failure
///
/// # Example
///
/// ```no_run
/// use dampen_dev::reload::{attempt_theme_hot_reload, ThemeReloadResult};
/// use dampen_core::state::ThemeContext;
///
/// fn handle_theme_file_change(theme_path: &std::path::Path, ctx: &mut Option<ThemeContext>) {
///     let result = attempt_theme_hot_reload(theme_path, ctx);
///
///     match result {
///         ThemeReloadResult::Success => {
///             println!("Theme reloaded successfully");
///         }
///         ThemeReloadResult::ParseError(err) => {
///             eprintln!("Failed to parse theme file: {}", err);
///         }
///         ThemeReloadResult::ValidationError(err) => {
///             eprintln!("Theme validation failed: {}", err);
///         }
///         ThemeReloadResult::NoThemeContext => {
///             eprintln!("No theme context to reload");
///         }
///         ThemeReloadResult::FileNotFound => {
///             eprintln!("Theme file not found");
///         }
///     }
/// }
/// ```
pub fn attempt_theme_hot_reload(
    theme_path: &std::path::Path,
    theme_context: &mut Option<dampen_core::state::ThemeContext>,
) -> ThemeReloadResult {
    let theme_context = match theme_context {
        Some(ctx) => ctx,
        None => return ThemeReloadResult::NoThemeContext,
    };

    let content = match std::fs::read_to_string(theme_path) {
        Ok(c) => c,
        Err(e) => return ThemeReloadResult::ParseError(format!("Failed to read file: {}", e)),
    };

    let new_doc = match dampen_core::parser::theme_parser::parse_theme_document(&content) {
        Ok(doc) => doc,
        Err(e) => {
            return ThemeReloadResult::ParseError(format!(
                "Failed to parse theme document: {}",
                e.message
            ));
        }
    };

    if let Err(e) = new_doc.validate() {
        return ThemeReloadResult::ValidationError(e.to_string());
    }

    theme_context.reload(new_doc);
    ThemeReloadResult::Success
}

/// Check if a path is a theme file path
pub fn is_theme_file_path(path: &std::path::Path) -> bool {
    path.file_name()
        .and_then(|n| n.to_str())
        .map(|n| n == "theme.dampen")
        .unwrap_or(false)
}

/// Find the theme directory path from a changed file path
///
/// If the changed file is in or under the theme directory, returns the theme directory.
/// Otherwise returns None.
pub fn get_theme_dir_from_path(path: &std::path::Path) -> Option<std::path::PathBuf> {
    let path = std::fs::canonicalize(path).ok()?;
    let theme_file_name = path.file_name()?;

    if theme_file_name == "theme.dampen" {
        return Some(path.parent()?.to_path_buf());
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
    struct TestModel {
        count: i32,
        name: String,
    }

    impl UiBindable for TestModel {
        fn get_field(&self, _path: &[&str]) -> Option<dampen_core::binding::BindingValue> {
            None
        }

        fn available_fields() -> Vec<String> {
            vec![]
        }
    }

    impl Default for TestModel {
        fn default() -> Self {
            Self {
                count: 0,
                name: "default".to_string(),
            }
        }
    }

    #[test]
    fn test_snapshot_model_success() {
        let mut context = HotReloadContext::<TestModel>::new();
        let model = TestModel {
            count: 42,
            name: "Alice".to_string(),
        };

        let result = context.snapshot_model(&model);
        assert!(result.is_ok());
        assert!(context.last_model_snapshot.is_some());
    }

    #[test]
    fn test_restore_model_success() {
        let mut context = HotReloadContext::<TestModel>::new();
        let original = TestModel {
            count: 42,
            name: "Alice".to_string(),
        };

        // First snapshot
        context.snapshot_model(&original).unwrap();

        // Then restore
        let restored = context.restore_model().unwrap();
        assert_eq!(restored, original);
    }

    #[test]
    fn test_restore_model_no_snapshot() {
        let context = HotReloadContext::<TestModel>::new();

        // Try to restore without snapshot
        let result = context.restore_model();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("No model snapshot"));
    }

    #[test]
    fn test_snapshot_restore_round_trip() {
        let mut context = HotReloadContext::<TestModel>::new();
        let original = TestModel {
            count: 999,
            name: "Bob".to_string(),
        };

        // Snapshot, modify, and restore
        context.snapshot_model(&original).unwrap();

        let mut modified = original.clone();
        modified.count = 0;
        modified.name = "Changed".to_string();

        // Restore should get original back
        let restored = context.restore_model().unwrap();
        assert_eq!(restored, original);
        assert_ne!(restored, modified);
    }

    #[test]
    fn test_multiple_snapshots() {
        let mut context = HotReloadContext::<TestModel>::new();

        // First snapshot
        let model1 = TestModel {
            count: 1,
            name: "First".to_string(),
        };
        context.snapshot_model(&model1).unwrap();

        // Second snapshot (should overwrite first)
        let model2 = TestModel {
            count: 2,
            name: "Second".to_string(),
        };
        context.snapshot_model(&model2).unwrap();

        // Restore should get the second model
        let restored = context.restore_model().unwrap();
        assert_eq!(restored, model2);
        assert_ne!(restored, model1);
    }

    #[test]
    fn test_record_reload() {
        let mut context = HotReloadContext::<TestModel>::new();

        assert_eq!(context.reload_count, 0);
        assert!(context.error.is_none());

        // Record successful reload
        context.record_reload(true);
        assert_eq!(context.reload_count, 1);
        assert!(context.error.is_none());

        // Record failed reload
        context.record_reload(false);
        assert_eq!(context.reload_count, 2);
        assert!(context.error.is_some());

        // Record successful reload again
        context.record_reload(true);
        assert_eq!(context.reload_count, 3);
        assert!(context.error.is_none());
    }

    #[test]
    fn test_cache_hit_rate_calculated_correctly() {
        use std::sync::atomic::Ordering;

        let mut context = HotReloadContext::<TestModel>::new();

        // Initially: 0 hits, 0 misses
        assert_eq!(context.calculate_cache_hit_rate(), 0.0);

        // Simulate 3 hits, 2 misses
        context.cache_hits.store(3, Ordering::Relaxed);
        context.cache_misses.store(2, Ordering::Relaxed);

        // Hit rate = 3 / (3 + 2) = 0.6
        assert_eq!(context.calculate_cache_hit_rate(), 0.6);
    }

    #[test]
    fn test_cache_hit_rate_zero_division() {
        let context = HotReloadContext::<TestModel>::new();
        // Should not panic on division by zero
        assert_eq!(context.calculate_cache_hit_rate(), 0.0);
    }

    #[test]
    fn test_cache_hit_rate_full_misses() {
        use std::sync::atomic::Ordering;

        let mut context = HotReloadContext::<TestModel>::new();
        context.cache_hits.store(0, Ordering::Relaxed);
        context.cache_misses.store(5, Ordering::Relaxed);
        assert_eq!(context.calculate_cache_hit_rate(), 0.0);
    }

    #[test]
    fn test_cache_hit_rate_full_hits() {
        use std::sync::atomic::Ordering;

        let mut context = HotReloadContext::<TestModel>::new();
        context.cache_hits.store(5, Ordering::Relaxed);
        context.cache_misses.store(0, Ordering::Relaxed);
        assert_eq!(context.calculate_cache_hit_rate(), 1.0);
    }

    #[test]
    fn test_attempt_hot_reload_success() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // Create initial state with a model
        let xml_v1 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="Version 1" /></column></dampen>"#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 42,
            name: "Alice".to_string(),
        };
        let registry_v1 = HandlerRegistry::new();
        let state_v1 = AppState::with_all(doc_v1, model_v1, registry_v1);

        // Create hot-reload context
        let mut context = HotReloadContext::<TestModel>::new();

        // New XML with changes
        let xml_v2 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="Version 2" /></column></dampen>"#;

        // Attempt hot-reload
        let result = attempt_hot_reload(xml_v2, &state_v1, &mut context, || HandlerRegistry::new());

        // Should succeed and preserve model
        match result {
            ReloadResult::Success(new_state) => {
                assert_eq!(new_state.model.count, 42);
                assert_eq!(new_state.model.name, "Alice");
                assert_eq!(context.reload_count, 1);
            }
            _ => panic!("Expected Success, got {:?}", result),
        }
    }

    #[test]
    fn test_attempt_hot_reload_parse_error() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // Create initial state
        let xml_v1 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="Version 1" /></column></dampen>"#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 10,
            name: "Bob".to_string(),
        };
        let state_v1 = AppState::with_all(doc_v1, model_v1, HandlerRegistry::new());

        let mut context = HotReloadContext::<TestModel>::new();

        // Invalid XML (unclosed tag)
        let xml_invalid = r#"<dampen version="1.1" encoding="utf-8"><column><text value="Broken"#;

        // Attempt hot-reload
        let result = attempt_hot_reload(xml_invalid, &state_v1, &mut context, || {
            HandlerRegistry::new()
        });

        // Should return ParseError
        match result {
            ReloadResult::ParseError(_err) => {
                // Expected
                assert_eq!(context.reload_count, 1); // Failed reload is recorded
            }
            _ => panic!("Expected ParseError, got {:?}", result),
        }
    }

    #[test]
    fn test_attempt_hot_reload_model_restore_failure() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // Create initial state
        let xml_v1 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="Version 1" /></column></dampen>"#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 99,
            name: "Charlie".to_string(),
        };
        let state_v1 = AppState::with_all(doc_v1, model_v1, HandlerRegistry::new());

        // Create context and manually corrupt the snapshot to trigger restore failure
        let mut context = HotReloadContext::<TestModel>::new();
        context.last_model_snapshot = Some("{ invalid json }".to_string()); // Invalid JSON

        // New valid XML
        let xml_v2 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="Version 2" /></column></dampen>"#;

        // Attempt hot-reload (will snapshot current model, then try to restore from corrupted snapshot)
        let result = attempt_hot_reload(xml_v2, &state_v1, &mut context, || HandlerRegistry::new());

        // The function snapshots the current model first, so it will actually succeed
        // because the new snapshot overwrites the corrupted one.
        // To truly test restore failure, we need to test the restore_model method directly,
        // which we already do in test_restore_model_no_snapshot.

        // This test actually validates that the snapshot-before-parse strategy works correctly.
        match result {
            ReloadResult::Success(new_state) => {
                // Model preserved via the snapshot taken at the start of attempt_hot_reload
                assert_eq!(new_state.model.count, 99);
                assert_eq!(new_state.model.name, "Charlie");
                assert_eq!(context.reload_count, 1);
            }
            _ => panic!("Expected Success, got {:?}", result),
        }
    }

    #[test]
    fn test_attempt_hot_reload_preserves_model_across_multiple_reloads() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // Create initial state
        let xml_v1 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="V1" /></column></dampen>"#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 100,
            name: "Dave".to_string(),
        };
        let state_v1 = AppState::with_all(doc_v1, model_v1, HandlerRegistry::new());

        let mut context = HotReloadContext::<TestModel>::new();

        // First reload
        let xml_v2 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="V2" /></column></dampen>"#;
        let result = attempt_hot_reload(xml_v2, &state_v1, &mut context, || HandlerRegistry::new());

        let state_v2 = match result {
            ReloadResult::Success(s) => s,
            _ => panic!("First reload failed"),
        };

        assert_eq!(state_v2.model.count, 100);
        assert_eq!(state_v2.model.name, "Dave");

        // Second reload
        let xml_v3 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="V3" /></column></dampen>"#;
        let result = attempt_hot_reload(xml_v3, &state_v2, &mut context, || HandlerRegistry::new());

        let state_v3 = match result {
            ReloadResult::Success(s) => s,
            _ => panic!("Second reload failed"),
        };

        // Model still preserved
        assert_eq!(state_v3.model.count, 100);
        assert_eq!(state_v3.model.name, "Dave");
        assert_eq!(context.reload_count, 2);
    }

    #[test]
    fn test_attempt_hot_reload_with_handler_registry() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // Create initial state
        let xml_v1 = r#"<dampen version="1.1" encoding="utf-8"><column><button label="Click" on_click="test" /></column></dampen>"#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 5,
            name: "Eve".to_string(),
        };

        let registry_v1 = HandlerRegistry::new();
        registry_v1.register_simple("test", |_model| {
            // Handler v1
        });

        let state_v1 = AppState::with_all(doc_v1, model_v1, registry_v1);

        let mut context = HotReloadContext::<TestModel>::new();

        // New XML with different handler
        let xml_v2 = r#"<dampen version="1.1" encoding="utf-8"><column><button label="Click Me" on_click="test2" /></column></dampen>"#;

        // Create NEW handler registry (simulating code change)
        let result = attempt_hot_reload(xml_v2, &state_v1, &mut context, || {
            let registry = HandlerRegistry::new();
            registry.register_simple("test2", |_model| {
                // Handler v2
            });
            registry
        });

        // Should succeed
        match result {
            ReloadResult::Success(new_state) => {
                // Model preserved
                assert_eq!(new_state.model.count, 5);
                assert_eq!(new_state.model.name, "Eve");

                // Handler registry updated
                assert!(new_state.handler_registry.get("test2").is_some());
            }
            _ => panic!("Expected Success, got {:?}", result),
        }
    }

    #[test]
    fn test_collect_handler_names() {
        use dampen_core::parser;

        // XML with multiple handlers
        let xml = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="Click" on_click="handle_click" />
                    <text_input placeholder="Type" on_input="handle_input" />
                    <button label="Submit" on_click="handle_submit" />
                </column>
            </dampen>
        "#;

        let doc = parser::parse(xml).unwrap();
        let handlers = collect_handler_names(&doc);

        // Should collect all three unique handlers
        assert_eq!(handlers.len(), 3);
        assert!(handlers.contains(&"handle_click".to_string()));
        assert!(handlers.contains(&"handle_input".to_string()));
        assert!(handlers.contains(&"handle_submit".to_string()));
    }

    #[test]
    fn test_collect_handler_names_nested() {
        use dampen_core::parser;

        // XML with nested handlers
        let xml = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <row>
                        <button label="A" on_click="handler_a" />
                    </row>
                    <row>
                        <button label="B" on_click="handler_b" />
                        <column>
                            <button label="C" on_click="handler_c" />
                        </column>
                    </row>
                </column>
            </dampen>
        "#;

        let doc = parser::parse(xml).unwrap();
        let handlers = collect_handler_names(&doc);

        // Should collect handlers from all nesting levels
        assert_eq!(handlers.len(), 3);
        assert!(handlers.contains(&"handler_a".to_string()));
        assert!(handlers.contains(&"handler_b".to_string()));
        assert!(handlers.contains(&"handler_c".to_string()));
    }

    #[test]
    fn test_collect_handler_names_duplicates() {
        use dampen_core::parser;

        // XML with duplicate handler names
        let xml = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="1" on_click="same_handler" />
                    <button label="2" on_click="same_handler" />
                    <button label="3" on_click="same_handler" />
                </column>
            </dampen>
        "#;

        let doc = parser::parse(xml).unwrap();
        let handlers = collect_handler_names(&doc);

        // Should deduplicate
        assert_eq!(handlers.len(), 1);
        assert!(handlers.contains(&"same_handler".to_string()));
    }

    #[test]
    fn test_validate_handlers_all_present() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        let xml = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="Click" on_click="test_handler" />
                </column>
            </dampen>
        "#;

        let doc = parser::parse(xml).unwrap();
        let registry = HandlerRegistry::new();
        registry.register_simple("test_handler", |_model| {});

        let result = validate_handlers(&doc, &registry);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_handlers_missing() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        let xml = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="Click" on_click="missing_handler" />
                </column>
            </dampen>
        "#;

        let doc = parser::parse(xml).unwrap();
        let registry = HandlerRegistry::new();
        // Registry is empty, handler not registered

        let result = validate_handlers(&doc, &registry);
        assert!(result.is_err());

        let missing = result.unwrap_err();
        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0], "missing_handler");
    }

    #[test]
    fn test_validate_handlers_multiple_missing() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        let xml = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="A" on_click="handler_a" />
                    <button label="B" on_click="handler_b" />
                    <button label="C" on_click="handler_c" />
                </column>
            </dampen>
        "#;

        let doc = parser::parse(xml).unwrap();
        let registry = HandlerRegistry::new();
        // Only register handler_b
        registry.register_simple("handler_b", |_model| {});

        let result = validate_handlers(&doc, &registry);
        assert!(result.is_err());

        let missing = result.unwrap_err();
        assert_eq!(missing.len(), 2);
        assert!(missing.contains(&"handler_a".to_string()));
        assert!(missing.contains(&"handler_c".to_string()));
    }

    #[test]
    fn test_attempt_hot_reload_validation_error() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // Create initial state
        let xml_v1 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="V1" /></column></dampen>"#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 10,
            name: "Test".to_string(),
        };
        let state_v1 = AppState::with_all(doc_v1, model_v1, HandlerRegistry::new());

        let mut context = HotReloadContext::<TestModel>::new();

        // New XML with a handler that won't be registered
        let xml_v2 = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="Click" on_click="unregistered_handler" />
                </column>
            </dampen>
        "#;

        // Create handler registry WITHOUT the required handler
        let result = attempt_hot_reload(xml_v2, &state_v1, &mut context, || {
            HandlerRegistry::new() // Empty registry
        });

        // Should return ValidationError
        match result {
            ReloadResult::ValidationError(errors) => {
                assert!(!errors.is_empty());
                assert!(errors[0].contains("unregistered_handler"));
                assert_eq!(context.reload_count, 1); // Failed reload is recorded
            }
            _ => panic!("Expected ValidationError, got {:?}", result),
        }
    }

    #[test]
    fn test_attempt_hot_reload_validation_success() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // Create initial state
        let xml_v1 = r#"<dampen version="1.1" encoding="utf-8"><column><text value="V1" /></column></dampen>"#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 20,
            name: "Valid".to_string(),
        };
        let state_v1 = AppState::with_all(doc_v1, model_v1, HandlerRegistry::new());

        let mut context = HotReloadContext::<TestModel>::new();

        // New XML with a handler
        let xml_v2 = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="Click" on_click="registered_handler" />
                </column>
            </dampen>
        "#;

        // Create handler registry WITH the required handler
        let result = attempt_hot_reload(xml_v2, &state_v1, &mut context, || {
            let registry = HandlerRegistry::new();
            registry.register_simple("registered_handler", |_model| {});
            registry
        });

        // Should succeed
        match result {
            ReloadResult::Success(new_state) => {
                assert_eq!(new_state.model.count, 20);
                assert_eq!(new_state.model.name, "Valid");
                assert_eq!(context.reload_count, 1);
            }
            _ => panic!("Expected Success, got {:?}", result),
        }
    }

    #[test]
    fn test_handler_registry_complete_replacement() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // Create initial state with handler "old_handler"
        let xml_v1 = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="Old" on_click="old_handler" />
                </column>
            </dampen>
        "#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 1,
            name: "Initial".to_string(),
        };

        let registry_v1 = HandlerRegistry::new();
        registry_v1.register_simple("old_handler", |_model| {});

        let state_v1 = AppState::with_all(doc_v1, model_v1, registry_v1);

        // Verify old handler exists
        assert!(state_v1.handler_registry.get("old_handler").is_some());

        let mut context = HotReloadContext::<TestModel>::new();

        // New XML with completely different handler
        let xml_v2 = r#"
            <dampen version="1.1" encoding="utf-8">
                <column>
                    <button label="New" on_click="new_handler" />
                    <button label="Another" on_click="another_handler" />
                </column>
            </dampen>
        "#;

        // Rebuild registry with NEW handlers only (old_handler not included)
        let result = attempt_hot_reload(xml_v2, &state_v1, &mut context, || {
            let registry = HandlerRegistry::new();
            registry.register_simple("new_handler", |_model| {});
            registry.register_simple("another_handler", |_model| {});
            registry
        });

        // Should succeed
        match result {
            ReloadResult::Success(new_state) => {
                // Model preserved
                assert_eq!(new_state.model.count, 1);
                assert_eq!(new_state.model.name, "Initial");

                // Old handler should NOT exist in new registry
                assert!(new_state.handler_registry.get("old_handler").is_none());

                // New handlers should exist
                assert!(new_state.handler_registry.get("new_handler").is_some());
                assert!(new_state.handler_registry.get("another_handler").is_some());
            }
            _ => panic!("Expected Success, got {:?}", result),
        }
    }

    #[test]
    fn test_handler_registry_rebuild_before_validation() {
        use dampen_core::handler::HandlerRegistry;
        use dampen_core::parser;

        // This test validates that registry is rebuilt BEFORE validation happens
        // Scenario: Old state has handler A, new XML needs handler B
        // If registry is rebuilt before validation, it should succeed

        let xml_v1 = r#"<dampen version="1.1" encoding="utf-8"><column><button on_click="handler_a" label="A" /></column></dampen>"#;
        let doc_v1 = parser::parse(xml_v1).unwrap();
        let model_v1 = TestModel {
            count: 100,
            name: "Test".to_string(),
        };

        let registry_v1 = HandlerRegistry::new();
        registry_v1.register_simple("handler_a", |_model| {});

        let state_v1 = AppState::with_all(doc_v1, model_v1, registry_v1);

        let mut context = HotReloadContext::<TestModel>::new();

        // New XML references handler_b (different from handler_a)
        let xml_v2 = r#"<dampen version="1.1" encoding="utf-8"><column><button on_click="handler_b" label="B" /></column></dampen>"#;

        // Registry rebuild provides handler_b
        let result = attempt_hot_reload(xml_v2, &state_v1, &mut context, || {
            let registry = HandlerRegistry::new();
            registry.register_simple("handler_b", |_model| {}); // Different handler!
            registry
        });

        // Should succeed because registry was rebuilt with handler_b BEFORE validation
        match result {
            ReloadResult::Success(new_state) => {
                assert_eq!(new_state.model.count, 100);
                // Verify new handler exists
                assert!(new_state.handler_registry.get("handler_b").is_some());
                // Verify old handler is gone
                assert!(new_state.handler_registry.get("handler_a").is_none());
            }
            _ => panic!(
                "Expected Success (registry rebuilt before validation), got {:?}",
                result
            ),
        }
    }
}

#[cfg(test)]
mod theme_reload_tests {
    use super::*;
    use dampen_core::ir::style::Color;
    use dampen_core::ir::theme::{SpacingScale, Theme, ThemeDocument, ThemePalette, Typography};
    use tempfile::TempDir;

    fn create_test_palette(primary: &str) -> ThemePalette {
        ThemePalette {
            primary: Some(Color::from_hex(primary).unwrap()),
            secondary: Some(Color::from_hex("#2ecc71").unwrap()),
            success: Some(Color::from_hex("#27ae60").unwrap()),
            warning: Some(Color::from_hex("#f39c12").unwrap()),
            danger: Some(Color::from_hex("#e74c3c").unwrap()),
            background: Some(Color::from_hex("#ecf0f1").unwrap()),
            surface: Some(Color::from_hex("#ffffff").unwrap()),
            text: Some(Color::from_hex("#2c3e50").unwrap()),
            text_secondary: Some(Color::from_hex("#7f8c8d").unwrap()),
        }
    }

    fn create_test_theme(name: &str, primary: &str) -> Theme {
        Theme {
            name: name.to_string(),
            palette: create_test_palette(primary),
            typography: Typography {
                font_family: Some("sans-serif".to_string()),
                font_size_base: Some(16.0),
                font_size_small: Some(12.0),
                font_size_large: Some(24.0),
                font_weight: dampen_core::ir::theme::FontWeight::Normal,
                line_height: Some(1.5),
            },
            spacing: SpacingScale { unit: Some(8.0) },
            base_styles: std::collections::HashMap::new(),
            extends: None,
        }
    }

    fn create_test_document() -> ThemeDocument {
        ThemeDocument {
            themes: std::collections::HashMap::from([
                ("light".to_string(), create_test_theme("light", "#3498db")),
                ("dark".to_string(), create_test_theme("dark", "#5dade2")),
            ]),
            default_theme: Some("light".to_string()),
            follow_system: true,
        }
    }

    fn create_test_theme_context() -> dampen_core::state::ThemeContext {
        let doc = create_test_document();
        dampen_core::state::ThemeContext::from_document(doc, None).unwrap()
    }

    #[test]
    fn test_attempt_theme_hot_reload_success() {
        let temp_dir = TempDir::new().unwrap();
        let theme_dir = temp_dir.path().join("src/ui/theme");
        std::fs::create_dir_all(&theme_dir).unwrap();

        let theme_content = r##"
            <dampen version="1.1" encoding="utf-8">
                <themes>
                    <theme name="light">
                        <palette
                            primary="#111111"
                            secondary="#2ecc71"
                            success="#27ae60"
                            warning="#f39c12"
                            danger="#e74c3c"
                            background="#ecf0f1"
                            surface="#ffffff"
                            text="#2c3e50"
                            text_secondary="#7f8c8d" />
                    </theme>
                </themes>
                <default_theme name="light" />
            </dampen>
        "##;

        let theme_path = theme_dir.join("theme.dampen");
        std::fs::write(&theme_path, theme_content).unwrap();

        let mut theme_ctx = Some(create_test_theme_context());
        let result = attempt_theme_hot_reload(&theme_path, &mut theme_ctx);

        match result {
            ThemeReloadResult::Success => {
                let ctx = theme_ctx.unwrap();
                assert_eq!(ctx.active_name(), "light");
                assert_eq!(
                    ctx.active().palette.primary,
                    Some(Color::from_hex("#111111").unwrap())
                );
            }
            _ => panic!("Expected Success, got {:?}", result),
        }
    }

    #[test]
    fn test_attempt_theme_hot_reload_parse_error() {
        let temp_dir = TempDir::new().unwrap();
        let theme_dir = temp_dir.path().join("src/ui/theme");
        std::fs::create_dir_all(&theme_dir).unwrap();

        let theme_path = theme_dir.join("theme.dampen");
        std::fs::write(&theme_path, "invalid xml").unwrap();

        let mut theme_ctx = Some(create_test_theme_context());
        let result = attempt_theme_hot_reload(&theme_path, &mut theme_ctx);

        match result {
            ThemeReloadResult::ParseError(_) => {}
            _ => panic!("Expected ParseError, got {:?}", result),
        }
    }

    #[test]
    fn test_attempt_theme_hot_reload_no_theme_context() {
        let temp_dir = TempDir::new().unwrap();
        let theme_dir = temp_dir.path().join("src/ui/theme");
        std::fs::create_dir_all(&theme_dir).unwrap();

        let theme_path = theme_dir.join("theme.dampen");
        std::fs::write(
            &theme_path,
            r#"<dampen version="1.1" encoding="utf-8"><themes></themes></dampen>"#,
        )
        .unwrap();

        let mut theme_ctx: Option<dampen_core::state::ThemeContext> = None;
        let result = attempt_theme_hot_reload(&theme_path, &mut theme_ctx);

        match result {
            ThemeReloadResult::NoThemeContext => {}
            _ => panic!("Expected NoThemeContext, got {:?}", result),
        }
    }

    #[test]
    fn test_attempt_theme_hot_reload_preserves_active_theme() {
        let temp_dir = TempDir::new().unwrap();
        let theme_dir = temp_dir.path().join("src/ui/theme");
        std::fs::create_dir_all(&theme_dir).unwrap();

        let theme_content = r##"
            <dampen version="1.1" encoding="utf-8">
                <themes>
                    <theme name="new_theme">
                        <palette
                            primary="#ff0000"
                            secondary="#2ecc71"
                            success="#27ae60"
                            warning="#f39c12"
                            danger="#e74c3c"
                            background="#ecf0f1"
                            surface="#ffffff"
                            text="#2c3e50"
                            text_secondary="#7f8c8d" />
                    </theme>
                    <theme name="dark">
                        <palette
                            primary="#5dade2"
                            secondary="#52be80"
                            success="#27ae60"
                            warning="#f39c12"
                            danger="#ec7063"
                            background="#2c3e50"
                            surface="#34495e"
                            text="#ecf0f1"
                            text_secondary="#95a5a6" />
                    </theme>
                </themes>
                <default_theme name="new_theme" />
            </dampen>
        "##;

        let theme_path = theme_dir.join("theme.dampen");
        std::fs::write(&theme_path, theme_content).unwrap();

        let mut theme_ctx = Some(create_test_theme_context());
        theme_ctx.as_mut().unwrap().set_theme("dark").unwrap();
        assert_eq!(theme_ctx.as_ref().unwrap().active_name(), "dark");

        let result = attempt_theme_hot_reload(&theme_path, &mut theme_ctx);

        match result {
            ThemeReloadResult::Success => {
                let ctx = theme_ctx.unwrap();
                assert_eq!(ctx.active_name(), "dark");
            }
            _ => panic!("Expected Success, got {:?}", result),
        }
    }

    #[test]
    fn test_is_theme_file_path() {
        assert!(is_theme_file_path(&std::path::PathBuf::from(
            "src/ui/theme/theme.dampen"
        )));
        assert!(!is_theme_file_path(&std::path::PathBuf::from(
            "src/ui/window.dampen"
        )));
        assert!(is_theme_file_path(&std::path::PathBuf::from(
            "/some/path/theme.dampen"
        )));
    }

    #[test]
    fn test_get_theme_dir_from_path() {
        let temp_dir = TempDir::new().unwrap();
        let theme_dir = temp_dir.path().join("src/ui/theme");
        std::fs::create_dir_all(&theme_dir).unwrap();
        let theme_path = theme_dir.join("theme.dampen");
        std::fs::write(
            &theme_path,
            "<dampen version=\"1.0\"><themes></themes></dampen>",
        )
        .unwrap();

        let result = get_theme_dir_from_path(&theme_path);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), theme_dir);
    }
}