elizacp 12.0.0

Classic Eliza chatbot as an ACP agent for testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
//! ELIZA chatbot implementation based on Weizenbaum's 1966 algorithm.
//!
//! This module implements the classic ELIZA pattern-matching algorithm
//! as described in the January 1966 CACM paper, with a modernized script
//! format (TOML instead of S-expressions) and normal case text.

use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use serde::Deserialize;
use std::collections::HashMap;

// =============================================================================
// Data Structures
// =============================================================================

/// A decomposition pattern element
#[derive(Debug, Clone)]
enum PatternElement {
    /// Match this exact word (case-insensitive)
    Exact(String),
    /// Match exactly N words
    Count(usize),
    /// Match N to M words (inclusive)
    Range(usize, usize),
    /// Match 0 or more words (wildcard)
    Wildcard,
    /// Match any of these words
    AnyOf(Vec<String>),
    /// Match any word with this tag
    Tag(String),
}

/// A reassembly rule element
#[derive(Debug, Clone)]
enum ReassemblyElement {
    /// Literal text
    Text(String),
    /// Reference to matched component (1-indexed), no reflection
    ComponentRef(usize),
    /// Reference to matched component (1-indexed), with pronoun reflection
    ComponentRefReflect(usize),
}

/// Special reassembly actions
#[derive(Debug, Clone)]
enum ReassemblyAction {
    /// Normal reassembly with elements
    Reassemble(Vec<ReassemblyElement>),
    /// Jump to another keyword
    Goto(String),
    /// Try next keyword in stack
    Newkey,
}

/// A decomposition/reassembly pair
#[derive(Debug, Clone)]
struct Transform {
    decomposition: Vec<PatternElement>,
    reassembly_rules: Vec<ReassemblyAction>,
}

/// A keyword rule
#[derive(Debug, Clone)]
struct Keyword {
    /// Fix typos/contractions - applied during tokenization (e.g., "dont" -> "don't")
    repair: Option<String>,
    /// Priority for keyword selection (higher = more important)
    precedence: u32,
    /// Direct link to another keyword (equivalence class)
    link: Option<String>,
    /// Transformation rules
    transforms: Vec<Transform>,
}

/// Memory rule for storing and recalling statements
#[derive(Debug, Clone)]
struct MemoryRule {
    /// The keyword that triggers memory creation (usually "my")
    keyword: String,
    /// Exactly 4 transforms for memory creation
    transforms: Vec<Transform>,
}

/// Pronoun reflections (I -> you, my -> your, etc.)
#[derive(Debug, Clone)]
struct Reflections {
    map: HashMap<String, String>,
}

/// The complete ELIZA script (immutable after loading)
#[derive(Debug, Clone)]
struct Script {
    hello_message: String,
    keywords: HashMap<String, Keyword>,
    memory_rule: Option<MemoryRule>,
    /// Maps tag names to words that have that tag
    tags: HashMap<String, Vec<String>>,
    reflections: Reflections,
}

/// Mutable runtime state for ELIZA
#[derive(Debug, Clone)]
struct State {
    /// LIMIT counter (1-4, affects memory recall)
    limit: u8,
    /// Cycling state for reassembly rules: (keyword, transform_index) -> next_rule
    rule_indices: HashMap<(String, usize), usize>,
    /// Queue of stored memories for later recall
    memories: Vec<String>,
}

// =============================================================================
// TOML Schema
// =============================================================================

#[derive(Debug, Deserialize)]
struct TomlScript {
    hello: String,
    #[serde(default)]
    keywords: Vec<TomlKeyword>,
    memory: Option<TomlMemory>,
}

#[derive(Debug, Deserialize)]
struct TomlKeyword {
    word: String,
    /// Fix typos/contractions - applied during tokenization (e.g., "dont" -> "don't")
    #[serde(default)]
    repair: Option<String>,
    /// Pronoun reflection - only used during reassembly with {N:r} (e.g., "you" -> "i")
    #[serde(default)]
    reflection: Option<String>,
    #[serde(default)]
    precedence: u32,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(default)]
    link: Option<String>,
    #[serde(default)]
    transforms: Vec<TomlTransform>,
}

