kiran 1.0.0

Kiran — AI-native game engine for AGNOS
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
//! ECS world, generational entity allocator, game clock, event bus
//!
//! Provides the fundamental building blocks for the Kiran game engine:
//! - Entity allocation with generational indices
//! - Component storage (type-erased, per-entity)
//! - Singleton resources
//! - Typed event bus
//! - Game clock with fixed timestep support

use std::any::{Any, TypeId};
use std::collections::HashMap;

use thiserror::Error;

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Errors produced by kiran.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum KiranError {
    /// Entity does not exist in the world.
    #[error("entity {0:?} does not exist")]
    EntityNotFound(Entity),

    /// Component not found on the entity.
    #[error("component not found for entity {0:?}")]
    ComponentNotFound(Entity),

    /// Singleton resource not found.
    #[error("resource of type `{0}` not found")]
    ResourceNotFound(&'static str),

    /// Entity was already despawned (stale handle).
    #[error("entity {0:?} has already been despawned")]
    EntityDespawned(Entity),

    /// Scene-related error.
    #[error("scene error: {0}")]
    Scene(String),

    /// Rendering error.
    #[error("render error: {0}")]
    Render(String),

    /// Catch-all for other errors.
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

/// Convenience alias for `std::result::Result<T, KiranError>`.
pub type Result<T> = std::result::Result<T, KiranError>;

// ---------------------------------------------------------------------------
// Entity
// ---------------------------------------------------------------------------

/// A handle to an entity in the ECS world.
///
/// Upper 32 bits = generation, lower 32 bits = index.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Entity(u64);

impl Entity {
    /// Create an entity from an index and generation.
    #[inline]
    pub fn new(index: u32, generation: u32) -> Self {
        Self((generation as u64) << 32 | index as u64)
    }

    /// Index portion (lower 32 bits).
    #[inline]
    pub fn index(self) -> u32 {
        self.0 as u32
    }

    /// Generation portion (upper 32 bits).
    #[inline]
    pub fn generation(self) -> u32 {
        (self.0 >> 32) as u32
    }

    /// Raw u64 id.
    #[inline]
    pub fn id(self) -> u64 {
        self.0
    }

    /// Reconstruct an entity from a raw u64 id.
    #[inline]
    pub fn from_id(id: u64) -> Self {
        Self(id)
    }
}

impl std::fmt::Debug for Entity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Entity({}v{})", self.index(), self.generation())
    }
}

impl std::fmt::Display for Entity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}v{}", self.index(), self.generation())
    }
}

// ---------------------------------------------------------------------------
// EntityAllocator
// ---------------------------------------------------------------------------

/// Allocates and recycles entity indices with generational safety.
#[derive(Debug, Default)]
pub struct EntityAllocator {
    /// Next fresh index (used when free list is empty).
    next_index: u32,
    /// Generation per index slot.
    generations: Vec<u32>,
    /// Recycled indices available for reuse.
    free_list: Vec<u32>,
    /// Tracks which entities are alive.
    alive: Vec<bool>,
    /// Cached count of alive entities (avoids O(n) scan).
    alive_count: usize,
}

impl EntityAllocator {
    /// Allocate a new entity.
    pub fn spawn(&mut self) -> Entity {
        self.alive_count += 1;
        if let Some(index) = self.free_list.pop() {
            self.alive[index as usize] = true;
            Entity::new(index, self.generations[index as usize])
        } else {
            let index = self.next_index;
            self.next_index += 1;
            self.generations.push(0);
            self.alive.push(true);
            Entity::new(index, 0)
        }
    }

    /// Despawn an entity, bumping its generation for reuse.
    pub fn despawn(&mut self, entity: Entity) -> Result<()> {
        let idx = entity.index() as usize;
        if idx >= self.alive.len() || !self.alive[idx] {
            return Err(KiranError::EntityNotFound(entity));
        }
        if self.generations[idx] != entity.generation() {
            return Err(KiranError::EntityDespawned(entity));
        }
        self.alive[idx] = false;
        self.alive_count -= 1;
        self.generations[idx] += 1;
        self.free_list.push(entity.index());
        Ok(())
    }

    /// Check whether an entity handle is still alive.
    pub fn is_alive(&self, entity: Entity) -> bool {
        let idx = entity.index() as usize;
        idx < self.alive.len() && self.alive[idx] && self.generations[idx] == entity.generation()
    }

    /// Number of currently alive entities (O(1)).
    pub fn alive_count(&self) -> usize {
        self.alive_count
    }
}

// ---------------------------------------------------------------------------
// World
// ---------------------------------------------------------------------------

/// Dense component storage indexed by entity index (O(1) access).
type ComponentVec = Vec<Option<Box<dyn Any + Send + Sync>>>;

/// A resource entry: value + change tracking ticks.
struct ResourceEntry {
    value: Box<dyn Any + Send + Sync>,
    /// Tick at which this resource was last mutated.
    changed_tick: u64,
    /// Tick at which this resource was last checked via `clear_resource_changed`.
    last_checked_tick: Option<u64>,
}

/// The central ECS container — entities, components, and resources.
pub struct World {
    allocator: EntityAllocator,
    /// component storage: TypeId -> vec indexed by entity index
    components: HashMap<TypeId, ComponentVec>,
    /// singleton resources with integrated change tracking (single HashMap lookup)
    resources: HashMap<TypeId, ResourceEntry>,
    /// Global change tick (incremented via `increment_tick()`).
    tick: u64,
}

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

impl World {
    /// Create an empty world.
    ///
    /// # Examples
    ///
    /// ```
    /// use kiran::World;
    ///
    /// let mut world = World::new();
    /// let entity = world.spawn();
    /// world.insert_component(entity, 42_u32).unwrap();
    /// assert_eq!(world.entity_count(), 1);
    /// let results = world.query::<u32>();
    /// assert_eq!(results.len(), 1);
    /// ```
    pub fn new() -> Self {
        Self {
            allocator: EntityAllocator::default(),
            components: HashMap::new(),
            resources: HashMap::new(),
            tick: 0,
        }
    }

    /// Spawn a new entity.
    pub fn spawn(&mut self) -> Entity {
        self.allocator.spawn()
    }

    /// Despawn an entity and remove all its components.
    pub fn despawn(&mut self, entity: Entity) -> Result<()> {
        self.allocator.despawn(entity)?;
        let idx = entity.index() as usize;
        for storage in self.components.values_mut() {
            if idx < storage.len() {
                storage[idx] = None;
            }
        }
        Ok(())
    }

    /// Check if an entity is alive.
    pub fn is_alive(&self, entity: Entity) -> bool {
        self.allocator.is_alive(entity)
    }