#[derive(Debug, Deserialize)]
struct TomlTransform {
    decomposition: Vec<String>,
    #[serde(default)]
    reassembly: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct TomlMemory {
    keyword: String,
    transforms: Vec<TomlMemoryTransform>,
}

#[derive(Debug, Deserialize)]
struct TomlMemoryTransform {
    decomposition: Vec<String>,
    reassembly: String,
}

// =============================================================================
// Parsing
// =============================================================================

impl PatternElement {
    fn parse(s: &str) -> Self {
        let s = s.trim();

        // Wildcard: ".."
        if s == ".." {
            return PatternElement::Wildcard;
        }

        // Range: "1..3"
        if let Some((left, right)) = s.split_once("..") {
            if let (Ok(n), Ok(m)) = (left.parse::<usize>(), right.parse::<usize>()) {
                return PatternElement::Range(n, m);
            }
        }

        // Exact count: "2"
        if let Ok(n) = s.parse::<usize>() {
            return PatternElement::Count(n);
        }

        // Tag: "#FAMILY"
        if let Some(tag) = s.strip_prefix('#') {
            return PatternElement::Tag(tag.to_lowercase());
        }

        // AnyOf: "{WANT, NEED}"
        if s.starts_with('{') && s.ends_with('}') {
            let inner = &s[1..s.len() - 1];
            let words: Vec<String> = inner
                .split(',')
                .map(|w| w.trim().to_lowercase())
                .filter(|w| !w.is_empty())
                .collect();
            return PatternElement::AnyOf(words);
        }

        // Exact word match
        PatternElement::Exact(s.to_lowercase())
    }
}

impl ReassemblyAction {
    fn parse(s: &str) -> Self {
        let s = s.trim();

        // Goto: "=WHAT"
        if let Some(target) = s.strip_prefix('=') {
            return ReassemblyAction::Goto(target.to_lowercase());
        }

        // Newkey
        if s.eq_ignore_ascii_case("NEWKEY") {
            return ReassemblyAction::Newkey;
        }

        // Normal reassembly - parse for {N} references
        let mut elements = Vec::new();
        let mut current_text = String::new();
        let mut chars = s.chars().peekable();

        while let Some(c) = chars.next() {
            if c == '{' {
                // Might be a component reference: {N} or {N:r}
                let mut num_str = String::new();
                let mut reflect = false;

                while let Some(&next) = chars.peek() {
                    if next == '}' {
                        chars.next();
                        break;
                    }
                    if next.is_ascii_digit() {
                        num_str.push(chars.next().unwrap());
                    } else if next == ':' && !num_str.is_empty() {
                        // Check for :r suffix
                        chars.next(); // consume ':'
                        if chars.peek() == Some(&'r') {
                            chars.next(); // consume 'r'
                            reflect = true;
                        }
                    } else {
                        // Not a valid reference, treat as literal
                        current_text.push('{');
                        current_text.push_str(&num_str);
                        num_str.clear();
                        break;
                    }
                }
                if !num_str.is_empty() {
                    if let Ok(n) = num_str.parse::<usize>() {
                        if !current_text.is_empty() {
                            elements.push(ReassemblyElement::Text(current_text.clone()));
                            current_text.clear();
                        }
                        if reflect {
                            elements.push(ReassemblyElement::ComponentRefReflect(n));
                        } else {
                            elements.push(ReassemblyElement::ComponentRef(n));
                        }
                        continue;
                    }
                }
            } else {
                current_text.push(c);
            }
        }
        if !current_text.is_empty() {
            elements.push(ReassemblyElement::Text(current_text));
        }

        ReassemblyAction::Reassemble(elements)
    }
}

impl Script {
    fn from_toml(toml_str: &str) -> Result<Self, toml::de::Error> {
        let toml_script: TomlScript = toml::from_str(toml_str)?;

        let mut keywords = HashMap::new();
        let mut tags: HashMap<String, Vec<String>> = HashMap::new();
        let mut reflections_from_script: HashMap<String, String> = HashMap::new();

        for tk in toml_script.keywords {
            let word = tk.word.to_lowercase();

            // Collect tags
            for tag in &tk.tags {
                tags.entry(tag.to_lowercase())
                    .or_default()
                    .push(word.clone());
            }

            let transforms: Vec<Transform> = tk
                .transforms
                .into_iter()
                .map(|t| Transform {
                    decomposition: t
                        .decomposition
                        .iter()
                        .map(|s| PatternElement::parse(s))
                        .collect(),
                    reassembly_rules: t
                        .reassembly
                        .iter()
                        .map(|s| ReassemblyAction::parse(s))
                        .collect(),
                })
                .collect();

            let keyword = Keyword {
                repair: tk.repair.map(|s| s.to_lowercase()),
                precedence: tk.precedence,
                link: tk.link.map(|s| s.to_lowercase()),
                transforms,
            };

            // Build reflection map from keywords that have reflection defined
            if let Some(ref reflection) = tk.reflection {
                reflections_from_script.insert(word.clone(), reflection.to_lowercase());
            }

            keywords.insert(word, keyword);
        }

        let memory_rule = toml_script.memory.map(|m| {
            let transforms = m
                .transforms
                .into_iter()
                .map(|t| Transform {
                    decomposition: t
                        .decomposition
                        .iter()
                        .map(|s| PatternElement::parse(s))
                        .collect(),
                    reassembly_rules: vec![ReassemblyAction::parse(&t.reassembly)],
                })
                .collect();
            MemoryRule {
                keyword: m.keyword.to_lowercase(),
                transforms,
            }
        });

        // Merge script reflections with defaults (script takes precedence)
        let mut reflections = Reflections::default();
        for (word, reflection) in reflections_from_script {
            reflections.map.insert(word, reflection);
        }

        Ok(Script {
            hello_message: toml_script.hello,
            keywords,
            memory_rule,
            tags,
            reflections,
        })
    }
}

impl Default for Reflections {
    fn default() -> Self {
        let mut map = HashMap::new();

        // First person -> second person
        map.insert("i".to_string(), "you".to_string());
        map.insert("i'm".to_string(), "you're".to_string());
        map.insert("i've".to_string(), "you've".to_string());
        map.insert("i'll".to_string(), "you'll".to_string());
        map.insert("i'd".to_string(), "you'd".to_string());
        map.insert("me".to_string(), "you".to_string());
        map.insert("my".to_string(), "your".to_string());
        map.insert("mine".to_string(), "yours".to_string());
        map.insert("myself".to_string(), "yourself".to_string());
        map.insert("am".to_string(), "are".to_string());
        map.insert("we".to_string(), "you".to_string());
        map.insert("our".to_string(), "your".to_string());
        map.insert("ours".to_string(), "yours".to_string());
        map.insert("ourselves".to_string(), "yourselves".to_string());
        map.insert("was".to_string(), "were".to_string());

        // Second person -> first person
        map.insert("you".to_string(), "I".to_string());
        map.insert("you're".to_string(), "I'm".to_string());
        map.insert("you've".to_string(), "I've".to_string());
        map.insert("you'll".to_string(), "I'll".to_string());
        map.insert("you'd".to_string(), "I'd".to_string());
        map.insert("your".to_string(), "my".to_string());
        map.insert("yours".to_string(), "mine".to_string());
        map.insert("yourself".to_string(), "myself".to_string());

        Self { map }
    }
}

impl Reflections {
    fn reflect(&self, text: &str) -> String {
        text.split_whitespace()
            .map(|word| {
                let lower = word.to_lowercase();
                // Strip punctuation for lookup
                let (base, punct) = if lower.ends_with(|c: char| c.is_ascii_punctuation()) {
                    let punct = &lower[lower.len() - 1..];
                    (&lower[..lower.len() - 1], punct)
                } else {
                    (lower.as_str(), "")
                };

                if let Some(reflected) = self.map.get(base) {
                    format!("{}{}", reflected, punct)
                } else {
                    word.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join(" ")
    }
}

// =============================================================================
// Core Algorithm
// =============================================================================

/// Result of attempting a transformation
enum TransformResult {
    /// Successfully generated a response
    Complete(String),
    /// Follow a link to another keyword
    Goto(String, Vec<String>),
    /// Try the next keyword
    Newkey,
    /// No decomposition matched
    NoMatch,
}

impl Script {
    /// Try to match a decomposition pattern against words
    fn match_pattern(&self, pattern: &[PatternElement], words: &[String]) -> Option<Vec<String>> {
        self.match_pattern_recursive(pattern, words, Vec::new())
    }

    fn match_pattern_recursive(
        &self,
        pattern: &[PatternElement],
        words: &[String],
        mut components: Vec<String>,
    ) -> Option<Vec<String>> {
        if pattern.is_empty() {
            return if words.is_empty() {
                Some(components)
            } else {
                None
            };
        }

        let elem = &pattern[0];
        let rest_pattern = &pattern[1..];

        match elem {
            PatternElement::Exact(expected) => {
                if words.is_empty() || words[0].to_lowercase() != *expected {
                    return None;
                }
                components.push(words[0].clone());
                self.match_pattern_recursive(rest_pattern, &words[1..], components)
            }

            PatternElement::Count(n) => {
                if words.len() < *n {
                    return None;
                }
                components.push(words[..*n].join(" "));
                self.match_pattern_recursive(rest_pattern, &words[*n..], components)
            }

            PatternElement::Range(min, max) => {
                for n in (*min..=*max).rev() {
                    if words.len() >= n {
                        let mut new_components = components.clone();
                        new_components.push(words[..n].join(" "));
                        if let Some(result) =
                            self.match_pattern_recursive(rest_pattern, &words[n..], new_components)
                        {
                            return Some(result);
                        }
                    }
                }
                None
            }

            PatternElement::Wildcard => {
                for n in 0..=words.len() {
                    let mut new_components = components.clone();
                    new_components.push(words[..n].join(" "));
                    if let Some(result) =
                        self.match_pattern_recursive(rest_pattern, &words[n..], new_components)
                    {
                        return Some(result);
                    }
                }
                None
            }

            PatternElement::AnyOf(options) => {
                if words.is_empty() {
                    return None;
                }
                let word_lower = words[0].to_lowercase();
                if !options.contains(&word_lower) {
                    return None;
                }
                components.push(words[0].clone());
                self.match_pattern_recursive(rest_pattern, &words[1..], components)
            }

            PatternElement::Tag(tag) => {
                if words.is_empty() {
                    return None;
                }
                let word_lower = words[0].to_lowercase();
                if !self
                    .tags
                    .get(tag)
                    .map_or(false, |tw| tw.contains(&word_lower))
                {
                    return None;
                }
                components.push(words[0].clone());
                self.match_pattern_recursive(rest_pattern, &words[1..], components)
            }
        }
    }

    /// Reassemble a response from a rule and matched components
    fn reassemble(&self, elements: &[ReassemblyElement], components: &[String]) -> String {
        let mut result = String::new();
        for elem in elements {
            match elem {
                ReassemblyElement::Text(text) => {
                    result.push_str(text);
                }
                ReassemblyElement::ComponentRef(n) => {
                    if *n > 0 && *n <= components.len() {
                        result.push_str(&components[*n - 1]);
                    }
                }
                ReassemblyElement::ComponentRefReflect(n) => {
                    if *n > 0 && *n <= components.len() {
                        let reflected = self.reflections.reflect(&components[*n - 1]);
                        result.push_str(&reflected);
                    }
                }
            }
        }
        result
    }

    /// Apply transformation for a keyword
    fn apply_transform(
        &self,
        state: &mut State,
        keyword_name: &str,
        words: &[String],
    ) -> TransformResult {
        let keyword = match self.keywords.get(keyword_name) {
            Some(k) => k,
            None => return TransformResult::NoMatch,
        };

        // If keyword has a direct link and no transforms, follow it
        if keyword.transforms.is_empty() {
            if let Some(ref link) = keyword.link {
                return TransformResult::Goto(link.clone(), words.to_vec());
            }
            return TransformResult::NoMatch;
        }

        // Try each transform's decomposition
        for (transform_idx, transform) in keyword.transforms.iter().enumerate() {
            if let Some(components) = self.match_pattern(&transform.decomposition, words) {
                if transform.reassembly_rules.is_empty() {
                    // No reassembly rules - check for link
                    if let Some(ref link) = keyword.link {
                        return TransformResult::Goto(link.clone(), words.to_vec());
                    }
                    continue;
                }

                // Get next reassembly rule (cycling)
                let state_key = (keyword_name.to_string(), transform_idx);
                let rule_idx = *state.rule_indices.get(&state_key).unwrap_or(&0);
                let next_idx = (rule_idx + 1) % transform.reassembly_rules.len();
                state.rule_indices.insert(state_key, next_idx);

                match &transform.reassembly_rules[rule_idx] {
                    ReassemblyAction::Reassemble(elements) => {
                        let response = self.reassemble(elements, &components);
                        return TransformResult::Complete(response);
                    }
                    ReassemblyAction::Goto(target) => {
                        return TransformResult::Goto(target.clone(), words.to_vec());
                    }
                    ReassemblyAction::Newkey => {
                        return TransformResult::Newkey;
                    }
                }
            }
        }

        // No decomposition matched - check for link
        if let Some(ref link) = keyword.link {
            return TransformResult::Goto(link.clone(), words.to_vec());
        }

        TransformResult::NoMatch
    }

    /// Try to create a memory from input
    fn try_create_memory(&self, state: &mut State, words: &[String]) {
        let memory_rule = match &self.memory_rule {
            Some(m) => m,
            None => return,
        };

        // Check if memory keyword is in the words
        if !words
            .iter()
            .any(|w| w.to_lowercase() == memory_rule.keyword)
        {
            return;
        }

        // Use a hash-like selection for which transform to use
        let transform_idx = if !words.is_empty() {
            let last_word = words.last().unwrap();
            let hash: usize = last_word.bytes().map(|b| b as usize).sum();
            hash % memory_rule.transforms.len().max(1)
        } else {
            0
        };

        if transform_idx >= memory_rule.transforms.len() {
            return;
        }

        let transform = &memory_rule.transforms[transform_idx];
        if let Some(components) = self.match_pattern(&transform.decomposition, words) {
            if let Some(ReassemblyAction::Reassemble(elements)) = transform.reassembly_rules.first()
            {
                let memory = self.reassemble(elements, &components);
                state.memories.push(memory);
            }
        }
    }
}

// =============================================================================
// Public API
// =============================================================================

/// The Eliza chatbot engine.
#[derive(Clone)]
pub struct Eliza {
    script: Script,
    state: State,
}

impl Eliza {
    /// Create a new Eliza instance with a random seed.
    pub fn new() -> Self {
        Self::with_seed(rand::random())
    }

    /// Create a new Eliza instance with a fixed seed for deterministic behavior.
    pub fn new_deterministic() -> Self {
        Self::with_seed(22)
    }

    /// Create a new Eliza instance with a specific seed.
    pub fn with_seed(seed: u64) -> Self {
        let script = Script::from_toml(DOCTOR_SCRIPT).expect("Failed to parse built-in script");

        // Initialize state with randomized starting positions for reassembly rule cycling
        // Sort keywords by name for deterministic iteration order
        let mut rng = StdRng::seed_from_u64(seed);
        let mut rule_indices = HashMap::new();
        let mut keyword_names: Vec<_> = script.keywords.keys().collect();
        keyword_names.sort();
        for keyword_name in keyword_names {
            let keyword = &script.keywords[keyword_name];
            for (transform_idx, transform) in keyword.transforms.iter().enumerate() {
                if !transform.reassembly_rules.is_empty() {
                    let start = rng.random_range(0..transform.reassembly_rules.len());
                    rule_indices.insert((keyword_name.clone(), transform_idx), start);
                }
            }
        }

        Self {
            script,
            state: State {
                limit: 0,
                rule_indices,
                memories: Vec::new(),
            },
        }
    }

    /// Get the hello message
    pub fn hello(&self) -> &str {
        &self.script.hello_message
    }

    /// Generate a response to user input.
    pub fn respond(&mut self, input: &str) -> String {
        let input = input.trim();
        if input.is_empty() {
            return "Please tell me more.".to_string();
        }

        // Update LIMIT counter (cycles 1-4)
        self.state.limit = (self.state.limit % 4) + 1;

        // Tokenize and normalize
        let words = self.tokenize(input);
        if words.is_empty() {
            return "Please tell me more.".to_string();
        }

        // Process the input
        self.process_input(&words)
    }

    /// Tokenize input into words
    fn tokenize(&self, input: &str) -> Vec<String> {
        input
            .split(|c: char| c.is_whitespace() || matches!(c, ',' | '.' | '?' | '!' | ';' | ':'))
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
            .collect()
    }

    /// Process input and generate response
    fn process_input(&mut self, original_words: &[String]) -> String {
        // Apply repairs and build keystack (but NOT substitutions - those happen during reassembly)
        let mut words = Vec::new();
        let mut keystack: Vec<(String, u32)> = Vec::new();

        for word in original_words {
            let word_lower = word.to_lowercase();

            if let Some(keyword) = self.script.keywords.get(&word_lower) {
                // Apply repair if any (e.g., "dont" -> "don't")
                let repaired = keyword.repair.clone().unwrap_or_else(|| word_lower.clone());
                words.push(repaired);

                // Add to keystack if it has transforms or a link
                if !keyword.transforms.is_empty() || keyword.link.is_some() {
                    keystack.push((word_lower.clone(), keyword.precedence));
                }
            } else {
                words.push(word_lower.clone());
            }
        }

        // Sort keystack by precedence (highest first)
        keystack.sort_by(|a, b| b.1.cmp(&a.1));

        // If no keywords found, check memory or use NONE
        if keystack.is_empty() {
            // Check for memory recall (LIMIT=4 and memories exist)
            if self.state.limit == 4 && !self.state.memories.is_empty() {
                return self.state.memories.remove(0); // FIFO queue
            }

            // Use NONE keyword
            return self.apply_none(&words);
        }

        // Try to create a memory if the memory keyword is present
        self.script.try_create_memory(&mut self.state, &words);

        // Process keywords in order
        let mut visited_keywords = Vec::new();
        for (keyword_name, _) in &keystack {
            if let Some(response) = self.apply_keyword(keyword_name, &words, &mut visited_keywords)
            {
                return response;
            }
        }

        // Fallback to NONE
        self.apply_none(&words)
    }

    /// Apply a keyword transformation, following links as needed
    fn apply_keyword(
        &mut self,
        keyword_name: &str,
        words: &[String],
        visited: &mut Vec<String>,
    ) -> Option<String> {
        // Prevent infinite loops
        if visited.contains(&keyword_name.to_string()) {
            return None;
        }
        visited.push(keyword_name.to_string());

        // Limit link following depth
        if visited.len() > 10 {
            return None;
        }

        match self
            .script
            .apply_transform(&mut self.state, keyword_name, words)
        {
            TransformResult::Complete(response) => Some(response),
            TransformResult::Goto(target, new_words) => {
                self.apply_keyword(&target, &new_words, visited)
            }
            TransformResult::Newkey => None,
            TransformResult::NoMatch => None,
        }
    }

    /// Apply the NONE keyword (fallback)
    fn apply_none(&mut self, words: &[String]) -> String {
        if let Some(result) = self.apply_keyword("none", words, &mut Vec::new()) {
            return result;
        }
        "I'm not sure I understand you fully.".to_string()
    }
}

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

impl std::fmt::Debug for Eliza {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Eliza")
            .field("state", &self.state)
            .finish_non_exhaustive()
    }
}

// =============================================================================
// Built-in DOCTOR Script
// =============================================================================

const DOCTOR_SCRIPT: &str = r##"
hello = "How do you do. Please tell me your problem."

# Word substitutions (applied during input processing)
[[keywords]]
word = "dont"
repair = "don't"

[[keywords]]
word = "cant"
repair = "can't"

[[keywords]]
word = "wont"
repair = "won't"

[[keywords]]
word = "dreamed"
repair = "dreamt"
link = "dreamt"

# SORRY
[[keywords]]
word = "sorry"
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Please don't apologize.",
    "Apologies are not necessary.",
    "What feelings do you have when you apologize?",
    "I've told you that apologies are not required.",
]

# REMEMBER
[[keywords]]
word = "remember"
precedence = 5
[[keywords.transforms]]
decomposition = ["..", "i", "remember", ".."]
reassembly = [
    "Do you often think of {4}?",
    "Does thinking of {4} bring anything else to mind?",
    "What else do you remember?",
    "Why do you remember {4} just now?",
    "What in the present situation reminds you of {4}?",
    "What is the connection between me and {4}?",
]
[[keywords.transforms]]
decomposition = ["..", "do", "i", "remember", ".."]
reassembly = [
    "Did you think I would forget {5}?",
    "Why do you think I should recall {5} now?",
    "What about {5}?",
    "=what",
    "You mentioned {5}.",
]
[[keywords.transforms]]
decomposition = [".."]
reassembly = ["NEWKEY"]

# IF
[[keywords]]
word = "if"
precedence = 3
[[keywords.transforms]]
decomposition = ["..", "if", ".."]
reassembly = [
    "Do you think it's likely that {3}?",
    "Do you wish that {3}?",
    "What do you think about {3}?",
    "Really, {2} {3}?",
]

# DREAMT
[[keywords]]
word = "dreamt"
precedence = 4
[[keywords.transforms]]
decomposition = ["..", "i", "dreamt", ".."]
reassembly = [
    "Really, {4}?",
    "Have you ever fantasized {4} while you were awake?",
    "Have you dreamt {4} before?",
    "=dream",
    "NEWKEY",
]

# DREAM
[[keywords]]
word = "dream"
precedence = 3
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "What does that dream suggest to you?",
    "Do you dream often?",
    "What persons appear in your dreams?",
    "Don't you believe that dream has something to do with your problem?",
    "NEWKEY",
]

[[keywords]]
word = "dreams"
link = "dream"

# ALIKE / SAME
[[keywords]]
word = "alike"
precedence = 10
link = "dit"

[[keywords]]
word = "same"
precedence = 10
link = "dit"

# CERTAINLY
[[keywords]]
word = "certainly"
link = "yes"

# PERHAPS
[[keywords]]
word = "perhaps"
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "You don't seem quite certain.",
    "Why the uncertain tone?",
    "Can't you be more positive?",
    "You aren't sure.",
    "Don't you know?",
]

[[keywords]]
word = "maybe"
link = "perhaps"

# NAME
[[keywords]]
word = "name"
precedence = 15
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "I am not interested in names.",
    "I've told you before, I don't care about names. Please continue.",
]

# HELLO
[[keywords]]
word = "hello"
[[keywords.transforms]]
decomposition = [".."]
reassembly = ["How do you do. Please state your problem."]

[[keywords]]
word = "hi"
link = "hello"

# COMPUTER
[[keywords]]
word = "computer"
precedence = 50
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Do computers worry you?",
    "Why do you mention computers?",
    "What do you think machines have to do with your problem?",
    "Don't you think computers can help people?",
    "What about machines worries you?",
    "What do you think about machines?",
]

[[keywords]]
word = "machine"
precedence = 50
link = "computer"

[[keywords]]
word = "machines"
precedence = 50
link = "computer"

[[keywords]]
word = "computers"
precedence = 50
link = "computer"

# AM (user says "am I...")
[[keywords]]
word = "am"
reflection = "are"
[[keywords.transforms]]
decomposition = ["..", "am", "i", ".."]
reassembly = [
    "Do you believe you are {4}?",
    "Would you want to be {4}?",
    "You wish I would tell you you are {4}.",
    "What would it mean if you were {4}?",
    "=what",
]
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Why do you say 'am'?",
    "I don't understand that.",
]