    /// Insert a component on an entity.
    pub fn insert_component<T: 'static + Send + Sync>(
        &mut self,
        entity: Entity,
        component: T,
    ) -> Result<()> {
        if !self.allocator.is_alive(entity) {
            return Err(KiranError::EntityNotFound(entity));
        }
        let idx = entity.index() as usize;
        let storage = self.components.entry(TypeId::of::<T>()).or_default();
        if idx >= storage.len() {
            storage.resize_with(idx + 1, || None);
        }
        storage[idx] = Some(Box::new(component));
        Ok(())
    }

    /// Check if an entity has a component of the given type.
    pub fn has_component<T: 'static + Send + Sync>(&self, entity: Entity) -> bool {
        let idx = entity.index() as usize;
        self.components
            .get(&TypeId::of::<T>())
            .is_some_and(|storage| storage.get(idx).is_some_and(|slot| slot.is_some()))
    }

    /// Get a reference to an entity's component.
    pub fn get_component<T: 'static + Send + Sync>(&self, entity: Entity) -> Option<&T> {
        let idx = entity.index() as usize;
        self.components
            .get(&TypeId::of::<T>())?
            .get(idx)?
            .as_ref()?
            .downcast_ref::<T>()
    }

    /// Get a mutable reference to an entity's component.
    pub fn get_component_mut<T: 'static + Send + Sync>(
        &mut self,
        entity: Entity,
    ) -> Option<&mut T> {
        let idx = entity.index() as usize;
        self.components
            .get_mut(&TypeId::of::<T>())?
            .get_mut(idx)?
            .as_mut()?
            .downcast_mut::<T>()
    }

    /// Remove a component from an entity, returning it if it existed.
    pub fn remove_component<T: 'static + Send + Sync>(&mut self, entity: Entity) -> Option<T> {
        let idx = entity.index() as usize;
        let storage = self.components.get_mut(&TypeId::of::<T>())?;
        let boxed = storage.get_mut(idx)?.take()?;
        boxed.downcast::<T>().ok().map(|b| *b)
    }

    /// Insert a singleton resource.
    pub fn insert_resource<T: 'static + Send + Sync>(&mut self, resource: T) {
        self.resources.insert(
            TypeId::of::<T>(),
            ResourceEntry {
                value: Box::new(resource),
                changed_tick: self.tick,
                last_checked_tick: None,
            },
        );
    }

    /// Get a reference to a singleton resource.
    pub fn get_resource<T: 'static + Send + Sync>(&self) -> Option<&T> {
        self.resources
            .get(&TypeId::of::<T>())?
            .value
            .downcast_ref::<T>()
    }

    /// Get a mutable reference to a singleton resource.
    /// Marks the resource as changed at the current tick.
    pub fn get_resource_mut<T: 'static + Send + Sync>(&mut self) -> Option<&mut T> {
        let entry = self.resources.get_mut(&TypeId::of::<T>())?;
        entry.changed_tick = self.tick;
        entry.value.downcast_mut::<T>()
    }

    /// Check if a resource has changed since the last call to `clear_resource_changed`.
    pub fn is_resource_changed<T: 'static + Send + Sync>(&self) -> bool {
        let Some(entry) = self.resources.get(&TypeId::of::<T>()) else {
            return false;
        };
        match entry.last_checked_tick {
            Some(checked) => entry.changed_tick > checked,
            None => true, // never checked → changed
        }
    }

    /// Mark a resource as "seen" — future `is_resource_changed` returns false until modified again.
    pub fn clear_resource_changed<T: 'static + Send + Sync>(&mut self) {
        if let Some(entry) = self.resources.get_mut(&TypeId::of::<T>()) {
            entry.last_checked_tick = Some(self.tick);
        }
    }

    /// Increment the global change tick. Call once per frame.
    pub fn increment_tick(&mut self) {
        self.tick += 1;
    }

    /// Current global tick.
    pub fn tick(&self) -> u64 {
        self.tick
    }

    /// Number of alive entities.
    pub fn entity_count(&self) -> usize {
        self.allocator.alive_count()
    }

    // -----------------------------------------------------------------------
    // Queries — iterate entities by component set
    // -----------------------------------------------------------------------

    /// Iterate all entities with component `A`.
    /// Returns `(Entity, &A)` for each matching entity.
    pub fn query<A: 'static + Send + Sync>(&self) -> Vec<(Entity, &A)> {
        let tid = TypeId::of::<A>();
        let Some(storage) = self.components.get(&tid) else {
            return Vec::new();
        };
        let mut results = Vec::new();
        for (idx, slot) in storage.iter().enumerate() {
            if let Some(boxed) = slot
                && let Some(component) = boxed.downcast_ref::<A>()
                && idx < self.allocator.generations.len()
                && self
                    .allocator
                    .is_alive(Entity::new(idx as u32, self.allocator.generations[idx]))
            {
                results.push((
                    Entity::new(idx as u32, self.allocator.generations[idx]),
                    component,
                ));
            }
        }
        results
    }

    /// Iterate all entities with components `A` and `B`.
    pub fn query2<A: 'static + Send + Sync, B: 'static + Send + Sync>(
        &self,
    ) -> Vec<(Entity, &A, &B)> {
        let tid_a = TypeId::of::<A>();
        let tid_b = TypeId::of::<B>();
        let (Some(storage_a), Some(storage_b)) =
            (self.components.get(&tid_a), self.components.get(&tid_b))
        else {
            return Vec::new();
        };
        let len = storage_a
            .len()
            .min(storage_b.len())
            .min(self.allocator.generations.len());
        let mut results = Vec::new();
        for idx in 0..len {
            if let (Some(Some(box_a)), Some(Some(box_b))) = (storage_a.get(idx), storage_b.get(idx))
                && let (Some(a), Some(b)) = (box_a.downcast_ref::<A>(), box_b.downcast_ref::<B>())
                && self
                    .allocator
                    .is_alive(Entity::new(idx as u32, self.allocator.generations[idx]))
            {
                results.push((
                    Entity::new(idx as u32, self.allocator.generations[idx]),
                    a,
                    b,
                ));
            }
        }
        results
    }

    /// Iterate all entities with components `A`, `B`, and `C`.
    pub fn query3<A: 'static + Send + Sync, B: 'static + Send + Sync, C: 'static + Send + Sync>(
        &self,
    ) -> Vec<(Entity, &A, &B, &C)> {
        let tid_a = TypeId::of::<A>();
        let tid_b = TypeId::of::<B>();
        let tid_c = TypeId::of::<C>();
        let (Some(sa), Some(sb), Some(sc)) = (
            self.components.get(&tid_a),
            self.components.get(&tid_b),
            self.components.get(&tid_c),
        ) else {
            return Vec::new();
        };
        let len = sa
            .len()
            .min(sb.len())
            .min(sc.len())
            .min(self.allocator.generations.len());
        let mut results = Vec::new();
        for idx in 0..len {
            if let (Some(Some(ba)), Some(Some(bb)), Some(Some(bc))) =
                (sa.get(idx), sb.get(idx), sc.get(idx))
                && let (Some(a), Some(b), Some(c)) = (
                    ba.downcast_ref::<A>(),
                    bb.downcast_ref::<B>(),
                    bc.downcast_ref::<C>(),
                )
                && self
                    .allocator
                    .is_alive(Entity::new(idx as u32, self.allocator.generations[idx]))
            {
                results.push((
                    Entity::new(idx as u32, self.allocator.generations[idx]),
                    a,
                    b,
                    c,
                ));
            }
        }
        results
    }
}

// ---------------------------------------------------------------------------
// Entity Commands — deferred mutations
// ---------------------------------------------------------------------------

type InitFn = Box<dyn FnOnce(&mut World, Entity)>;

/// A deferred command to apply to the world between system stages.
enum Command {
    Spawn(Vec<InitFn>),
    Despawn(Entity),
    InsertComponent(Entity, TypeId, Box<dyn Any + Send + Sync>),
    RemoveComponent(Entity, TypeId),
}

/// Deferred command buffer — collect spawn/despawn/insert during systems,
/// apply between stages without requiring `&mut World`.
#[derive(Default)]
pub struct Commands {
    queue: Vec<Command>,
}

impl Commands {
    /// Create an empty command buffer.
    pub fn new() -> Self {
        Self::default()
    }