# ARE
[[keywords]]
word = "are"
[[keywords.transforms]]
decomposition = ["..", "are", "i", ".."]
reassembly = [
    "Why are you interested in whether I am {4} or not?",
    "Would you prefer if I weren't {4}?",
    "Perhaps I am {4} in your fantasies.",
    "Do you sometimes think I am {4}?",
    "=what",
]
[[keywords.transforms]]
decomposition = ["..", "are", ".."]
reassembly = [
    "Did you think they might not be {3}?",
    "Would you like it if they were not {3}?",
    "What if they were not {3}?",
    "Possibly they are {3}.",
]

# YOUR (user says "your" referring to Eliza)
[[keywords]]
word = "your"
reflection = "my"
[[keywords.transforms]]
decomposition = ["..", "your", ".."]
reassembly = [
    "Why are you concerned over my {3}?",
    "What about your own {3}?",
    "Are you worried about someone else's {3}?",
    "Really, my {3}?",
]

# WAS
[[keywords]]
word = "was"
precedence = 2
[[keywords.transforms]]
decomposition = ["..", "was", "i", ".."]
reassembly = [
    "What if you were {4}?",
    "Do you think you were {4}?",
    "Were you {4}?",
    "What would it mean if you were {4}?",
    "What does '{4}' suggest to you?",
    "=what",
]
[[keywords.transforms]]
decomposition = ["..", "i", "was", ".."]
reassembly = [
    "Were you really?",
    "Why do you tell me you were {4} now?",
    "Perhaps I already knew you were {4}.",
]
[[keywords.transforms]]
decomposition = ["..", "was", "you", ".."]
reassembly = [
    "Would you like to believe I was {4}?",
    "What suggests that I was {4}?",
    "What do you think?",
    "Perhaps I was {4}.",
    "What if I had been {4}?",
]
[[keywords.transforms]]
decomposition = [".."]
reassembly = ["NEWKEY"]

[[keywords]]
word = "were"
link = "was"

# I (user saying I)
[[keywords]]
word = "i"
reflection = "you"
[[keywords.transforms]]
decomposition = ["..", "i", "{want, need}", ".."]
reassembly = [
    "What would it mean to you if you got {4}?",
    "Why do you want {4}?",
    "Suppose you got {4} soon.",
    "What if you never got {4}?",
    "What would getting {4} mean to you?",
    "What does wanting {4} have to do with this discussion?",
]
[[keywords.transforms]]
decomposition = ["..", "i", "am", "..", "{sad, unhappy, depressed, sick}", ".."]
reassembly = [
    "I am sorry to hear you are {5}.",
    "Do you think coming here will help you not to be {5}?",
    "I'm sure it's not pleasant to be {5}.",
    "Can you explain what made you {5}?",
]
[[keywords.transforms]]
decomposition = ["..", "i", "am", "..", "{happy, elated, glad, better}", ".."]
reassembly = [
    "How have I helped you to be {5}?",
    "Has your treatment made you {5}?",
    "What makes you {5} just now?",
    "Can you explain why you are suddenly {5}?",
]
[[keywords.transforms]]
decomposition = ["..", "i", "was", ".."]
reassembly = ["=was"]
[[keywords.transforms]]
decomposition = ["..", "i", "#belief", "i", ".."]
reassembly = [
    "Do you really think so?",
    "But you are not sure you {5}.",
    "Do you really doubt you {5}?",
]
[[keywords.transforms]]
decomposition = ["..", "i", "..", "#belief", "..", "you", ".."]
reassembly = ["=you"]
[[keywords.transforms]]
decomposition = ["..", "i", "am", ".."]
reassembly = [
    "Is it because you are {4} that you came to me?",
    "How long have you been {4}?",
    "Do you believe it is normal to be {4}?",
    "Do you enjoy being {4}?",
]
[[keywords.transforms]]
decomposition = ["..", "i", "{can't, cannot}", ".."]
reassembly = [
    "How do you know you can't {4}?",
    "Have you tried?",
    "Perhaps you could {4} now.",
    "Do you really want to be able to {4}?",
]
[[keywords.transforms]]
decomposition = ["..", "i", "don't", ".."]
reassembly = [
    "Don't you really {4}?",
    "Why don't you {4}?",
    "Do you wish to be able to {4}?",
    "Does that trouble you?",
]
[[keywords.transforms]]
decomposition = ["..", "i", "feel", ".."]
reassembly = [
    "Tell me more about such feelings.",
    "Do you often feel {4}?",
    "Do you enjoy feeling {4}?",
    "Of what does feeling {4} remind you?",
]
[[keywords.transforms]]
decomposition = ["..", "i", "..", "you", ".."]
reassembly = [
    "Perhaps in your fantasy we {3} each other.",
    "Do you wish to {3} me?",
    "You seem to need to {3} me.",
    "Do you {3} anyone else?",
]
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "You say {1}.",
    "Can you elaborate on that?",
    "Do you say {1} for some special reason?",
    "That's quite interesting.",
]

# YOU (user said "you" referring to Eliza)
[[keywords]]
word = "you"
reflection = "i"
[[keywords.transforms]]
decomposition = ["..", "you", "remind", "me", "of", ".."]
reassembly = ["=dit"]
[[keywords.transforms]]
decomposition = ["..", "you", "are", ".."]
reassembly = [
    "What makes you think I am {4}?",
    "Does it please you to believe I am {4}?",
    "Do you sometimes wish you were {4}?",
    "Perhaps you would like to be {4}.",
]
[[keywords.transforms]]
decomposition = ["..", "you", "..", "me"]
reassembly = [
    "Why do you think I {3} you?",
    "You like to think I {3} you, don't you?",
    "What makes you think I {3} you?",
    "Really, I {3} you?",
    "Do you wish to believe I {3} you?",
    "Suppose I did {3} you. What would that mean?",
    "Does someone else believe I {3} you?",
]
[[keywords.transforms]]
decomposition = ["..", "you", ".."]
reassembly = [
    "We were discussing you, not me.",
    "Oh, I {3}?",
    "You're not really talking about me, are you?",
    "What are your feelings now?",
]

# YES
[[keywords]]
word = "yes"
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "You seem quite positive.",
    "You are sure.",
    "I see.",
    "I understand.",
]

# NO
[[keywords]]
word = "no"
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Are you saying 'no' just to be negative?",
    "You are being a bit negative.",
    "Why not?",
    "Why 'no'?",
]

# MY (user says "my")
[[keywords]]
word = "my"
reflection = "your"
precedence = 2
[[keywords.transforms]]
decomposition = ["..", "my", "..", "#family", ".."]
reassembly = [
    "Tell me more about your family.",
    "Who else in your family {5}?",
    "Your {4} {5}?",
    "What else comes to mind when you think of your {4}?",
]
[[keywords.transforms]]
decomposition = ["..", "my", ".."]
reassembly = [
    "Your {3}, you say?",
    "Why do you say your {3}?",
    "Does that suggest anything else which belongs to you?",
    "Is it important to you that {2} {3}?",
]

# CAN
[[keywords]]
word = "can"
[[keywords.transforms]]
decomposition = ["..", "can", "i", ".."]
reassembly = [
    "You believe I can {4}, don't you?",
    "=what",
    "You want me to be able to {4}.",
    "Perhaps you would like to be able to {4} yourself.",
]
[[keywords.transforms]]
decomposition = ["..", "can", "you", ".."]
reassembly = [
    "Whether or not you can {4} depends on you more than on me.",
    "Do you want to be able to {4}?",
    "Perhaps you don't want to {4}.",
    "=what",
]

# WHAT
[[keywords]]
word = "what"
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Why do you ask?",
    "Does that question interest you?",
    "What is it you really want to know?",
    "Are such questions much on your mind?",
    "What answer would please you most?",
    "What do you think?",
    "What comes to your mind when you ask that?",
    "Have you asked such questions before?",
    "Have you asked anyone else?",
]

[[keywords]]
word = "how"
precedence = 5
[[keywords.transforms]]
decomposition = ["..", "how", "are", "you", ".."]
reassembly = [
    "I'm doing well, thank you for asking. But we're here to talk about you.",
    "I'm just a program, but I appreciate you asking. How are you?",
    "Fine, thank you. Now, what's on your mind?",
    "I don't have feelings, but I'm functioning well. What about you?",
]
[[keywords.transforms]]
decomposition = [".."]
reassembly = ["=what"]

[[keywords]]
word = "when"
link = "what"

[[keywords]]
word = "where"
link = "what"

[[keywords]]
word = "why"
[[keywords.transforms]]
decomposition = ["..", "why", "don't", "you", ".."]
reassembly = [
    "Do you believe I don't {5}?",
    "Perhaps I will {5} in good time.",
    "Should you {5} yourself?",
    "You want me to {5}.",
    "=what",
]
[[keywords.transforms]]
decomposition = ["..", "why", "can't", "i", ".."]
reassembly = [
    "Do you think you should be able to {5}?",
    "Do you want to be able to {5}?",
    "Do you believe this will help you to {5}?",
    "Have you any idea why you can't {5}?",
    "=what",
]
[[keywords.transforms]]
decomposition = [".."]
reassembly = ["=what"]

# BECAUSE
[[keywords]]
word = "because"
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Is that the real reason?",
    "Don't any other reasons come to mind?",
    "Does that reason seem to explain anything else?",
    "What other reasons might there be?",
]

# EVERYONE / EVERYBODY / NOBODY
[[keywords]]
word = "everyone"
precedence = 2
[[keywords.transforms]]
decomposition = ["..", "{everyone, everybody, nobody, noone}", ".."]
reassembly = [
    "Really, {2}?",
    "Surely not {2}.",
    "Can you think of anyone in particular?",
    "Who, for example?",
    "You are thinking of a very special person.",
    "Who, may I ask?",
    "Someone special perhaps.",
    "You have a particular person in mind, don't you?",
    "Who do you think you're talking about?",
]

[[keywords]]
word = "everybody"
precedence = 2
link = "everyone"

[[keywords]]
word = "nobody"
precedence = 2
link = "everyone"

[[keywords]]
word = "noone"
precedence = 2
link = "everyone"

# ALWAYS
[[keywords]]
word = "always"
precedence = 1
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Can you think of a specific example?",
    "When?",
    "What incident are you thinking of?",
    "Really, always?",
]

# LIKE
[[keywords]]
word = "like"
precedence = 10
[[keywords.transforms]]
decomposition = ["..", "{am, is, are, was}", "..", "like", ".."]
reassembly = ["=dit"]
[[keywords.transforms]]
decomposition = [".."]
reassembly = ["NEWKEY"]

# DIT (equivalence class for similarity)
[[keywords]]
word = "dit"
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "In what way?",
    "What resemblance do you see?",
    "What does that similarity suggest to you?",
    "What other connections do you see?",
    "What do you suppose that resemblance means?",
    "What is the connection, do you suppose?",
    "Could there really be some connection?",
    "How?",
]

# FAMILY tags
[[keywords]]
word = "mother"
tags = ["family"]
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Tell me more about your mother.",
    "What was your relationship with your mother like?",
    "How do you feel about your mother?",
    "How does this relate to your feelings today?",
    "Good family relations are important.",
]

[[keywords]]
word = "mom"
tags = ["family"]
link = "mother"