    /// Queue an entity spawn. Returns a placeholder entity ID.
    /// Components can be added via the returned builder.
    pub fn spawn(&mut self) -> CommandEntityBuilder<'_> {
        let idx = self.queue.len();
        self.queue.push(Command::Spawn(Vec::new()));
        CommandEntityBuilder {
            commands: self,
            spawn_idx: idx,
        }
    }

    /// Queue an entity despawn.
    pub fn despawn(&mut self, entity: Entity) {
        self.queue.push(Command::Despawn(entity));
    }

    /// Queue inserting a component on an entity.
    pub fn insert<T: 'static + Send + Sync>(&mut self, entity: Entity, component: T) {
        self.queue.push(Command::InsertComponent(
            entity,
            TypeId::of::<T>(),
            Box::new(component),
        ));
    }

    /// Queue removing a component from an entity.
    pub fn remove<T: 'static + Send + Sync>(&mut self, entity: Entity) {
        self.queue
            .push(Command::RemoveComponent(entity, TypeId::of::<T>()));
    }

    /// Number of pending commands.
    pub fn len(&self) -> usize {
        self.queue.len()
    }

    /// Whether the command buffer is empty.
    pub fn is_empty(&self) -> bool {
        self.queue.is_empty()
    }

    /// Apply all queued commands to the world, consuming the buffer.
    pub fn apply(self, world: &mut World) {
        for cmd in self.queue {
            match cmd {
                Command::Spawn(init_fns) => {
                    let entity = world.spawn();
                    for f in init_fns {
                        f(world, entity);
                    }
                }
                Command::Despawn(entity) => {
                    let _ = world.despawn(entity);
                }
                Command::InsertComponent(entity, tid, boxed) => {
                    let idx = entity.index() as usize;
                    let storage = world.components.entry(tid).or_default();
                    if idx >= storage.len() {
                        storage.resize_with(idx + 1, || None);
                    }
                    storage[idx] = Some(boxed);
                }
                Command::RemoveComponent(entity, tid) => {
                    let idx = entity.index() as usize;
                    if let Some(storage) = world.components.get_mut(&tid)
                        && idx < storage.len()
                    {
                        storage[idx] = None;
                    }
                }
            }
        }
    }
}

/// Builder for adding components to a spawned entity command.
pub struct CommandEntityBuilder<'a> {
    commands: &'a mut Commands,
    spawn_idx: usize,
}

impl<'a> CommandEntityBuilder<'a> {
    /// Add a component to the entity being spawned.
    pub fn with<T: 'static + Send + Sync>(self, component: T) -> Self {
        if let Command::Spawn(ref mut init_fns) = self.commands.queue[self.spawn_idx] {
            init_fns.push(Box::new(move |world: &mut World, entity: Entity| {
                let _ = world.insert_component(entity, component);
            }));
        }
        self
    }
}

// ---------------------------------------------------------------------------
// Component change detection
// ---------------------------------------------------------------------------

/// Tracks per-component change ticks for change detection.
/// Store as a resource to enable `Changed<T>` / `Added<T>` queries.
#[derive(Default)]
pub struct ChangeTracker {
    /// (TypeId, entity_index) → tick when last modified
    changed: HashMap<(TypeId, u32), u64>,
    /// (TypeId, entity_index) → tick when first added
    added: HashMap<(TypeId, u32), u64>,
}

impl ChangeTracker {
    /// Create an empty change tracker.
    pub fn new() -> Self {
        Self::default()
    }

    /// Mark a component as changed at the given tick.
    pub fn mark_changed<T: 'static>(&mut self, entity: Entity, tick: u64) {
        self.changed
            .insert((TypeId::of::<T>(), entity.index()), tick);
    }

    /// Mark a component as added at the given tick.
    pub fn mark_added<T: 'static>(&mut self, entity: Entity, tick: u64) {
        self.added.insert((TypeId::of::<T>(), entity.index()), tick);
    }

    /// Check if a component was changed since `since_tick`.
    pub fn is_changed<T: 'static>(&self, entity: Entity, since_tick: u64) -> bool {
        self.changed
            .get(&(TypeId::of::<T>(), entity.index()))
            .is_some_and(|&tick| tick > since_tick)
    }

    /// Check if a component was added since `since_tick`.
    pub fn is_added<T: 'static>(&self, entity: Entity, since_tick: u64) -> bool {
        self.added
            .get(&(TypeId::of::<T>(), entity.index()))
            .is_some_and(|&tick| tick > since_tick)
    }

    /// Clear tracking for a despawned entity.
    pub fn clear_entity(&mut self, entity: Entity) {
        let idx = entity.index();
        self.changed.retain(|&(_, i), _| i != idx);
        self.added.retain(|&(_, i), _| i != idx);
    }
}

// ---------------------------------------------------------------------------
// System trait + scheduler
// ---------------------------------------------------------------------------

/// Pipeline stage for ordering systems.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum SystemStage {
    /// Read input events, update InputState.
    Input = 0,
    /// Fixed-timestep physics simulation.
    Physics = 1,
    /// Gameplay logic (AI, scripting, game rules).
    GameLogic = 2,
    /// Submit draw commands, update cameras.
    Render = 3,
}

/// A system that operates on the world each frame.
pub trait System: Send {
    /// Run this system against the world.
    fn run(&mut self, world: &mut World);

    /// Which stage this system belongs to.
    fn stage(&self) -> SystemStage;

    /// Human-readable name for debugging.
    fn name(&self) -> &str;

    /// Systems this must run after (by name). Default: none.
    fn after(&self) -> &[&str] {
        &[]
    }

    /// Systems this must run before (by name). Default: none.
    fn before(&self) -> &[&str] {
        &[]
    }
}

/// Insert multiple components on an entity atomically.
pub fn insert_bundle(
    world: &mut World,
    entity: Entity,
    components: Vec<(TypeId, Box<dyn Any + Send + Sync>)>,
) -> Result<()> {
    if !world.is_alive(entity) {
        return Err(KiranError::EntityNotFound(entity));
    }
    let idx = entity.index() as usize;
    for (tid, boxed) in components {
        let storage = world.components.entry(tid).or_default();
        if idx >= storage.len() {
            storage.resize_with(idx + 1, || None);
        }
        storage[idx] = Some(boxed);
    }
    Ok(())
}

/// Helper macro-free bundle builder.
pub struct Bundle {
    components: Vec<(TypeId, Box<dyn Any + Send + Sync>)>,
}

impl Bundle {
    /// Create an empty bundle.
    pub fn new() -> Self {
        Self {
            components: Vec::new(),
        }
    }

    /// Add a component to the bundle.
    pub fn with<T: 'static + Send + Sync>(mut self, component: T) -> Self {
        self.components
            .push((TypeId::of::<T>(), Box::new(component)));
        self
    }

    /// Insert all components onto an entity.
    pub fn apply(self, world: &mut World, entity: Entity) -> Result<()> {
        insert_bundle(world, entity, self.components)
    }
}

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

/// Runs systems in stage order: Input → Physics → GameLogic → Render.
///
/// Within each stage, respects `before`/`after` ordering constraints via
/// topological sort. Systems with no ordering dependencies within a stage
/// can be run concurrently when `run_parallel` is enabled.
pub struct Scheduler {
    systems: Vec<Box<dyn System>>,
    /// Cached execution order (indices into `systems`).
    order: Vec<usize>,
    dirty: bool,
    /// Enable parallel execution of independent systems within a stage.
    pub run_parallel: bool,
}

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