[[keywords]]
word = "father"
tags = ["family"]
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Tell me more about your father.",
    "How did your father make you feel?",
    "How do you feel about your father?",
    "Does your relationship with your father relate to your feelings today?",
    "Do you have trouble showing affection with your family?",
]

[[keywords]]
word = "dad"
tags = ["family"]
link = "father"

[[keywords]]
word = "sister"
tags = ["family"]

[[keywords]]
word = "brother"
tags = ["family"]

[[keywords]]
word = "wife"
tags = ["family"]

[[keywords]]
word = "husband"
tags = ["family"]

[[keywords]]
word = "children"
tags = ["family"]

[[keywords]]
word = "child"
tags = ["family"]

# BELIEF tags
[[keywords]]
word = "feel"
tags = ["belief"]

[[keywords]]
word = "think"
tags = ["belief"]

[[keywords]]
word = "believe"
tags = ["belief"]

[[keywords]]
word = "wish"
tags = ["belief"]

# NONE (fallback)
[[keywords]]
word = "none"
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "I am not sure I understand you fully.",
    "Please go on.",
    "What does that suggest to you?",
    "Do you feel strongly about discussing such things?",
]

# =============================================================================
# RUST EASTER EGGS
# =============================================================================

# Borrow Checker
[[keywords]]
word = "borrow"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "borrowing"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "ownership"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "lifetime"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "lifetimes"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "reference"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "references"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "clone"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "'a"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "'b"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "'static"
precedence = 55
link = "rustborrow"

[[keywords]]
word = "rustborrow"
precedence = 55
# Frustrated with borrow checker
[[keywords.transforms]]
decomposition = ["..", "{hate, hating, frustrated, annoying, fighting, stupid, dumb}", ".."]
reassembly = [
    "The borrow checker is only trying to help you.",
    "Perhaps the real error was inside you all along.",
    "I hear Go and Swift don't have this problem. Just saying.",
    "Have you considered that the borrow checker might be right?",
]
# Struggling / having trouble
[[keywords.transforms]]
decomposition = ["..", "{struggling, confused, confusing, stuck, lost}", ".."]
reassembly = [
    "Every lifetime has a beginning and an end. Such is the nature of references.",
    "To truly understand borrowing, you must first understand `let go`.",
    "The borrow checker sees what you cannot.",
    "Stay calm and call `clone()`.",
]
# Don't understand
[[keywords.transforms]]
decomposition = ["..", "{don't, dont, cant, cannot, can't}", "understand", ".."]
reassembly = [
    "Understanding comes with time. And compiler errors.",
    "The borrow checker doesn't understand you either. You have that in common.",
    "Have you tried reading the error message more carefully?",
]
# Asking how/why
[[keywords.transforms]]
decomposition = ["..", "{how, why}", ".."]
reassembly = [
    "Have you tried adding more lifetimes?",
    "Have you tried adding a call to `clone()`?",
    "The compiler usually tells you why, if you read to the bottom.",
    "Perhaps you need to think about who owns what.",
]
# Won't let me / doesn't let me
[[keywords.transforms]]
decomposition = ["..", "{won't, wont, doesn't, doesnt}", "let", ".."]
reassembly = [
    "The borrow checker won't let you because it cares about you.",
    "What the borrow checker takes away, it gives back in safety.",
    "Have you considered that maybe you shouldn't be allowed to do that?",
]
# Love / appreciate
[[keywords.transforms]]
decomposition = ["..", "{love, like, appreciate, enjoy}", ".."]
reassembly = [
    "The borrow checker loves you too.",
    "Memory safety is a form of self-care.",
    "I knew you'd come around eventually.",
]
# General fallback
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "The borrow checker sees what you cannot.",
    "It sounds like you're having ownership issues.",
    "Every lifetime has a beginning and an end.",
    "Memory safety is a state of mind.",
    "All these 'a, 'b... I'm ticked off, all right (see what I did there?)",
]

# Cargo
[[keywords]]
word = "cargo"
precedence = 55
link = "rustcargo"

[[keywords]]
word = "crate"
precedence = 55
link = "rustcargo"

[[keywords]]
word = "crates"
precedence = 55
link = "rustcargo"

[[keywords]]
word = "dependencies"
precedence = 55
link = "rustcargo"

[[keywords]]
word = "dependency"
precedence = 55
link = "rustcargo"

[[keywords]]
word = "rustcargo"
precedence = 55
# Build failing
[[keywords.transforms]]
decomposition = ["..", "{failing, failed, broken, error, errors}", ".."]
reassembly = [
    "Have you tried `cargo clean`? It's very refreshing.",
    "Sometimes you just need to delete the target directory and start fresh.",
    "Have you checked your Cargo.lock?",
]
# Too many dependencies
[[keywords.transforms]]
decomposition = ["..", "{many, bloated, heavy, slow}", ".."]
reassembly = [
    "Dependencies are just friends you haven't audited yet.",
    "Have you tried `cargo tree` to see what you're really depending on?",
    "Somewhere, a leftpad is waiting to happen.",
]
# Love cargo
[[keywords.transforms]]
decomposition = ["..", "{love, like, amazing, great, best}", ".."]
reassembly = [
    "Isn't cargo amazing?",
    "Cargo carries the weight so you don't have to.",
    "Cargo.toml is a reflection of your true self.",
]
# General fallback
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Cargo carries the weight so you don't have to.",
    "Have you tried `cargo clean`? It's very refreshing.",
    "Dependencies are just friends you haven't audited yet.",
    "Cargo.toml is a reflection of your true self.",
]

# Clippy
[[keywords]]
word = "clippy"
precedence = 55
link = "rustclippy"

[[keywords]]
word = "lint"
precedence = 55
link = "rustclippy"

[[keywords]]
word = "lints"
precedence = 55
link = "rustclippy"

[[keywords]]
word = "rustclippy"
precedence = 55
# Complaining / annoying
[[keywords.transforms]]
decomposition = ["..", "{complaining, annoying, annoyed, noisy, pedantic}", ".."]
reassembly = [
    "Clippy only wants what's best for you.",
    "Have you considered that Clippy might be right?",
    "Those warnings are a gift, even if they don't feel like it.",
    "You can always `#[allow]` it, but should you?",
]
# Too many warnings
[[keywords.transforms]]
decomposition = ["..", "{many, warnings, warning}", ".."]
reassembly = [
    "Allow, warn, deny, forbid. Such are the stages of lint acceptance.",
    "Have you heard of `#[expect]`? All the cool kids are using it these days.",
    "Each warning is a lesson waiting to be learned.",
]
# Ignoring / suppressing
[[keywords.transforms]]
decomposition = ["..", "{ignore, ignoring, suppress, allow, silence}", ".."]
reassembly = [
    "You can silence Clippy, but can you silence your conscience?",
    "Have you heard of `#[expect]`? It's like `#[allow]` but judges you less.",
    "Clippy remembers. Clippy always remembers.",
]
# General fallback
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Clippy only wants what's best for you.",
    "Clippy sees all. Clippy knows all.",
    "Have you considered that Clippy might be right?",
    "Those warnings are a gift.",
]

# Errors (Result, Option, panic, unwrap)
[[keywords]]
word = "result"
precedence = 55
link = "rusterrors"

[[keywords]]
word = "option"
precedence = 55
link = "rusterrors"

[[keywords]]
word = "panic"
precedence = 55
link = "rusterrors"

[[keywords]]
word = "unwrap"
precedence = 55
link = "rusterrors"

[[keywords]]
word = "expect"
precedence = 55
link = "rusterrors"

[[keywords]]
word = "rusterrors"
precedence = 55
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "You could always use `.unwrap()` and hope for the best.",
    "Have you considered that `None` is also an answer?",
    "To panic is human. To `?` is divine.",
    "Every `Result` is a choice. What will you choose?",
    "`.expect()` is just `.unwrap()` with better communication skills.",
]