impl Scheduler {
    /// Create an empty scheduler.
    pub fn new() -> Self {
        Self {
            systems: Vec::new(),
            order: Vec::new(),
            dirty: true,
            run_parallel: false,
        }
    }

    /// Add a system to the scheduler.
    pub fn add_system(&mut self, system: Box<dyn System>) {
        self.systems.push(system);
        self.dirty = true;
    }

    /// Rebuild execution order: stage sort + topological sort within each stage.
    fn rebuild_order(&mut self) {
        let n = self.systems.len();
        if n == 0 {
            self.order.clear();
            self.dirty = false;
            return;
        }

        // Group system indices by stage
        let mut by_stage: std::collections::BTreeMap<SystemStage, Vec<usize>> =
            std::collections::BTreeMap::new();
        for (i, sys) in self.systems.iter().enumerate() {
            by_stage.entry(sys.stage()).or_default().push(i);
        }

        self.order.clear();
        self.order.reserve(n);

        for (_stage, indices) in &by_stage {
            if indices.len() <= 1 {
                self.order.extend(indices);
                continue;
            }

            // Build name → index map for this stage
            let name_to_idx: HashMap<&str, usize> = indices
                .iter()
                .map(|&i| (self.systems[i].name(), i))
                .collect();

            // Topological sort within this stage
            let mut in_degree: HashMap<usize, usize> = indices.iter().map(|&i| (i, 0)).collect();
            let mut edges: HashMap<usize, Vec<usize>> = HashMap::new();

            for &i in indices {
                // "after" means i runs after the named system → edge from named → i
                for &dep_name in self.systems[i].after() {
                    if let Some(&dep_idx) = name_to_idx.get(dep_name) {
                        edges.entry(dep_idx).or_default().push(i);
                        *in_degree.entry(i).or_default() += 1;
                    }
                }
                // "before" means i runs before the named system → edge from i → named
                for &dep_name in self.systems[i].before() {
                    if let Some(&dep_idx) = name_to_idx.get(dep_name) {
                        edges.entry(i).or_default().push(dep_idx);
                        *in_degree.entry(dep_idx).or_default() += 1;
                    }
                }
            }

            // Kahn's algorithm
            let mut queue: std::collections::VecDeque<usize> = indices
                .iter()
                .filter(|&&i| in_degree.get(&i).copied().unwrap_or(0) == 0)
                .copied()
                .collect();

            let mut sorted = Vec::with_capacity(indices.len());
            while let Some(node) = queue.pop_front() {
                sorted.push(node);
                if let Some(neighbors) = edges.get(&node) {
                    for &neighbor in neighbors {
                        if let Some(deg) = in_degree.get_mut(&neighbor) {
                            *deg -= 1;
                            if *deg == 0 {
                                queue.push_back(neighbor);
                            }
                        }
                    }
                }
            }

            // If cycle detected, fall back to original order
            if sorted.len() == indices.len() {
                self.order.extend(sorted);
            } else {
                tracing::warn!(
                    stage = ?_stage,
                    "cycle detected in system ordering, using insertion order"
                );
                self.order.extend(indices);
            }
        }

        self.dirty = false;
    }

    /// Run all systems in stage order against the world.
    pub fn run(&mut self, world: &mut World) {
        if self.dirty {
            self.rebuild_order();
        }
        for &idx in &self.order {
            self.systems[idx].run(world);
        }
    }

    /// Number of registered systems.
    #[must_use]
    #[inline]
    pub fn system_count(&self) -> usize {
        self.systems.len()
    }

    /// List system names in execution order.
    pub fn system_names(&mut self) -> Vec<&str> {
        if self.dirty {
            self.rebuild_order();
        }
        self.order.iter().map(|&i| self.systems[i].name()).collect()
    }
}

/// Convenience: wrap a closure as a system.
pub struct FnSystem<F: FnMut(&mut World) + Send> {
    func: F,
    stage: SystemStage,
    name: String,
}

impl<F: FnMut(&mut World) + Send> FnSystem<F> {
    /// Create a closure-based system with a name and stage.
    pub fn new(name: impl Into<String>, stage: SystemStage, func: F) -> Self {
        Self {
            func,
            stage,
            name: name.into(),
        }
    }
}

impl<F: FnMut(&mut World) + Send> System for FnSystem<F> {
    fn run(&mut self, world: &mut World) {
        (self.func)(world);
    }

    fn stage(&self) -> SystemStage {
        self.stage
    }

    fn name(&self) -> &str {
        &self.name
    }
}

// ---------------------------------------------------------------------------
// GameClock
// ---------------------------------------------------------------------------

/// Tracks frame timing and provides a fixed timestep accumulator.
#[derive(Debug, Clone)]
pub struct GameClock {
    /// Delta time for this frame (seconds).
    pub delta: f64,
    /// Total elapsed time (seconds).
    pub elapsed: f64,
    /// Frame counter.
    pub frame: u64,
    /// Fixed timestep interval (seconds).
    pub fixed_timestep: f64,
    /// Internal accumulator for fixed updates.
    accumulator: f64,
}

impl Default for GameClock {
    fn default() -> Self {
        Self {
            delta: 0.0,
            elapsed: 0.0,
            frame: 0,
            fixed_timestep: 1.0 / 60.0,
            accumulator: 0.0,
        }
    }
}

impl GameClock {
    /// Create a clock with a given fixed timestep.
    pub fn with_timestep(fixed_timestep: f64) -> Self {
        Self {
            fixed_timestep,
            ..Default::default()
        }
    }

    /// Advance the clock by `dt` seconds.
    pub fn tick(&mut self, dt: f64) {
        self.delta = dt;
        self.elapsed += dt;
        self.frame += 1;
        self.accumulator += dt;
    }

    /// Consume one fixed-timestep chunk if available. Returns true if consumed.
    pub fn consume_fixed(&mut self) -> bool {
        if self.accumulator >= self.fixed_timestep {
            self.accumulator -= self.fixed_timestep;
            true
        } else {
            false
        }
    }

    /// How many fixed steps are pending.
    pub fn pending_fixed_steps(&self) -> u32 {
        (self.accumulator / self.fixed_timestep) as u32
    }
}

// ---------------------------------------------------------------------------
// EventBus
// ---------------------------------------------------------------------------

/// A simple typed event bus: publish events, drain per type.
#[derive(Default)]
pub struct EventBus {
    channels: HashMap<TypeId, Vec<Box<dyn Any + Send + Sync>>>,
}

impl EventBus {
    /// Create an empty event bus.
    pub fn new() -> Self {
        Self::default()
    }

    /// Publish an event.
    pub fn publish<E: 'static + Send + Sync>(&mut self, event: E) {
        self.channels
            .entry(TypeId::of::<E>())
            .or_default()
            .push(Box::new(event));
    }

    /// Drain all events of a given type, returning them.
    pub fn drain<E: 'static + Send + Sync>(&mut self) -> Vec<E> {
        self.channels
            .remove(&TypeId::of::<E>())
            .unwrap_or_default()
            .into_iter()
            .filter_map(|b| b.downcast::<E>().ok().map(|b| *b))
            .collect()
    }

    /// Peek at the count of pending events of a given type.
    pub fn count<E: 'static + Send + Sync>(&self) -> usize {
        self.channels.get(&TypeId::of::<E>()).map_or(0, |v| v.len())
    }

    /// Clear all events across all types.
    pub fn clear(&mut self) {
        self.channels.clear();
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- Entity tests --

    #[test]
    fn entity_index_generation() {
        let e = Entity::new(42, 7);
        assert_eq!(e.index(), 42);
        assert_eq!(e.generation(), 7);
    }

    #[test]
    fn entity_id_roundtrip() {
        let e = Entity::new(100, 3);
        let id = e.id();
        let e2 = Entity(id);
        assert_eq!(e, e2);
    }

    #[test]
    fn entity_display() {
        let e = Entity::new(5, 2);
        assert_eq!(format!("{e}"), "5v2");
        assert_eq!(format!("{e:?}"), "Entity(5v2)");
    }

    // -- EntityAllocator tests --

    #[test]
    fn allocator_spawn_sequential() {
        let mut alloc = EntityAllocator::default();
        let e0 = alloc.spawn();
        let e1 = alloc.spawn();
        assert_eq!(e0.index(), 0);
        assert_eq!(e1.index(), 1);
        assert_eq!(e0.generation(), 0);
        assert_eq!(alloc.alive_count(), 2);
    }

    #[test]
    fn allocator_despawn_and_recycle() {
        let mut alloc = EntityAllocator::default();
        let e0 = alloc.spawn();
        alloc.despawn(e0).unwrap();
        assert_eq!(alloc.alive_count(), 0);

        let e0_reused = alloc.spawn();
        assert_eq!(e0_reused.index(), 0);
        assert_eq!(e0_reused.generation(), 1);
        assert!(alloc.is_alive(e0_reused));
        assert!(!alloc.is_alive(e0)); // stale handle
    }

    #[test]
    fn allocator_despawn_invalid() {
        let mut alloc = EntityAllocator::default();
        let fake = Entity::new(999, 0);
        assert!(alloc.despawn(fake).is_err());
    }

    #[test]
    fn allocator_double_despawn() {
        let mut alloc = EntityAllocator::default();
        let e = alloc.spawn();
        alloc.despawn(e).unwrap();
        assert!(alloc.despawn(e).is_err());
    }

    // -- World tests --

    #[derive(Debug, Clone, PartialEq)]
    struct Health(i32);

    #[derive(Debug, Clone, PartialEq)]
    struct Velocity {
        x: f32,
        y: f32,
    }

    #[test]
    fn world_spawn_and_count() {
        let mut world = World::new();
        assert_eq!(world.entity_count(), 0);
        let _e = world.spawn();
        assert_eq!(world.entity_count(), 1);
        let _e2 = world.spawn();
        assert_eq!(world.entity_count(), 2);
    }

    #[test]
    fn world_insert_get_component() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(100)).unwrap();

        let h = world.get_component::<Health>(e).unwrap();
        assert_eq!(h.0, 100);
    }

    #[test]
    fn world_get_missing_component() {
        let world = World::new();
        let e = Entity::new(0, 0);
        assert!(world.get_component::<Health>(e).is_none());
    }

    #[test]
    fn world_remove_component() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(50)).unwrap();

        let removed = world.remove_component::<Health>(e);
        assert_eq!(removed, Some(Health(50)));
        assert!(world.get_component::<Health>(e).is_none());
    }

    #[test]
    fn world_despawn_removes_components() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(75)).unwrap();
        world
            .insert_component(e, Velocity { x: 1.0, y: 2.0 })
            .unwrap();

        world.despawn(e).unwrap();
        assert_eq!(world.entity_count(), 0);
    }

    #[test]
    fn world_component_mut() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(10)).unwrap();

        let h = world.get_component_mut::<Health>(e).unwrap();
        h.0 += 5;

        assert_eq!(world.get_component::<Health>(e).unwrap().0, 15);
    }

    #[test]
    fn world_insert_component_dead_entity() {
        let mut world = World::new();
        let e = world.spawn();
        world.despawn(e).unwrap();
        assert!(world.insert_component(e, Health(1)).is_err());
    }

    #[test]
    fn world_multiple_component_types() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(100)).unwrap();
        world
            .insert_component(e, Velocity { x: 3.0, y: 4.0 })
            .unwrap();

        assert_eq!(world.get_component::<Health>(e).unwrap().0, 100);
        assert_eq!(world.get_component::<Velocity>(e).unwrap().x, 3.0);
    }

    // -- Resource tests --

    #[derive(Debug, PartialEq)]
    struct Gravity(f64);

    #[test]
    fn world_resources() {
        let mut world = World::new();
        world.insert_resource(Gravity(9.81));
        assert_eq!(world.get_resource::<Gravity>().unwrap().0, 9.81);

        let g = world.get_resource_mut::<Gravity>().unwrap();
        g.0 = 1.625;
        assert_eq!(world.get_resource::<Gravity>().unwrap().0, 1.625);
    }

    #[test]
    fn world_missing_resource() {
        let world = World::new();
        assert!(world.get_resource::<Gravity>().is_none());
    }

    // -- GameClock tests --

    #[test]
    fn clock_tick() {
        let mut clock = GameClock::default();
        clock.tick(0.016);
        assert_eq!(clock.frame, 1);
        assert!((clock.delta - 0.016).abs() < 1e-10);
        assert!((clock.elapsed - 0.016).abs() < 1e-10);
    }

    #[test]
    fn clock_fixed_step() {
        let mut clock = GameClock::with_timestep(1.0 / 60.0);
        clock.tick(0.033); // ~2 frames at 60fps
        assert_eq!(clock.pending_fixed_steps(), 1);
        assert!(clock.consume_fixed());
        assert_eq!(clock.pending_fixed_steps(), 0);
    }

    #[test]
    fn clock_no_fixed_step_when_below() {
        let mut clock = GameClock::with_timestep(1.0 / 60.0);
        clock.tick(0.001);
        assert!(!clock.consume_fixed());
    }

    // -- EventBus tests --

    #[derive(Debug, PartialEq)]
    struct Collision {
        a: u64,
        b: u64,
    }

    #[derive(Debug, PartialEq)]
    struct ScoreChanged(i32);

    #[test]
    fn event_bus_publish_drain() {
        let mut bus = EventBus::new();
        bus.publish(Collision { a: 1, b: 2 });
        bus.publish(Collision { a: 3, b: 4 });

        assert_eq!(bus.count::<Collision>(), 2);
        let events = bus.drain::<Collision>();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0], Collision { a: 1, b: 2 });
        assert_eq!(bus.count::<Collision>(), 0);
    }

    #[test]
    fn event_bus_different_types() {
        let mut bus = EventBus::new();
        bus.publish(Collision { a: 1, b: 2 });
        bus.publish(ScoreChanged(10));

        assert_eq!(bus.count::<Collision>(), 1);
        assert_eq!(bus.count::<ScoreChanged>(), 1);

        let scores = bus.drain::<ScoreChanged>();
        assert_eq!(scores.len(), 1);
        assert_eq!(scores[0].0, 10);
    }

    #[test]
    fn event_bus_drain_empty() {
        let mut bus = EventBus::new();
        let events = bus.drain::<Collision>();
        assert!(events.is_empty());
    }

    #[test]
    fn event_bus_clear() {
        let mut bus = EventBus::new();
        bus.publish(Collision { a: 0, b: 0 });
        bus.publish(ScoreChanged(5));
        bus.clear();
        assert_eq!(bus.count::<Collision>(), 0);
        assert_eq!(bus.count::<ScoreChanged>(), 0);
    }

    // -- Stress / edge case tests --

    #[test]
    fn stress_spawn_despawn_1000() {
        let mut world = World::new();
        let mut entities = Vec::new();
        for _ in 0..1000 {
            entities.push(world.spawn());
        }
        assert_eq!(world.entity_count(), 1000);

        // Despawn odd-indexed
        for i in (1..1000).step_by(2) {
            world.despawn(entities[i]).unwrap();
        }
        assert_eq!(world.entity_count(), 500);

        // Respawn into recycled slots
        for _ in 0..500 {
            let e = world.spawn();
            assert_eq!(e.generation(), 1); // recycled
        }
        assert_eq!(world.entity_count(), 1000);
    }

    #[test]
    fn has_component() {
        let mut world = World::new();
        let e = world.spawn();
        assert!(!world.has_component::<Health>(e));
        world.insert_component(e, Health(42)).unwrap();
        assert!(world.has_component::<Health>(e));
        world.remove_component::<Health>(e);
        assert!(!world.has_component::<Health>(e));
    }

    #[test]
    fn resource_replacement() {
        let mut world = World::new();
        world.insert_resource(Gravity(9.81));
        assert_eq!(world.get_resource::<Gravity>().unwrap().0, 9.81);

        world.insert_resource(Gravity(1.625));
        assert_eq!(world.get_resource::<Gravity>().unwrap().0, 1.625);
    }

    #[test]
    fn clock_spike_frame() {
        let mut clock = GameClock::with_timestep(1.0 / 60.0);
        clock.tick(0.5); // 500ms spike — 30 fixed steps pending
        assert_eq!(clock.pending_fixed_steps(), 30);
        let mut count = 0;
        while clock.consume_fixed() {
            count += 1;
        }
        assert_eq!(count, 30);
    }

    #[test]
    fn clock_zero_dt() {
        let mut clock = GameClock::default();
        clock.tick(0.0);
        assert_eq!(clock.frame, 1);
        assert_eq!(clock.delta, 0.0);
        assert!(!clock.consume_fixed());
    }

    #[test]
    fn event_bus_publish_after_drain() {
        let mut bus = EventBus::new();
        bus.publish(ScoreChanged(1));
        let _ = bus.drain::<ScoreChanged>();
        assert_eq!(bus.count::<ScoreChanged>(), 0);

        bus.publish(ScoreChanged(2));
        assert_eq!(bus.count::<ScoreChanged>(), 1);
        let events = bus.drain::<ScoreChanged>();
        assert_eq!(events[0].0, 2);
    }

    #[test]
    fn entity_boundary_values() {
        let e = Entity::new(u32::MAX, u32::MAX);
        assert_eq!(e.index(), u32::MAX);
        assert_eq!(e.generation(), u32::MAX);

        let e_zero = Entity::new(0, 0);
        assert_eq!(e_zero.id(), 0);
    }

    #[test]
    fn world_component_overwrite() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(100)).unwrap();
        world.insert_component(e, Health(200)).unwrap();
        assert_eq!(world.get_component::<Health>(e).unwrap().0, 200);
    }

    #[test]
    fn alive_count_consistency() {
        let mut alloc = EntityAllocator::default();
        assert_eq!(alloc.alive_count(), 0);

        let e0 = alloc.spawn();
        let e1 = alloc.spawn();
        let e2 = alloc.spawn();
        assert_eq!(alloc.alive_count(), 3);

        alloc.despawn(e1).unwrap();
        assert_eq!(alloc.alive_count(), 2);

        alloc.despawn(e0).unwrap();
        alloc.despawn(e2).unwrap();
        assert_eq!(alloc.alive_count(), 0);

        // Respawn and verify
        let _ = alloc.spawn();
        assert_eq!(alloc.alive_count(), 1);
    }

    // -- System / Scheduler tests --

    #[test]
    fn scheduler_runs_in_stage_order() {
        use std::sync::{Arc, Mutex};

        let log: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));

        let log1 = log.clone();
        let log2 = log.clone();
        let log3 = log.clone();

        let mut scheduler = Scheduler::new();

        // Add in reverse order to verify sorting
        scheduler.add_system(Box::new(FnSystem::new(
            "render",
            SystemStage::Render,
            move |_| {
                log3.lock().unwrap().push("render");
            },
        )));
        scheduler.add_system(Box::new(FnSystem::new(
            "input",
            SystemStage::Input,
            move |_| {
                log1.lock().unwrap().push("input");
            },
        )));
        scheduler.add_system(Box::new(FnSystem::new(
            "logic",
            SystemStage::GameLogic,
            move |_| {
                log2.lock().unwrap().push("logic");
            },
        )));

        let mut world = World::new();
        scheduler.run(&mut world);

        let order = log.lock().unwrap();
        assert_eq!(*order, vec!["input", "logic", "render"]);
    }

    #[test]
    fn scheduler_system_names() {
        let mut scheduler = Scheduler::new();
        scheduler.add_system(Box::new(FnSystem::new(
            "physics",
            SystemStage::Physics,
            |_| {},
        )));
        scheduler.add_system(Box::new(FnSystem::new("input", SystemStage::Input, |_| {})));

        let names = scheduler.system_names();
        assert_eq!(names, vec!["input", "physics"]);
    }

    #[test]
    fn scheduler_system_modifies_world() {
        let mut scheduler = Scheduler::new();
        scheduler.add_system(Box::new(FnSystem::new(
            "spawner",
            SystemStage::GameLogic,
            |world: &mut World| {
                world.spawn();
            },
        )));

        let mut world = World::new();
        assert_eq!(world.entity_count(), 0);
        scheduler.run(&mut world);
        assert_eq!(world.entity_count(), 1);
        scheduler.run(&mut world);
        assert_eq!(world.entity_count(), 2);
    }

    #[test]
    fn system_stage_ordering() {
        assert!(SystemStage::Input < SystemStage::Physics);
        assert!(SystemStage::Physics < SystemStage::GameLogic);
        assert!(SystemStage::GameLogic < SystemStage::Render);
    }

    #[test]
    fn fn_system_basics() {
        let sys = FnSystem::new("test_sys", SystemStage::Input, |_: &mut World| {});
        assert_eq!(sys.name(), "test_sys");
        assert_eq!(sys.stage(), SystemStage::Input);
    }

    #[test]
    fn scheduler_all_four_stages() {
        use std::sync::{Arc, Mutex};

        let log: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
        let (l1, l2, l3, l4) = (log.clone(), log.clone(), log.clone(), log.clone());

        let mut scheduler = Scheduler::new();
        scheduler.add_system(Box::new(FnSystem::new(
            "render",
            SystemStage::Render,
            move |_| {
                l4.lock().unwrap().push("render");
            },
        )));
        scheduler.add_system(Box::new(FnSystem::new(
            "physics",
            SystemStage::Physics,
            move |_| {
                l2.lock().unwrap().push("physics");
            },
        )));
        scheduler.add_system(Box::new(FnSystem::new(
            "input",
            SystemStage::Input,
            move |_| {
                l1.lock().unwrap().push("input");
            },
        )));
        scheduler.add_system(Box::new(FnSystem::new(
            "logic",
            SystemStage::GameLogic,
            move |_| {
                l3.lock().unwrap().push("logic");
            },
        )));

        let mut world = World::new();
        scheduler.run(&mut world);

        let order = log.lock().unwrap();
        assert_eq!(*order, vec!["input", "physics", "logic", "render"]);
    }

    #[test]
    fn scheduler_empty() {
        let mut scheduler = Scheduler::new();
        let mut world = World::new();
        scheduler.run(&mut world); // should not panic
        assert_eq!(scheduler.system_count(), 0);
    }

    #[test]
    fn scheduler_multiple_runs() {
        use std::sync::{Arc, Mutex};

        let count: Arc<Mutex<u32>> = Arc::new(Mutex::new(0));
        let c = count.clone();

        let mut scheduler = Scheduler::new();
        scheduler.add_system(Box::new(FnSystem::new(
            "counter",
            SystemStage::GameLogic,
            move |_| {
                *c.lock().unwrap() += 1;
            },
        )));

        let mut world = World::new();
        for _ in 0..5 {
            scheduler.run(&mut world);
        }
        assert_eq!(*count.lock().unwrap(), 5);
    }

    #[test]
    fn scheduler_after_ordering() {
        use std::sync::{Arc, Mutex};
        let order: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));

        struct OrderedSystem {
            name: String,
            after_deps: Vec<&'static str>,
            order: Arc<Mutex<Vec<String>>>,
        }

        impl System for OrderedSystem {
            fn run(&mut self, _world: &mut World) {
                self.order.lock().unwrap().push(self.name.clone());
            }
            fn stage(&self) -> SystemStage {
                SystemStage::GameLogic
            }
            fn name(&self) -> &str {
                &self.name
            }
            fn after(&self) -> &[&str] {
                &self.after_deps
            }
        }

        let mut scheduler = Scheduler::new();
        // B runs after A
        scheduler.add_system(Box::new(OrderedSystem {
            name: "B".into(),
            after_deps: vec!["A"],
            order: order.clone(),
        }));
        scheduler.add_system(Box::new(OrderedSystem {
            name: "A".into(),
            after_deps: vec![],
            order: order.clone(),
        }));

        let mut world = World::new();
        scheduler.run(&mut world);

        let result = order.lock().unwrap();
        assert_eq!(result[0], "A");
        assert_eq!(result[1], "B");
    }

    #[test]
    fn scheduler_before_ordering() {
        use std::sync::{Arc, Mutex};
        let order: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));

        struct BeforeSystem {
            name: String,
            before_deps: Vec<&'static str>,
            order: Arc<Mutex<Vec<String>>>,
        }

        impl System for BeforeSystem {
            fn run(&mut self, _world: &mut World) {
                self.order.lock().unwrap().push(self.name.clone());
            }
            fn stage(&self) -> SystemStage {
                SystemStage::GameLogic
            }
            fn name(&self) -> &str {
                &self.name
            }
            fn before(&self) -> &[&str] {
                &self.before_deps
            }
        }

        let mut scheduler = Scheduler::new();
        // A runs before B (added in reverse)
        scheduler.add_system(Box::new(BeforeSystem {
            name: "B".into(),
            before_deps: vec![],
            order: order.clone(),
        }));
        scheduler.add_system(Box::new(BeforeSystem {
            name: "A".into(),
            before_deps: vec!["B"],
            order: order.clone(),
        }));

        let mut world = World::new();
        scheduler.run(&mut world);

        let result = order.lock().unwrap();
        assert_eq!(result[0], "A");
        assert_eq!(result[1], "B");
    }

    #[test]
    fn scheduler_chain_ordering() {
        use std::sync::{Arc, Mutex};
        let order: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));

        struct ChainSys {
            name: String,
            after_deps: Vec<&'static str>,
            order: Arc<Mutex<Vec<String>>>,
        }

        impl System for ChainSys {
            fn run(&mut self, _world: &mut World) {
                self.order.lock().unwrap().push(self.name.clone());
            }
            fn stage(&self) -> SystemStage {
                SystemStage::GameLogic
            }
            fn name(&self) -> &str {
                &self.name
            }
            fn after(&self) -> &[&str] {
                &self.after_deps
            }
        }

        let mut scheduler = Scheduler::new();
        // C after B, B after A (added out of order)
        scheduler.add_system(Box::new(ChainSys {
            name: "C".into(),
            after_deps: vec!["B"],
            order: order.clone(),
        }));
        scheduler.add_system(Box::new(ChainSys {
            name: "A".into(),
            after_deps: vec![],
            order: order.clone(),
        }));
        scheduler.add_system(Box::new(ChainSys {
            name: "B".into(),
            after_deps: vec!["A"],
            order: order.clone(),
        }));

        let mut world = World::new();
        scheduler.run(&mut world);

        let result = order.lock().unwrap();
        assert_eq!(*result, vec!["A", "B", "C"]);
    }

    #[test]
    fn scheduler_cross_stage_independence() {
        // Ordering constraints only apply within the same stage
        let mut scheduler = Scheduler::new();
        scheduler.add_system(Box::new(FnSystem::new(
            "input_sys",
            SystemStage::Input,
            |_: &mut World| {},
        )));
        scheduler.add_system(Box::new(FnSystem::new(
            "render_sys",
            SystemStage::Render,
            |_: &mut World| {},
        )));

        let names = scheduler.system_names();
        assert_eq!(names[0], "input_sys");
        assert_eq!(names[1], "render_sys");
    }

    #[test]
    fn entity_from_id_roundtrip() {
        let e = Entity::new(42, 7);
        let id = e.id();
        let reconstructed = Entity::from_id(id);
        assert_eq!(e, reconstructed);
        assert_eq!(reconstructed.index(), 42);
        assert_eq!(reconstructed.generation(), 7);
    }

    #[test]
    fn get_component_mut_dead_entity() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(100)).unwrap();
        world.despawn(e).unwrap();
        assert!(world.get_component_mut::<Health>(e).is_none());
    }

    #[test]
    fn resource_get_wrong_type() {
        let mut world = World::new();
        world.insert_resource(Gravity(9.81));
        assert!(world.get_resource::<Health>().is_none());
    }

    #[test]
    fn world_is_alive() {
        let mut world = World::new();
        let e = world.spawn();
        assert!(world.is_alive(e));
        world.despawn(e).unwrap();
        assert!(!world.is_alive(e));
    }

    #[test]
    fn remove_component_returns_none_if_missing() {
        let mut world = World::new();
        let e = world.spawn();
        assert!(world.remove_component::<Health>(e).is_none());
    }

    #[test]
    fn event_bus_large_batch() {
        let mut bus = EventBus::new();
        for i in 0..10000 {
            bus.publish(ScoreChanged(i));
        }
        assert_eq!(bus.count::<ScoreChanged>(), 10000);
        let events = bus.drain::<ScoreChanged>();
        assert_eq!(events.len(), 10000);
    }

    // -- Change detection tests --

    #[test]
    fn resource_change_detection_basic() {
        let mut world = World::new();
        world.insert_resource(Gravity(9.81));

        // Just inserted — changed
        assert!(world.is_resource_changed::<Gravity>());

        // Clear — no longer changed
        world.clear_resource_changed::<Gravity>();
        assert!(!world.is_resource_changed::<Gravity>());
    }

    #[test]
    fn resource_change_on_mut_access() {
        let mut world = World::new();
        world.insert_resource(Gravity(9.81));
        world.clear_resource_changed::<Gravity>();

        // Mutable access marks changed
        world.increment_tick();
        let g = world.get_resource_mut::<Gravity>().unwrap();
        g.0 = 1.625;

        assert!(world.is_resource_changed::<Gravity>());
    }

    #[test]
    fn resource_change_read_only_no_change() {
        let mut world = World::new();
        world.insert_resource(Gravity(9.81));
        world.clear_resource_changed::<Gravity>();

        // Read-only access does NOT mark changed
        world.increment_tick();
        let _ = world.get_resource::<Gravity>();

        assert!(!world.is_resource_changed::<Gravity>());
    }

    #[test]
    fn resource_change_multi_tick() {
        let mut world = World::new();
        world.insert_resource(Gravity(9.81));

        // Tick 0: inserted
        world.clear_resource_changed::<Gravity>();

        // Tick 1: no mutation → not changed
        world.increment_tick();
        assert!(!world.is_resource_changed::<Gravity>());

        // Tick 2: mutate → changed
        world.increment_tick();
        world.get_resource_mut::<Gravity>().unwrap().0 = 0.0;
        assert!(world.is_resource_changed::<Gravity>());

        // Clear and tick 3: not changed
        world.clear_resource_changed::<Gravity>();
        world.increment_tick();
        assert!(!world.is_resource_changed::<Gravity>());
    }

    #[test]
    fn resource_change_untracked_type() {
        let world = World::new();
        // Never inserted → not changed
        assert!(!world.is_resource_changed::<Gravity>());
    }

    #[test]
    fn world_tick() {
        let mut world = World::new();
        assert_eq!(world.tick(), 0);
        world.increment_tick();
        assert_eq!(world.tick(), 1);
        world.increment_tick();
        assert_eq!(world.tick(), 2);
    }

    // -- Query tests --

    #[test]
    fn query_single_component() {
        let mut world = World::new();
        let e1 = world.spawn();
        let e2 = world.spawn();
        let _e3 = world.spawn();
        world.insert_component(e1, Health(100)).unwrap();
        world.insert_component(e2, Health(50)).unwrap();
        // e3 has no Health

        let results = world.query::<Health>();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].1.0, 100);
        assert_eq!(results[1].1.0, 50);
    }

    #[test]
    fn query_two_components() {
        let mut world = World::new();
        let e1 = world.spawn();
        let e2 = world.spawn();
        world.insert_component(e1, Health(100)).unwrap();
        world
            .insert_component(e1, Velocity { x: 1.0, y: 2.0 })
            .unwrap();
        world.insert_component(e2, Health(50)).unwrap();
        // e2 has no Velocity

        let results = world.query2::<Health, Velocity>();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].1.0, 100);
        assert_eq!(results[0].2.x, 1.0);
    }

    #[test]
    fn query_empty_world() {
        let world = World::new();
        let results = world.query::<Health>();
        assert!(results.is_empty());
    }

    #[test]
    fn query_no_matches() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(100)).unwrap();

        let results = world.query::<Velocity>();
        assert!(results.is_empty());
    }

    #[test]
    fn query_excludes_despawned() {
        let mut world = World::new();
        let e1 = world.spawn();
        let e2 = world.spawn();
        world.insert_component(e1, Health(100)).unwrap();
        world.insert_component(e2, Health(50)).unwrap();
        world.despawn(e1).unwrap();

        let results = world.query::<Health>();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].1.0, 50);
    }

    #[test]
    fn query_1000_entities() {
        let mut world = World::new();
        for i in 0..1000 {
            let e = world.spawn();
            world.insert_component(e, Health(i)).unwrap();
        }
        let results = world.query::<Health>();
        assert_eq!(results.len(), 1000);
    }

    // -- Commands tests --

    #[test]
    fn commands_spawn() {
        let mut world = World::new();
        let mut cmds = Commands::new();
        cmds.spawn()
            .with(Health(100))
            .with(Velocity { x: 1.0, y: 2.0 });
        cmds.spawn().with(Health(50));

        assert_eq!(cmds.len(), 2);
        cmds.apply(&mut world);

        assert_eq!(world.entity_count(), 2);
        let results = world.query::<Health>();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn commands_despawn() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(100)).unwrap();

        let mut cmds = Commands::new();
        cmds.despawn(e);
        cmds.apply(&mut world);

        assert_eq!(world.entity_count(), 0);
    }

    #[test]
    fn commands_insert_component() {
        let mut world = World::new();
        let e = world.spawn();

        let mut cmds = Commands::new();
        cmds.insert(e, Health(42));
        cmds.apply(&mut world);

        assert_eq!(world.get_component::<Health>(e).unwrap().0, 42);
    }

    #[test]
    fn commands_remove_component() {
        let mut world = World::new();
        let e = world.spawn();
        world.insert_component(e, Health(100)).unwrap();

        let mut cmds = Commands::new();
        cmds.remove::<Health>(e);
        cmds.apply(&mut world);

        assert!(!world.has_component::<Health>(e));
    }

    #[test]
    fn commands_empty() {
        let cmds = Commands::new();
        assert!(cmds.is_empty());
        assert_eq!(cmds.len(), 0);
    }

    #[test]
    fn commands_mixed() {
        let mut world = World::new();
        let e1 = world.spawn();
        world.insert_component(e1, Health(100)).unwrap();

        let mut cmds = Commands::new();
        cmds.spawn().with(Health(50));
        cmds.despawn(e1);
        cmds.apply(&mut world);

        assert_eq!(world.entity_count(), 1);
    }

    // -- ChangeTracker tests --

    #[test]
    fn change_tracker_basic() {
        let mut tracker = ChangeTracker::new();
        let e = Entity::new(0, 0);

        tracker.mark_changed::<Health>(e, 5);
        assert!(tracker.is_changed::<Health>(e, 4));
        assert!(!tracker.is_changed::<Health>(e, 5));
        assert!(!tracker.is_changed::<Health>(e, 6));
    }

    #[test]
    fn change_tracker_added() {
        let mut tracker = ChangeTracker::new();
        let e = Entity::new(0, 0);

        tracker.mark_added::<Health>(e, 3);
        assert!(tracker.is_added::<Health>(e, 2));
        assert!(!tracker.is_added::<Health>(e, 3));
    }

    #[test]
    fn change_tracker_clear_entity() {
        let mut tracker = ChangeTracker::new();
        let e = Entity::new(0, 0);

        tracker.mark_changed::<Health>(e, 5);
        tracker.mark_added::<Health>(e, 5);
        tracker.clear_entity(e);

        assert!(!tracker.is_changed::<Health>(e, 0));
        assert!(!tracker.is_added::<Health>(e, 0));
    }

    #[test]
    fn change_tracker_different_types() {
        let mut tracker = ChangeTracker::new();
        let e = Entity::new(0, 0);

        tracker.mark_changed::<Health>(e, 5);
        assert!(tracker.is_changed::<Health>(e, 4));
        assert!(!tracker.is_changed::<Velocity>(e, 4));
    }

    // -- Bundle tests --

    #[test]
    fn bundle_insert() {
        let mut world = World::new();
        let e = world.spawn();
        Bundle::new()
            .with(Health(100))
            .with(Velocity { x: 1.0, y: 2.0 })
            .apply(&mut world, e)
            .unwrap();

        assert_eq!(world.get_component::<Health>(e).unwrap().0, 100);
        assert_eq!(world.get_component::<Velocity>(e).unwrap().x, 1.0);
    }

    #[test]
    fn bundle_dead_entity() {
        let mut world = World::new();
        let e = world.spawn();
        world.despawn(e).unwrap();
        let result = Bundle::new().with(Health(1)).apply(&mut world, e);
        assert!(result.is_err());
    }

    #[test]
    fn bundle_empty() {
        let mut world = World::new();
        let e = world.spawn();
        Bundle::new().apply(&mut world, e).unwrap();
    }
}