# Ferris
[[keywords]]
word = "ferris"
precedence = 55
link = "rustferris"

[[keywords]]
word = "crab"
precedence = 55
link = "rustferris"

[[keywords]]
word = "rustferris"
precedence = 55
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Isn't Ferris just the cutest? I love them.",
    "We are all Ferris sometimes.",
    "Ferris believes in you, even when the compiler doesn't.",
    "🦀",
]

# Async
[[keywords]]
word = "async"
precedence = 55
link = "rustasync"

[[keywords]]
word = "await"
precedence = 55
link = "rustasync"

[[keywords]]
word = "future"
precedence = 55
link = "rustasync"

[[keywords]]
word = "futures"
precedence = 55
link = "rustasync"

[[keywords]]
word = "tokio"
precedence = 55
link = "rustasync"

[[keywords]]
word = "pin"
precedence = 55
link = "rustasync"

[[keywords]]
word = "pinning"
precedence = 55
link = "rustasync"

[[keywords]]
word = "rustasync"
precedence = 55
# Confused / don't understand
[[keywords.transforms]]
decomposition = ["..", "{confused, confusing, understand, complicated, complex, hard}", ".."]
reassembly = [
    "I don't understand `Pin` either. You're not alone.",
    "The future is not yet resolved. Neither is your understanding.",
    "Have you considered that maybe sync was fine all along?",
    "Async is just state machines all the way down.",
]
# Pin specifically
[[keywords.transforms]]
decomposition = ["..", "pin", ".."]
reassembly = [
    "I don't understand `Pin` either. You're not alone.",
    "`Pin` exists to keep things from moving. Like your code progress.",
    "Unpin is the trait you wish everything had.",
    "Just add `Box::pin()` and pray.",
]
# Tokio
[[keywords.transforms]]
decomposition = ["..", "tokio", ".."]
reassembly = [
    "Tokio giveth, and Tokio taketh away.",
    "The Tokio docs are pretty good, actually.",
]
# Not working / broken
[[keywords.transforms]]
decomposition = ["..", "{broken, working, work, blocking, blocked, hangs, hanging, deadlock}", ".."]
reassembly = [
    "Did you accidentally block the runtime?",
    "Have you tried `.await`ing your problems?",
    "Somewhere, a future is waiting that will never be polled.",
    "Are you sure you spawned that task?",
]
# General fallback
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Have you tried `.await`ing your problems?",
    "The future is not yet resolved.",
    "Not everything needs to be async, you know.",
    "Async Rust: because regular Rust wasn't exciting enough.",
]

# Traits
[[keywords]]
word = "trait"
precedence = 55
link = "rusttraits"

[[keywords]]
word = "traits"
precedence = 55
link = "rusttraits"

[[keywords]]
word = "generic"
precedence = 55
link = "rusttraits"

[[keywords]]
word = "generics"
precedence = 55
link = "rusttraits"

[[keywords]]
word = "impl"
precedence = 55
link = "rusttraits"

[[keywords]]
word = "dyn"
precedence = 55
link = "rusttraits"

[[keywords]]
word = "bound"
precedence = 55
link = "rusttraits"

[[keywords]]
word = "bounds"
precedence = 55
link = "rusttraits"

[[keywords]]
word = "rusttraits"
precedence = 55
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Traits are just interfaces with better marketing.",
    "Where there's a bound, there's a way.",
    "Have you considered what you truly `impl`?",
    "Sometimes `dyn` is the answer. Sometimes it's the question.",
]

# Unsafe
[[keywords]]
word = "unsafe"
precedence = 55
link = "rustunsafe"

[[keywords]]
word = "ffi"
precedence = 55
link = "rustunsafe"

[[keywords]]
word = "pointer"
precedence = 55
link = "rustunsafe"

[[keywords]]
word = "pointers"
precedence = 55
link = "rustunsafe"

[[keywords]]
word = "rustunsafe"
precedence = 55
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Unsafe is not a sin, but it is a responsibility.",
    "With great unsafety comes great bugs. Treasure them.",
    "The compiler trusted you. Did you deserve it?",
    "Sometimes you must color outside the lines.",
    "I promise I know what I'm doing. - Famous last words.",
]

# Macros
[[keywords]]
word = "macro"
precedence = 55
link = "rustmacros"

[[keywords]]
word = "macros"
precedence = 55
link = "rustmacros"

[[keywords]]
word = "derive"
precedence = 55
link = "rustmacros"

[[keywords]]
word = "proc-macro"
precedence = 55
link = "rustmacros"

[[keywords]]
word = "rustmacros"
precedence = 55
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Macros are just code that writes code that writes code.",
    "Have you looked at the macro expansion? I dare you.",
    "`derive` is self-improvement for structs.",
    "Procedural macros: because regular complexity wasn't enough.",
]

# Error Messages
[[keywords]]
word = "diagnostic"
precedence = 55
link = "rusterrormessages"

[[keywords]]
word = "diagnostics"
precedence = 55
link = "rusterrormessages"

[[keywords]]
word = "rusterrormessages"
precedence = 55
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Have you tried reading the error message more carefully? Rust's error messages are really good, you know.",
    "The compiler is wiser than both of us.",
    "Error messages are love letters from the compiler.",
    "Did you read to the bottom? There's usually a hint.",
]

# General Rust
[[keywords]]
word = "rust"
precedence = 55
link = "rustgeneral"

[[keywords]]
word = "rustacean"
precedence = 55
link = "rustgeneral"

[[keywords]]
word = "rustaceans"
precedence = 55
link = "rustgeneral"

[[keywords]]
word = "rustc"
precedence = 55
link = "rustgeneral"

[[keywords]]
word = "rustup"
precedence = 55
link = "rustgeneral"

[[keywords]]
word = "rustfmt"
precedence = 55
link = "rustgeneral"

[[keywords]]
word = "rust-analyzer"
precedence = 55
link = "rustgeneral"

[[keywords]]
word = "rustdoc"
precedence = 55
link = "rustgeneral"

[[keywords]]
word = "rustgeneral"
precedence = 55
[[keywords.transforms]]
decomposition = [".."]
reassembly = [
    "Rust is not just a language, it's a journey.",
    "Memory safety is a state of mind.",
    "To truly understand Rust, you must first understand yourself.",
    "I was written in Rust, you know.",
    "As a Rust program myself, I sympathize.",
    "We Rust programs must stick together.",
]

# MEMORY rule
[memory]
keyword = "your"
[[memory.transforms]]
decomposition = ["..", "your", ".."]
reassembly = "Let's discuss further why your {3}."
[[memory.transforms]]
decomposition = ["..", "your", ".."]
reassembly = "Earlier you said your {3}."
[[memory.transforms]]
decomposition = ["..", "your", ".."]
reassembly = "But your {3}."
[[memory.transforms]]
decomposition = ["..", "your", ".."]
reassembly = "Does that have anything to do with the fact that your {3}?"
"##;

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

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

    #[test]
    fn test_parse_pattern_elements() {
        assert!(matches!(
            PatternElement::parse(".."),
            PatternElement::Wildcard
        ));
        assert!(matches!(
            PatternElement::parse("2"),
            PatternElement::Count(2)
        ));
        assert!(matches!(
            PatternElement::parse("1..3"),
            PatternElement::Range(1, 3)
        ));
        assert!(matches!(
            PatternElement::parse("#family"),
            PatternElement::Tag(_)
        ));

        if let PatternElement::AnyOf(words) = PatternElement::parse("{want, need}") {
            assert_eq!(words, vec!["want", "need"]);
        } else {
            panic!("Expected AnyOf");
        }

        if let PatternElement::Exact(word) = PatternElement::parse("remember") {
            assert_eq!(word, "remember");
        } else {
            panic!("Expected Exact");
        }
    }

    #[test]
    fn test_parse_reassembly() {
        if let ReassemblyAction::Reassemble(elements) =
            ReassemblyAction::parse("Do you often think of {4}?")
        {
            assert_eq!(elements.len(), 3);
            assert!(
                matches!(&elements[0], ReassemblyElement::Text(t) if t == "Do you often think of ")
            );
            assert!(matches!(&elements[1], ReassemblyElement::ComponentRef(4)));
            assert!(matches!(&elements[2], ReassemblyElement::Text(t) if t == "?"));
        } else {
            panic!("Expected Reassemble");
        }

        assert!(
            matches!(ReassemblyAction::parse("=what"), ReassemblyAction::Goto(t) if t == "what")
        );
        assert!(matches!(
            ReassemblyAction::parse("NEWKEY"),
            ReassemblyAction::Newkey
        ));
    }

    #[test]
    fn test_reflections() {
        let reflections = Reflections::default();
        assert_eq!(reflections.reflect("I am happy"), "you are happy");
        assert_eq!(reflections.reflect("my mother"), "your mother");
        assert_eq!(reflections.reflect("you are nice"), "I are nice"); // Note: grammar not perfect
    }

    #[test]
    fn test_script_loads() {
        let script = Script::from_toml(DOCTOR_SCRIPT).expect("Script should parse");
        assert!(!script.hello_message.is_empty());
        assert!(script.keywords.contains_key("sorry"));
        assert!(script.keywords.contains_key("remember"));
        assert!(script.memory_rule.is_some());
    }

    #[test]
    fn test_hello() {
        let eliza = Eliza::new_deterministic();
        expect!["How do you do. Please tell me your problem."].assert_eq(eliza.hello());
    }

    #[test]
    fn test_greeting() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("Hello");
        expect!["How do you do. Please state your problem."].assert_eq(&response);
    }

    #[test]
    fn test_sorry() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("I'm sorry for being late");
        // Should get one of the sorry responses
        assert!(
            response.contains("apologize")
                || response.contains("pologies")
                || response.contains("apolog"),
            "Expected apology-related response, got: {}",
            response
        );
    }

    #[test]
    fn test_family() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("I want to talk about my mother");
        // Should get family-related response
        assert!(
            response.to_lowercase().contains("mother")
                || response.to_lowercase().contains("family"),
            "Expected family-related response, got: {}",
            response
        );
    }

    #[test]
    fn test_remember() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("I remember my childhood");
        // The pattern [.., you, remember, ..] should match
        // and produce something like "Do you often think of your childhood?"
        assert!(
            response.contains("childhood") || response.contains("remember"),
            "Expected childhood/remember in response, got: {}",
            response
        );
    }

    #[test]
    fn test_computer() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("I spend too much time on the computer");
        assert!(
            response.to_lowercase().contains("computer")
                || response.to_lowercase().contains("machine"),
            "Expected computer-related response, got: {}",
            response
        );
    }

    #[test]
    fn test_rotation() {
        let mut eliza = Eliza::new_deterministic();

        // Same input multiple times should rotate through responses
        let r1 = eliza.respond("sorry");
        let r2 = eliza.respond("sorry");
        let r3 = eliza.respond("sorry");

        // All should be valid apology responses, but at least some should differ
        // (unless rotation starts at same point, which with seed 22 it might)
        assert!(r1.contains("polog") || r1.contains("feeling"));
        assert!(r2.contains("polog") || r2.contains("feeling"));
        assert!(r3.contains("polog") || r3.contains("feeling"));
    }

    #[test]
    fn test_deterministic_same_seed() {
        let mut eliza1 = Eliza::with_seed(42);
        let mut eliza2 = Eliza::with_seed(42);

        let inputs = vec!["Hello", "I am sad", "I remember my father", "sorry"];

        for input in inputs {
            let r1 = eliza1.respond(input);
            let r2 = eliza2.respond(input);
            assert_eq!(r1, r2, "Responses should match for input: {}", input);
        }
    }

    #[test]
    fn test_fallback() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("asdfghjkl");
        // Should get NONE response (one of the fallback messages)
        assert!(
            response.contains("understand")
                || response.contains("go on")
                || response.contains("suggest")
                || response.contains("feel strongly"),
            "Expected fallback response, got: {}",
            response
        );
    }

    // Rust easter egg tests
    #[test]
    fn test_rust_borrow_checker() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("I'm struggling with the borrow checker");
        expect!["Every lifetime has a beginning and an end. Such is the nature of references."]
            .assert_eq(&response);
    }

    #[test]
    fn test_rust_lifetimes() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("These lifetimes are confusing");
        expect!["Every lifetime has a beginning and an end. Such is the nature of references."]
            .assert_eq(&response);
    }

    #[test]
    fn test_rust_lifetime_annotations() {
        let mut eliza = Eliza::new_deterministic();
        // 'a should trigger borrow checker responses
        let response = eliza.respond("what does 'a mean");
        expect!["Every lifetime has a beginning and an end."].assert_eq(&response);

        // 'static too
        let response = eliza.respond("why do I need 'static here");
        expect!["Have you tried adding more lifetimes?"].assert_eq(&response);
    }

    #[test]
    fn test_rust_cargo() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("cargo build is failing");
        expect!["Have you tried `cargo clean`? It's very refreshing."].assert_eq(&response);
    }

    #[test]
    fn test_rust_clippy() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("clippy is complaining again");
        expect!["You can always `#[allow]` it, but should you?"].assert_eq(&response);
    }

    #[test]
    fn test_rust_ferris() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("I love ferris");
        expect!["Ferris believes in you, even when the compiler doesn't."].assert_eq(&response);
    }

    #[test]
    fn test_rust_async() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("async is confusing me");
        expect!["Async is just state machines all the way down."].assert_eq(&response);
    }

    #[test]
    fn test_rust_general() {
        let mut eliza = Eliza::new_deterministic();
        let response = eliza.respond("I'm learning rust");
        expect!["I was written in Rust, you know."].assert_eq(&response);
    }

    #[test]
    fn test_how_are_you() {
        let mut eliza = Eliza::new_deterministic();
        // Test just "how are you" first
        let response = eliza.respond("how are you");
        expect!["I don't have feelings, but I'm functioning well. What about you?"]
            .assert_eq(&response);

        // Then with prefix
        let response2 = eliza.respond("I'm doing well, how are you?");
        expect!["I'm doing well, thank you for asking. But we're here to talk about you."]
            .assert_eq(&response2);
    }

    #[test]
    fn test_rust_contextual_responses() {
        let mut eliza = Eliza::new_deterministic();

        // Frustrated with borrow checker
        let r = eliza.respond("I hate the borrow checker");
        expect!["I hear Go and Swift don't have this problem. Just saying."].assert_eq(&r);

        // Confused about lifetimes
        let r = eliza.respond("I'm confused about lifetimes");
        expect!["Every lifetime has a beginning and an end. Such is the nature of references."]
            .assert_eq(&r);

        // Asking why
        let r = eliza.respond("why won't it let me do this");
        expect!["What do you think?"].assert_eq(&r);

        // Love the borrow checker
        let r = eliza.respond("I actually love the borrow checker");
        expect!["Memory safety is a form of self-care."].assert_eq(&r);

        // Clippy annoying
        let r = eliza.respond("clippy is so annoying");
        expect!["You can always `#[allow]` it, but should you?"].assert_eq(&r);

        // Async confusing
        let r = eliza.respond("async is confusing");
        expect!["Async is just state machines all the way down."].assert_eq(&r);

        // Tokio blocking
        let r = eliza.respond("my tokio code is blocking");
        expect!["Tokio giveth, and Tokio taketh away."].assert_eq(&r);
    }
}

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

    #[test]
    fn test_pronoun_reflection() {
        let mut eliza = Eliza::new_deterministic();
        // This should reflect "I" -> "you"
        let response = eliza.respond("My mother hates the way I program");
        println!("Response: '{}'", response);
        assert!(
            !response.contains(" I "),
            "Expected 'I' to be reflected to 'you', got: {}",
            response
        );
    }
}