flow-wm 0.1.1

A scrolling, infinite-horizontal-canvas tiling window manager for Windows
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
//! Pure-logic window classification — no Win32 dependencies.
//!
//! Evaluates config [`WindowRule`]s against a [`WindowCandidate`] to determine
//! the window's [`WindowAction`] (Tile / Float / Ignore). Rules are processed
//! top-to-bottom with first-match-wins semantics. Maximized and fullscreen
//! overrides always take precedence over rules.
//!
//! # Design: platform independence
//!
//! This module is intentionally **platform-independent**. It accepts a
//! [`WindowCandidate`] (a plain Rust struct with no HWND) and produces a
//! [`WindowAction`] or [`WindowState`]. All classification logic can therefore
//! be unit-tested without any Win32 mocking, and the Win32 layer that gathers
//! window metadata is cleanly separated from the decision logic.
//!
//! # Pipeline (overview)
//!
//! Classification runs after cheap Win32 pre-filters (visible, titled, Alt+Tab
//! visible, no owner) have already eliminated obvious non-candidates in the
//! registry layer. Then, in order: maximized → `Ignored(Maximized)`; fullscreen
//! → `Ignored(Fullscreen)`; otherwise the [`ClassificationPipeline`] runs user
//! rules, then learned rules, then default rules — first match wins,
//! falling back to the default action. All regex patterns are pre-compiled at
//! construction time. The [`matches_rule`] function is kept public for testing
//! individual rule-matching logic.
//!
//! See the developer guide's *Window Registry* chapter
//! (`docs/src/dev-guide/window-registry.md`) for the full classification
//! flowchart and the default-rule catalogue.

use crate::common::Rect;
use crate::config::types::{MatchRule, WindowAction, WindowRule, WindowRulesConfig};
use crate::registry::types::{FloatingState, IgnoredReason, TilingState, WindowState};

// ── WindowCandidate ────────────────────────────────────────────────

/// Platform-independent snapshot of window metadata used for rule classification.
///
/// The Win32 layer fills this struct; the classifier never touches HWND. Consumed
/// by [`ClassificationPipeline`] and [`matches_rule`] to produce a [`WindowAction`].
///
/// See the developer guide's *Window Registry* chapter
/// (`docs/src/dev-guide/window-registry.md`) for the decoupling rationale and
/// the full classification algorithm.
#[derive(Debug, Clone)]
pub struct WindowCandidate {
    /// Executable name (e.g. `"code.exe"`).
    pub exe: String,
    /// Window title bar text.
    pub title: String,
    /// Win32 window class name.
    pub class: String,
    /// Full path to the executable.
    pub process_path: String,
}

// ── matches_rule ────────────────────────────────────────────────────

/// Test whether a window candidate matches all specified fields in a rule.
///
/// Uses AND logic: **every specified (non-`None`) field must match**.
/// Unspecified fields are ignored entirely.
///
/// # Match Semantics
///
/// | Field               | Match mode                     | Case sensitivity |
/// |----------------------|--------------------------------|------------------|
/// | `exe`               | Exact match                    | Case-insensitive |
/// | `exe_regex`         | Regex (full string)            | Case-insensitive |
/// | `title`             | Exact match                    | Case-sensitive   |
/// | `title_contains`    | Substring match                | Case-sensitive   |
/// | `title_regex`       | Regex (full string)            | Case-sensitive   |
/// | `class`             | Exact match                    | Case-sensitive   |
/// | `class_regex`       | Regex (full string)            | Case-sensitive   |
/// | `process_path`      | Exact match                    | Case-insensitive |
/// | `process_path_regex` | Regex (full string)           | Case-insensitive |
///
/// If a regex pattern fails to compile, logs a warning and treats the field
/// as non-matching (returns `false`). This prevents a bad regex from crashing
/// the daemon — the window simply falls through to the next rule or default.
#[must_use]
pub fn matches_rule(candidate: &WindowCandidate, rule: &MatchRule) -> bool {
    // exe — exact, case-insensitive (Windows paths are case-insensitive)
    if let Some(ref exe) = rule.exe
        && !candidate.exe.eq_ignore_ascii_case(exe)
    {
        return false;
    }

    // exe_regex — case-insensitive regex
    if let Some(ref pattern) = rule.exe_regex {
        match regex::RegexBuilder::new(pattern)
            .case_insensitive(true)
            .build()
        {
            Ok(re) => {
                if !re.is_match(&candidate.exe) {
                    return false;
                }
            }
            Err(e) => {
                log::warn!(
                    "exe_regex pattern '{pattern}' failed to compile: {e}; treating as non-match"
                );
                return false;
            }
        }
    }

    // title — exact, case-sensitive
    if let Some(ref title) = rule.title
        && candidate.title != *title
    {
        return false;
    }

    // title_contains — substring, case-sensitive
    if let Some(ref substr) = rule.title_contains
        && !candidate.title.contains(substr)
    {
        return false;
    }

    // title_regex — case-sensitive regex
    if let Some(ref pattern) = rule.title_regex {
        match regex::Regex::new(pattern) {
            Ok(re) => {
                if !re.is_match(&candidate.title) {
                    return false;
                }
            }
            Err(e) => {
                log::warn!(
                    "title_regex pattern '{pattern}' failed to compile: {e}; treating as non-match"
                );
                return false;
            }
        }
    }

    // class — exact, case-sensitive
    if let Some(ref class) = rule.class
        && candidate.class != *class
    {
        return false;
    }

    // class_regex — case-sensitive regex
    if let Some(ref pattern) = rule.class_regex {
        match regex::Regex::new(pattern) {
            Ok(re) => {
                if !re.is_match(&candidate.class) {
                    return false;
                }
            }
            Err(e) => {
                log::warn!(
                    "class_regex pattern '{pattern}' failed to compile: {e}; treating as non-match"
                );
                return false;
            }
        }
    }

    // process_path — exact, case-insensitive (Windows paths)
    if let Some(ref path) = rule.process_path
        && !candidate.process_path.eq_ignore_ascii_case(path)
    {
        return false;
    }

    // process_path_regex — case-insensitive regex
    if let Some(ref pattern) = rule.process_path_regex {
        match regex::RegexBuilder::new(pattern)
            .case_insensitive(true)
            .build()
        {
            Ok(re) => {
                if !re.is_match(&candidate.process_path) {
                    return false;
                }
            }
            Err(e) => {
                log::warn!(
                    "process_path_regex pattern '{pattern}' failed to compile: {e}; treating as non-match"
                );
                return false;
            }
        }
    }

    true
}

/// Convert a [`WindowAction`] to its corresponding initial [`WindowState`].
///
/// This produces placeholder positions (`col: 0, row: 0` / zero-rect) that
/// the layout engine will update once the window is placed.
#[must_use]
fn action_to_state(action: WindowAction) -> WindowState {
    match action {
        WindowAction::Tile => WindowState::Tiling(TilingState::Active { col: 0, row: 0 }),
        WindowAction::Float => WindowState::Floating(FloatingState::Active {
            rect: Rect {
                x: 0,
                y: 0,
                width: 0,
                height: 0,
            },
        }),
        WindowAction::Ignore => WindowState::Ignored(IgnoredReason::ExplicitRule),
    }
}

// ── CompiledRegex ─────────────────────────────────────────────────────

/// Pre-compiled regex with three possible states.
///
/// Used by [`CompiledRule`] to avoid recompiling regex patterns on every
/// classification call. Each regex field from a [`MatchRule`] is compiled
/// once at pipeline construction time.
///
/// # Variants
///
/// - `Unspecified` — The original pattern was `None`; skip this field entirely.
/// - `Valid(Regex)` — Pattern compiled successfully; use it for matching.
/// - `Invalid` — Pattern failed to compile; treat as non-match (same as
///   the runtime behaviour in [`matches_rule`], but logged once at startup).
enum CompiledRegex {
    /// Pattern was `None` — field not specified, skip check.
    Unspecified,
    /// Pattern compiled successfully.
    Valid(regex::Regex),
    /// Pattern failed to compile — treat as non-match.
    Invalid,
}

// ── CompiledRule ──────────────────────────────────────────────────────

/// A [`WindowRule`] with all regex patterns pre-compiled.
///
/// Created at pipeline construction time so that repeated calls to
/// [`ClassificationPipeline::classify`] avoid the cost of compiling regex
/// patterns on every match attempt.
///
/// # Performance
///
/// Without caching, each call to [`matches_rule`] rebuilds up to 4 regex
/// objects (`exe_regex`, `title_regex`, `class_regex`, `process_path_regex`).
/// For a daemon that classifies hundreds of windows and re-classifies on
/// config reload, this is measurable overhead. Pre-compiling once at
/// construction time makes every subsequent `classify()` call pure matching
/// with zero allocations.
///
/// # Fallback for Invalid Patterns
///
/// If a regex pattern fails to compile, the corresponding [`CompiledRegex`]
/// is set to `Invalid`. At match time, this causes the field to return
/// `false` (non-match), exactly matching the runtime behaviour of
/// [`matches_rule`].
struct CompiledRule {
    /// The original rule (holds action, non-regex fields, etc.).
    rule: WindowRule,
    /// Pre-compiled `exe_regex` (case-insensitive).
    exe_regex: CompiledRegex,
    /// Pre-compiled `title_regex` (case-sensitive).
    title_regex: CompiledRegex,
    /// Pre-compiled `class_regex` (case-sensitive).
    class_regex: CompiledRegex,
    /// Pre-compiled `process_path_regex` (case-insensitive).
    process_path_regex: CompiledRegex,
}

/// Compile a single regex pattern into a [`CompiledRegex`].
///
/// - `None` → `Unspecified`
/// - Valid pattern → `Valid(Regex)` with the given case sensitivity
/// - Invalid pattern → logs a warning → `Invalid`
fn compile_regex(pattern: Option<&str>, case_insensitive: bool, field_name: &str) -> CompiledRegex {
    match pattern {
        None => CompiledRegex::Unspecified,
        Some(p) => {
            let mut builder = regex::RegexBuilder::new(p);
            builder.case_insensitive(case_insensitive);
            match builder.build() {
                Ok(re) => CompiledRegex::Valid(re),
                Err(e) => {
                    log::warn!(
                        "{field_name} pattern '{p}' failed to compile: {e}; treating as non-match"
                    );
                    CompiledRegex::Invalid
                }
            }
        }
    }
}

/// Test whether a window candidate matches a compiled rule.
///
/// Uses AND logic identical to [`matches_rule`]: every specified (non-`None`)
/// field must match. The difference is that regex fields use pre-compiled
/// [`CompiledRegex`] values instead of building a new `Regex` per call.
#[must_use]
fn matches_compiled_rule(candidate: &WindowCandidate, compiled: &CompiledRule) -> bool {
    let rule = &compiled.rule.match_;

    // exe — exact, case-insensitive (Windows paths are case-insensitive)
    if let Some(ref exe) = rule.exe
        && !candidate.exe.eq_ignore_ascii_case(exe)
    {
        return false;
    }

    // exe_regex — pre-compiled, case-insensitive
    match &compiled.exe_regex {
        CompiledRegex::Valid(re) => {
            if !re.is_match(&candidate.exe) {
                return false;
            }
        }
        CompiledRegex::Invalid => return false,
        CompiledRegex::Unspecified => {}
    }

    // title — exact, case-sensitive
    if let Some(ref title) = rule.title
        && candidate.title != *title
    {
        return false;
    }

    // title_contains — substring, case-sensitive
    if let Some(ref substr) = rule.title_contains
        && !candidate.title.contains(substr)
    {
        return false;
    }

    // title_regex — pre-compiled, case-sensitive
    match &compiled.title_regex {
        CompiledRegex::Valid(re) => {
            if !re.is_match(&candidate.title) {
                return false;
            }
        }
        CompiledRegex::Invalid => return false,
        CompiledRegex::Unspecified => {}
    }

    // class — exact, case-sensitive
    if let Some(ref class) = rule.class
        && candidate.class != *class
    {
        return false;
    }

    // class_regex — pre-compiled, case-sensitive
    match &compiled.class_regex {
        CompiledRegex::Valid(re) => {
            if !re.is_match(&candidate.class) {
                return false;
            }
        }
        CompiledRegex::Invalid => return false,
        CompiledRegex::Unspecified => {}
    }

    // process_path — exact, case-insensitive (Windows paths)
    if let Some(ref path) = rule.process_path
        && !candidate.process_path.eq_ignore_ascii_case(path)
    {
        return false;
    }

    // process_path_regex — pre-compiled, case-insensitive
    match &compiled.process_path_regex {
        CompiledRegex::Valid(re) => {
            if !re.is_match(&candidate.process_path) {
                return false;
            }
        }
        CompiledRegex::Invalid => return false,
        CompiledRegex::Unspecified => {}
    }

    true
}

/// Compile all regex patterns in a list of [`WindowRule`]s into [`CompiledRule`]s.
fn compile_rules(rules: Vec<WindowRule>) -> Vec<CompiledRule> {
    rules
        .into_iter()
        .map(|rule| {
            let m = &rule.match_;
            CompiledRule {
                exe_regex: compile_regex(m.exe_regex.as_deref(), true, "exe_regex"),
                title_regex: compile_regex(m.title_regex.as_deref(), false, "title_regex"),
                class_regex: compile_regex(m.class_regex.as_deref(), false, "class_regex"),
                process_path_regex: compile_regex(
                    m.process_path_regex.as_deref(),
                    true,
                    "process_path_regex",
                ),
                rule,
            }
        })
        .collect()
}

// ── ClassificationPipeline ───────────────────────────────────────────

/// Multi-layer classification pipeline with pre-compiled regex patterns.
///
/// Evaluates rule layers in priority order (first match wins):
///
/// 1. **User rules** — from `flow-rules.toml` (highest priority).
/// 2. **Learned rules** — persisted user decisions from `set-window` (`history-flow-rules.toml`).
/// 3. **Default rules** — bundled at compile time (lowest rule priority).
/// 4. **Default action** — fallback when no rule matches at any layer.
///
/// All regex patterns are pre-compiled at construction. Entry point:
/// [`classify`](Self::classify). OS-state overrides (maximized/fullscreen)
/// are handled before the pipeline runs — see [`classify_with_state_pipeline`].
pub struct ClassificationPipeline {
    /// User-defined rules with pre-compiled regexes (highest priority after OS overrides).
    user_rules: Vec<CompiledRule>,
    /// Default rules bundled with the application (lowest rule priority).
    default_rules: Vec<CompiledRule>,
    /// Learned rules — persisted user decisions, populated at runtime via
    /// [`set_learned_rules`](Self::set_learned_rules).
    learned_rules: Vec<CompiledRule>,
    /// Fallback action when no rule matches at any layer.
    default_action: WindowAction,
}

impl ClassificationPipeline {
    /// Creates a new classification pipeline from user and default rule configs.
    ///
    /// All regex patterns are pre-compiled at this point. Invalid patterns
    /// are logged as warnings and treated as non-matching at classification
    /// time (identical to the runtime fallback in [`matches_rule`]).
    ///
    /// The fallback action used when no rule at any layer matches is taken
    /// from `user_rules.default_action`. The `default_rules.default_action`
    /// field is intentionally ignored — the user's preference always governs
    /// the final fallback.
    ///
    /// # Arguments
    ///
    /// * `user_rules` - Rules from the user's `flow-rules.toml`.
    /// * `default_rules` - Bundled default rules (embedded at compile time from
    ///   `default-flow-rules.toml`).
    #[must_use]
    pub fn new(user_rules: WindowRulesConfig, default_rules: WindowRulesConfig) -> Self {
        let default_action = user_rules.default_action;
        Self {
            user_rules: compile_rules(user_rules.rules),
            default_rules: compile_rules(default_rules.rules),
            learned_rules: Vec::new(),
            default_action,
        }
    }

    /// Classify a window candidate using the full pipeline.
    ///
    /// Evaluates rule layers in order (user → learned → default), returning
    /// the action from the first matching rule. If no rule matches at any
    /// layer, returns the `default_action`.
    ///
    /// Returns a [`WindowAction`] (not [`WindowState`]) — OS overrides
    /// (maximized/fullscreen) are handled separately by
    /// [`classify_with_state_pipeline`].
    #[must_use]
    pub fn classify(&self, candidate: &WindowCandidate) -> WindowAction {
        // 1. User rules (first match wins)
        for compiled in &self.user_rules {
            if matches_compiled_rule(candidate, compiled) {
                return compiled.rule.action;
            }
        }

        // 2. Learned rules (first match wins)
        for compiled in &self.learned_rules {
            if matches_compiled_rule(candidate, compiled) {
                return compiled.rule.action;
            }
        }

        // 3. Default rules (first match wins)
        for compiled in &self.default_rules {
            if matches_compiled_rule(candidate, compiled) {
                return compiled.rule.action;
            }
        }

        // 4. Fallback
        self.default_action
    }

    /// Replace the learned-rules layer with recompiled versions of `rules`.
    ///
    /// Learned rules sit between user rules and default rules in the priority
    /// chain — see (`docs/src/dev-guide/classification.md`). Call this after
    /// the daemon records a new user decision (e.g. via `set-window tile`)
    /// so the next window of the same app is classified to the learned mode.
    ///
    /// Recompiles all regex patterns (cheap at human-frequency update rates).
    /// Invalid regex patterns are logged and treated as non-matching at
    /// classification time, identical to [`new`](Self::new).
    pub fn set_learned_rules(&mut self, rules: Vec<WindowRule>) {
        self.learned_rules = compile_rules(rules);
    }

    /// Replace the user-rules layer (and fallback action) from `flow-rules.toml`.
    ///
    /// Used by hot-reload so classification picks up edited rules without
    /// restarting the daemon. Recompiles all regex patterns; invalid patterns
    /// are logged and treated as non-matching, identical to
    /// [`new`](Self::new). The fallback `default_action` is also refreshed
    /// from `user_rules.default_action`. See
    /// (`docs/src/dev-guide/config-and-persistence.md`).
    pub fn set_user_rules(&mut self, user_rules: WindowRulesConfig) {
        self.default_action = user_rules.default_action;
        self.user_rules = compile_rules(user_rules.rules);
    }
}

// ── classify_with_state_pipeline ──────────────────────────────────────

/// Classify a window using the full pipeline (OS overrides + multi-layer rules).
///
/// This is the high-level entry point that combines:
/// 1. Maximized/fullscreen OS-state overrides (always win).
/// 2. Multi-layer rule evaluation via [`ClassificationPipeline`].
/// 3. Action → [`WindowState`] conversion.
///
/// Visibility is `pub(super)` — this function is called by
/// [`core::WindowRegistry`](super::core::WindowRegistry) and is not part of
/// the public API of the registry module. External callers should interact
/// with the registry directly, not with the classification internals.
///
/// # Arguments
///
/// * `candidate` - Window metadata for classification.
/// * `is_maximized` - Whether the window is currently maximized.
/// * `is_fullscreen` - Whether the window is in fullscreen mode.
/// * `pipeline` - The multi-layer classification pipeline.
///
/// # Returns
///
/// A [`WindowState`] — `Ignored(Maximized)` or `Ignored(Fullscreen)` for OS
/// overrides, or the pipeline's result converted to a state.
#[must_use]
pub(super) fn classify_with_state_pipeline(
    candidate: &WindowCandidate,
    is_maximized: bool,
    is_fullscreen: bool,
    pipeline: &ClassificationPipeline,
) -> WindowState {
    if is_maximized {
        return WindowState::Ignored(IgnoredReason::Maximized);
    }
    if is_fullscreen {
        return WindowState::Ignored(IgnoredReason::Fullscreen);
    }

    let action = pipeline.classify(candidate);
    action_to_state(action)
}

// ── Tests ───────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registry::types::IgnoredReason;

    /// Helper to build a [`WindowCandidate`] with minimal boilerplate.
    fn candidate(exe: &str, title: &str, class: &str, process_path: &str) -> WindowCandidate {
        WindowCandidate {
            exe: exe.to_owned(),
            title: title.to_owned(),
            class: class.to_owned(),
            process_path: process_path.to_owned(),
        }
    }

    /// Helper to build a [`WindowRule`] from a [`MatchRule`] and [`WindowAction`].
    fn rule(match_rule: MatchRule, action: WindowAction) -> WindowRule {
        WindowRule {
            match_: match_rule,
            action,
            initial_width_px: None,
            override_persist: false,
        }
    }

    /// Helper to build a [`ClassificationPipeline`] from user rules and a default action.
    ///
    /// Creates a pipeline with the given rules as user rules, no default rules,
    /// and the given `default_action`. Useful for testing single-layer classification
    /// without boilerplate.
    fn pipeline_from(
        rules: Vec<WindowRule>,
        default_action: WindowAction,
    ) -> ClassificationPipeline {
        ClassificationPipeline::new(
            WindowRulesConfig {
                default_action,
                rules,
            },
            WindowRulesConfig::default(),
        )
    }

    // --- Pipeline classification tests (single-layer) ---

    #[test]
    fn pipeline_exact_exe_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("notepad.exe".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("notepad.exe", "", "", "");
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    #[test]
    fn pipeline_case_insensitive_exe_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("Explorer.EXE".into()),
                    ..Default::default()
                },
                WindowAction::Ignore,
            )],
            WindowAction::Tile,
        );
        let c = candidate("explorer.exe", "", "", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    #[test]
    fn pipeline_title_contains_case_sensitive() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    title_contains: Some("Open File".into()),
                    ..Default::default()
                },
                WindowAction::Ignore,
            )],
            WindowAction::Tile,
        );
        let c = candidate("explorer.exe", "Open File - Explorer", "", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    #[test]
    fn pipeline_title_contains_case_sensitive_mismatch() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    title_contains: Some("SETTINGS".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
            WindowAction::Tile,
        );
        let c = candidate("settings.exe", "Windows Settings", "", "");
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    #[test]
    fn pipeline_all_fields_and_logic() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("chrome.exe".into()),
                    class: Some("Chrome_WidgetWin_1".into()),
                    title: Some("New Tab - Google Chrome".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate(
            "chrome.exe",
            "New Tab - Google Chrome",
            "Chrome_WidgetWin_1",
            "C:\\Program Files\\Google\\Chrome\\chrome.exe",
        );
        assert_eq!(p.classify(&c), WindowAction::Tile);

        let c2 = candidate(
            "chrome.exe",
            "New Tab - Google Chrome",
            "SomeOtherClass",
            "",
        );
        assert_eq!(p.classify(&c2), WindowAction::Ignore);
    }

    #[test]
    fn pipeline_first_match_wins() {
        let p = pipeline_from(
            vec![
                rule(
                    MatchRule {
                        exe: Some("chrome.exe".into()),
                        ..Default::default()
                    },
                    WindowAction::Ignore,
                ),
                rule(
                    MatchRule {
                        exe: Some("chrome.exe".into()),
                        ..Default::default()
                    },
                    WindowAction::Tile,
                ),
            ],
            WindowAction::Float,
        );
        let c = candidate("chrome.exe", "", "", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    #[test]
    fn pipeline_default_action_when_no_rule_matches() {
        let p = pipeline_from(vec![], WindowAction::Tile);
        let c = candidate("unknown.exe", "Some Title", "", "");
        assert_eq!(p.classify(&c), WindowAction::Tile);

        let p2 = pipeline_from(vec![], WindowAction::Float);
        assert_eq!(p2.classify(&c), WindowAction::Float);
    }

    #[test]
    fn pipeline_window_candidate_with_empty_strings_no_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("notepad.exe".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("", "", "", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    #[test]
    fn pipeline_rule_with_all_fields_specified_matches() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("app.exe".into()),
                    title: Some("Main Window".into()),
                    class: Some("AppClass".into()),
                    process_path: Some("C:\\Apps\\app.exe".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
            WindowAction::Tile,
        );
        let c = candidate("app.exe", "Main Window", "AppClass", "C:\\Apps\\app.exe");
        assert_eq!(p.classify(&c), WindowAction::Float);
    }

    #[test]
    fn pipeline_rule_with_all_fields_specified_partial_mismatch() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("app.exe".into()),
                    title: Some("Main Window".into()),
                    class: Some("AppClass".into()),
                    process_path: Some("C:\\Apps\\app.exe".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
            WindowAction::Tile,
        );
        let c = candidate("app.exe", "Main Window", "AppClass", "D:\\Other\\app.exe");
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    // --- matches_rule field-specific tests ---

    #[test]
    fn title_exact_case_sensitive() {
        let rule = MatchRule {
            title: Some("Calculator".into()),
            ..Default::default()
        };
        let c = candidate("calc.exe", "Calculator", "", "");
        assert!(matches_rule(&c, &rule));

        let c2 = candidate("calc.exe", "calculator", "", "");
        assert!(!matches_rule(&c2, &rule));
    }

    #[test]
    fn class_exact_case_sensitive() {
        let rule = MatchRule {
            class: Some("Chrome_WidgetWin_1".into()),
            ..Default::default()
        };
        let c = candidate("chrome.exe", "", "Chrome_WidgetWin_1", "");
        assert!(matches_rule(&c, &rule));

        let c2 = candidate("chrome.exe", "", "chrome_widgetwin_1", "");
        assert!(!matches_rule(&c2, &rule));
    }

    #[test]
    fn process_path_case_insensitive() {
        let rule = MatchRule {
            process_path: Some("C:\\Windows\\System32\\calc.exe".into()),
            ..Default::default()
        };
        let c = candidate("calc.exe", "", "", "C:\\Windows\\System32\\calc.exe");
        assert!(matches_rule(&c, &rule));

        // Case-insensitive: Calc.exe should match calc.exe
        let c2 = candidate("calc.exe", "", "", "C:\\Windows\\System32\\Calc.exe");
        assert!(matches_rule(&c2, &rule));
    }

    #[test]
    fn title_regex_matches() {
        let rule = MatchRule {
            title_regex: Some("^Settings".into()),
            ..Default::default()
        };
        let c = candidate("settings.exe", "Settings - Display", "", "");
        assert!(matches_rule(&c, &rule));

        let c2 = candidate("explorer.exe", "Windows Settings", "", "");
        assert!(!matches_rule(&c2, &rule));
    }

    #[test]
    fn exe_regex_matches_case_insensitive() {
        let rule = MatchRule {
            exe_regex: Some("chrome\\.exe".into()),
            ..Default::default()
        };
        let c = candidate("chrome.exe", "", "", "");
        assert!(matches_rule(&c, &rule));

        let c2 = candidate("Chrome.EXE", "", "", "");
        assert!(matches_rule(&c2, &rule));
    }

    #[test]
    fn class_regex_matches() {
        let rule = MatchRule {
            class_regex: Some("Chrome.*".into()),
            ..Default::default()
        };
        let c = candidate("chrome.exe", "", "Chrome_WidgetWin_1", "");
        assert!(matches_rule(&c, &rule));

        let c2 = candidate("chrome.exe", "", "chrome_widgetwin_1", "");
        // Case-sensitive: lowercase shouldn't match "Chrome.*"
        assert!(!matches_rule(&c2, &rule));
    }

    #[test]
    fn process_path_regex_matches_case_insensitive() {
        let rule = MatchRule {
            process_path_regex: Some(".*\\\\Google\\\\Chrome\\\\.*".into()),
            ..Default::default()
        };
        let c = candidate(
            "chrome.exe",
            "",
            "",
            "C:\\Program Files\\Google\\Chrome\\chrome.exe",
        );
        assert!(matches_rule(&c, &rule));

        let c2 = candidate(
            "chrome.exe",
            "",
            "",
            "c:\\program files\\google\\chrome\\chrome.exe",
        );
        // Case-insensitive: lowercase path should still match
        assert!(matches_rule(&c2, &rule));
    }

    #[test]
    fn invalid_title_regex_returns_false() {
        let rule = MatchRule {
            title_regex: Some("[invalid(".into()),
            ..Default::default()
        };
        let c = candidate("test.exe", "anything", "", "");
        // Invalid regex should return false, not panic
        assert!(!matches_rule(&c, &rule));
    }

    /// Negative: invalid `exe_regex` pattern logs a warning and is treated as non-match.
    #[test]
    fn invalid_exe_regex_returns_false() {
        let rule = MatchRule {
            exe_regex: Some("[invalid(".into()),
            ..Default::default()
        };
        let c = candidate("test.exe", "", "", "");
        assert!(!matches_rule(&c, &rule));
    }

    /// Negative: invalid `class_regex` pattern logs a warning and is treated as non-match.
    #[test]
    fn invalid_class_regex_returns_false() {
        let rule = MatchRule {
            class_regex: Some("[invalid(".into()),
            ..Default::default()
        };
        let c = candidate("test.exe", "", "SomeClass", "");
        assert!(!matches_rule(&c, &rule));
    }

    /// Negative: invalid `process_path_regex` pattern logs a warning and is treated as non-match.
    #[test]
    fn invalid_process_path_regex_returns_false() {
        let rule = MatchRule {
            process_path_regex: Some("[invalid(".into()),
            ..Default::default()
        };
        let c = candidate("test.exe", "", "", "C:\\path\\test.exe");
        assert!(!matches_rule(&c, &rule));
    }

    /// Positive: `(?i)` inline flag in `class_regex` overrides default case-sensitive behavior.
    ///
    /// `class_regex` is case-sensitive by default. The `(?i)` inline flag allows
    /// users to opt into case-insensitive matching for specific patterns.
    #[test]
    fn class_regex_inline_flag_i_overrides_case_sensitivity() {
        let rule = MatchRule {
            class_regex: Some("(?i)chrome_widgetwin_1".into()),
            ..Default::default()
        };
        // Without (?i), this lowercase string would NOT match (class_regex is
        // case-sensitive). With (?i), it should match.
        let c = candidate("chrome.exe", "", "chrome_widgetwin_1", "");
        assert!(
            matches_rule(&c, &rule),
            "(?i) should make class_regex case-insensitive"
        );

        // Also verify uppercase input matches.
        let c2 = candidate("chrome.exe", "", "CHROME_WIDGETWIN_1", "");
        assert!(matches_rule(&c2, &rule), "(?i) should match uppercase too");
    }

    /// Positive: `(?-i)` inline flag in `exe_regex` opts into case-sensitive matching.
    ///
    /// `exe_regex` is case-insensitive by default. The `(?-i)` inline flag allows
    /// users to opt into case-sensitive matching for specific patterns.
    #[test]
    fn exe_regex_inline_flag_neg_i_opts_into_case_sensitive() {
        let rule = MatchRule {
            exe_regex: Some("(?-i)Chrome.exe".into()),
            ..Default::default()
        };
        // Exact case should match.
        let c = candidate("Chrome.exe", "", "", "");
        assert!(
            matches_rule(&c, &rule),
            "exact case should match with (?-i)"
        );

        // Different case should NOT match (case-sensitive now).
        let c2 = candidate("chrome.exe", "", "", "");
        assert!(
            !matches_rule(&c2, &rule),
            "different case should not match with (?-i)"
        );
    }

    #[test]
    fn unspecified_fields_ignored() {
        let rule = MatchRule {
            exe: Some("code.exe".into()),
            ..Default::default()
        };
        let c = candidate("code.exe", "", "", "");
        assert!(matches_rule(&c, &rule));
    }

    // --- classify_with_state_pipeline tests ---

    #[test]
    fn classify_with_state_pipeline_maximized_override() {
        let pipeline = pipeline_from(vec![], WindowAction::Tile);
        let c = candidate("code.exe", "main.rs", "", "");
        let state = classify_with_state_pipeline(&c, true, false, &pipeline);
        assert!(matches!(
            state,
            WindowState::Ignored(IgnoredReason::Maximized)
        ));
    }

    #[test]
    fn classify_with_state_pipeline_fullscreen_override() {
        let pipeline = pipeline_from(vec![], WindowAction::Tile);
        let c = candidate("game.exe", "Game", "", "");
        let state = classify_with_state_pipeline(&c, false, true, &pipeline);
        assert!(matches!(
            state,
            WindowState::Ignored(IgnoredReason::Fullscreen)
        ));
    }

    #[test]
    fn classify_with_state_pipeline_maximize_takes_precedence_over_fullscreen() {
        let pipeline = pipeline_from(vec![], WindowAction::Tile);
        let c = candidate("code.exe", "", "", "");
        let state = classify_with_state_pipeline(&c, true, true, &pipeline);
        assert!(matches!(
            state,
            WindowState::Ignored(IgnoredReason::Maximized)
        ));
    }

    #[test]
    fn classify_with_state_pipeline_tile_action() {
        let pipeline = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("code.exe".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("code.exe", "", "", "");
        let state = classify_with_state_pipeline(&c, false, false, &pipeline);
        assert!(matches!(
            state,
            WindowState::Tiling(TilingState::Active { col: 0, row: 0 })
        ));
    }

    #[test]
    fn classify_with_state_pipeline_float_action() {
        let pipeline = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("steam.exe".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
            WindowAction::Tile,
        );
        let c = candidate("steam.exe", "", "", "");
        let state = classify_with_state_pipeline(&c, false, false, &pipeline);
        assert!(matches!(
            state,
            WindowState::Floating(FloatingState::Active { rect: _ })
        ));
    }

    #[test]
    fn classify_with_state_pipeline_ignore_action() {
        let pipeline = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("explorer.exe".into()),
                    ..Default::default()
                },
                WindowAction::Ignore,
            )],
            WindowAction::Tile,
        );
        let c = candidate("explorer.exe", "", "", "");
        let state = classify_with_state_pipeline(&c, false, false, &pipeline);
        assert!(matches!(
            state,
            WindowState::Ignored(IgnoredReason::ExplicitRule)
        ));
    }

    #[test]
    fn classify_with_state_pipeline_default_used() {
        let pipeline = pipeline_from(vec![], WindowAction::Tile);
        let c = candidate("unknown.exe", "", "", "");
        let state = classify_with_state_pipeline(&c, false, false, &pipeline);
        assert!(matches!(
            state,
            WindowState::Tiling(TilingState::Active { col: 0, row: 0 })
        ));
    }

    #[test]
    fn classify_with_state_pipeline_empty_candidate() {
        let pipeline = pipeline_from(vec![], WindowAction::Tile);
        let c = candidate("", "", "", "");
        let state = classify_with_state_pipeline(&c, false, false, &pipeline);
        assert!(matches!(
            state,
            WindowState::Tiling(TilingState::Active { col: 0, row: 0 })
        ));
    }

    // --- action_to_state tests ---

    #[test]
    fn action_to_state_tile() {
        let state = action_to_state(WindowAction::Tile);
        assert!(matches!(
            state,
            WindowState::Tiling(TilingState::Active { col: 0, row: 0 })
        ));
    }

    #[test]
    fn action_to_state_float() {
        let state = action_to_state(WindowAction::Float);
        assert!(matches!(
            state,
            WindowState::Floating(FloatingState::Active {
                rect: Rect {
                    x: 0,
                    y: 0,
                    width: 0,
                    height: 0
                }
            })
        ));
    }

    #[test]
    fn action_to_state_ignore() {
        let state = action_to_state(WindowAction::Ignore);
        assert!(matches!(
            state,
            WindowState::Ignored(IgnoredReason::ExplicitRule)
        ));
    }

    // --- ClassificationPipeline multi-layer tests ---

    #[test]
    fn pipeline_user_rule_takes_priority_over_default() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![rule(
                MatchRule {
                    exe: Some("chrome.exe".into()),
                    ..Default::default()
                },
                WindowAction::Ignore,
            )],
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![rule(
                MatchRule {
                    exe: Some("chrome.exe".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
        };

        let pipeline = ClassificationPipeline::new(user_rules, default_rules);
        let c = candidate("chrome.exe", "", "", "");
        // User rule should win over default rule
        assert_eq!(pipeline.classify(&c), WindowAction::Ignore);
    }

    #[test]
    fn pipeline_falls_through_to_default_rules() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![], // No user rules match
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![rule(
                MatchRule {
                    exe: Some("firefox.exe".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
        };

        let pipeline = ClassificationPipeline::new(user_rules, default_rules);
        let c = candidate("firefox.exe", "", "", "");
        assert_eq!(pipeline.classify(&c), WindowAction::Float);
    }

    #[test]
    fn pipeline_falls_through_to_default_action() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Float,
            rules: vec![],
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![],
        };

        let pipeline = ClassificationPipeline::new(user_rules, default_rules);
        let c = candidate("unknown.exe", "", "", "");
        // Should use user's default_action (Float)
        assert_eq!(pipeline.classify(&c), WindowAction::Float);
    }

    // --- Pipeline learned rules slot tests ---

    /// The pipeline's learned rules layer is initially empty — when user rules
    /// don't match and default rules don't match, the pipeline falls through to
    /// default_action even though a learned layer exists (it's empty).
    ///
    /// This test documents that the pipeline has 4 layers (user → learned →
    /// default → fallback) and that the learned layer is a no-op until
    /// populated via `set_learned_rules`.
    #[test]
    fn pipeline_learned_rules_slot_is_noop_when_empty() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Float,
            rules: vec![],
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![],
        };

        let pipeline = ClassificationPipeline::new(user_rules, default_rules);
        let c = candidate("anything.exe", "", "", "");
        // No rules at any layer → should fall through to user's default_action.
        assert_eq!(pipeline.classify(&c), WindowAction::Float);
    }

    /// Positive: `set_learned_rules` compiles and installs rules so that
    /// a matching candidate is classified using the learned layer.
    #[test]
    fn set_learned_rules_classifies_with_learned_rule() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![],
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![],
        };

        let mut pipeline = ClassificationPipeline::new(user_rules, default_rules);
        pipeline.set_learned_rules(vec![rule(
            MatchRule {
                exe: Some("test.exe".into()),
                ..Default::default()
            },
            WindowAction::Float,
        )]);

        let c = candidate("test.exe", "", "", "");
        assert_eq!(
            pipeline.classify(&c),
            WindowAction::Float,
            "learned rule should classify test.exe as Float"
        );
    }

    /// Priority: user rules beat learned rules for the same candidate.
    #[test]
    fn set_learned_rules_user_rules_still_win() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![rule(
                MatchRule {
                    exe: Some("test.exe".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![],
        };

        let mut pipeline = ClassificationPipeline::new(user_rules, default_rules);
        pipeline.set_learned_rules(vec![rule(
            MatchRule {
                exe: Some("test.exe".into()),
                ..Default::default()
            },
            WindowAction::Float,
        )]);

        let c = candidate("test.exe", "", "", "");
        assert_eq!(
            pipeline.classify(&c),
            WindowAction::Tile,
            "user rules should take priority over learned rules"
        );
    }

    /// Priority: learned rules beat default rules for the same candidate.
    #[test]
    fn set_learned_rules_beats_default_rules() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![],
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![rule(
                MatchRule {
                    exe: Some("test.exe".into()),
                    ..Default::default()
                },
                WindowAction::Ignore,
            )],
        };

        let mut pipeline = ClassificationPipeline::new(user_rules, default_rules);
        pipeline.set_learned_rules(vec![rule(
            MatchRule {
                exe: Some("test.exe".into()),
                ..Default::default()
            },
            WindowAction::Float,
        )]);

        let c = candidate("test.exe", "", "", "");
        assert_eq!(
            pipeline.classify(&c),
            WindowAction::Float,
            "learned rules should take priority over default rules"
        );
    }

    /// Replacement: calling `set_learned_rules` twice fully replaces, not appends.
    #[test]
    fn set_learned_rules_replaces_previous() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![],
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![],
        };

        let mut pipeline = ClassificationPipeline::new(user_rules, default_rules);

        // First call: Float
        pipeline.set_learned_rules(vec![rule(
            MatchRule {
                exe: Some("test.exe".into()),
                ..Default::default()
            },
            WindowAction::Float,
        )]);
        let c = candidate("test.exe", "", "", "");
        assert_eq!(pipeline.classify(&c), WindowAction::Float);

        // Second call: Tile (same exe, different action)
        pipeline.set_learned_rules(vec![rule(
            MatchRule {
                exe: Some("test.exe".into()),
                ..Default::default()
            },
            WindowAction::Tile,
        )]);
        assert_eq!(
            pipeline.classify(&c),
            WindowAction::Tile,
            "second set_learned_rules should fully replace the first"
        );
    }

    /// Regression: verify that the pipeline with both user and default rules
    /// that are BOTH empty still produces the correct default_action.
    #[test]
    fn pipeline_empty_user_and_default_returns_user_default_action() {
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![],
        };
        let default_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![],
        };

        let pipeline = ClassificationPipeline::new(user_rules, default_rules);
        let c = candidate("unknown.exe", "Some Title", "SomeClass", "");
        assert_eq!(pipeline.classify(&c), WindowAction::Ignore);
    }

    // --- Pipeline with real embedded default rules (phase 3 integration) ---

    /// End-to-end: the classification pipeline uses the real embedded default
    /// rules (from [`crate::config::lifecycle::load_default_rules`]) when user
    /// rules don't match.
    ///
    /// This is the critical regression test for the bug fix that embedded
    /// `default-flow-rules.toml` at compile time. Before the fix, the default
    /// rules layer was empty during development (file not found next to exe),
    /// so phase 3 of the pipeline matched nothing. This test:
    ///
    /// 1. Builds a pipeline with **empty user rules** and the **real embedded
    ///    defaults** from `load_default_rules()`.
    /// 2. Classifies a `Shell_TrayWnd` window (the Windows taskbar).
    /// 3. Verifies the pipeline reaches phase 3 (default rules) and returns
    ///    `Ignore` — proving the embedded defaults are actually consulted.
    ///
    /// Also verifies user rules still take priority: a user rule for
    /// `Shell_TrayWnd` with action `Tile` should override the default
    /// `Ignore`.
    #[test]
    fn pipeline_embedded_default_rules_classify_taskbar_as_ignore() {
        use crate::config::lifecycle::load_default_rules;

        // Arrange: pipeline with empty user rules + real embedded defaults.
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![],
        };
        let default_rules = load_default_rules();

        let pipeline = ClassificationPipeline::new(user_rules, default_rules);

        // Act: classify a Shell_TrayWnd window (Windows taskbar).
        let taskbar = candidate("explorer.exe", "", "Shell_TrayWnd", "");

        // Assert: phase 3 default rules should match → Ignore.
        assert_eq!(
            pipeline.classify(&taskbar),
            WindowAction::Ignore,
            "embedded default rules should classify Shell_TrayWnd as Ignore"
        );
    }

    /// End-to-end: user rules take priority over the real embedded default
    /// rules for the same window.
    ///
    /// This proves that phase 3 (default rules) is correctly bypassed when
    /// a user rule matches first. Uses the real embedded defaults loaded by
    /// [`crate::config::lifecycle::load_default_rules`].
    #[test]
    fn pipeline_user_rule_overrides_embedded_default_for_taskbar() {
        use crate::config::lifecycle::load_default_rules;

        // Arrange: user rule overrides the default Shell_TrayWnd → Ignore
        // classification with Tile (contrived but proves priority).
        let user_rules = WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![rule(
                MatchRule {
                    class: Some("Shell_TrayWnd".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
        };
        let default_rules = load_default_rules();

        let pipeline = ClassificationPipeline::new(user_rules, default_rules);

        // Act: classify a Shell_TrayWnd window.
        let taskbar = candidate("explorer.exe", "", "Shell_TrayWnd", "");

        // Assert: user rule (Tile) should win over default rule (Ignore).
        assert_eq!(
            pipeline.classify(&taskbar),
            WindowAction::Tile,
            "user rule should override embedded default for Shell_TrayWnd"
        );
    }

    // --- Pipeline regex rule tests (pre-compiled via ClassificationPipeline) ---

    /// Positive: pipeline classifies correctly when `exe_regex` is used.
    ///
    /// Verifies that pre-compiled regex patterns work through the pipeline's
    /// [`CompiledRule`] path, not just the runtime [`matches_rule`] path.
    #[test]
    fn pipeline_exe_regex_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe_regex: Some("chrome\\.exe".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("chrome.exe", "", "", "");
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    /// Positive: `exe_regex` is case-insensitive by default through the pipeline.
    #[test]
    fn pipeline_exe_regex_case_insensitive() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe_regex: Some("CHROME\\.EXE".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("chrome.exe", "", "", "");
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    /// Negative: `exe_regex` that doesn't match falls through to default action.
    #[test]
    fn pipeline_exe_regex_mismatch_falls_through() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe_regex: Some("firefox\\.exe".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("chrome.exe", "", "", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    /// Positive: pipeline classifies correctly when `title_regex` is used.
    #[test]
    fn pipeline_title_regex_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    title_regex: Some("^Settings".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
            WindowAction::Tile,
        );
        let c = candidate("settings.exe", "Settings - Display", "", "");
        assert_eq!(p.classify(&c), WindowAction::Float);
    }

    /// Negative: `title_regex` is case-sensitive — lowercase won't match `^Settings`.
    #[test]
    fn pipeline_title_regex_case_sensitive_mismatch() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    title_regex: Some("^Settings".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
            WindowAction::Tile,
        );
        let c = candidate("settings.exe", "settings - display", "", "");
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    /// Positive: pipeline classifies correctly when `class_regex` is used.
    #[test]
    fn pipeline_class_regex_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    class_regex: Some("Chrome.*".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("chrome.exe", "", "Chrome_WidgetWin_1", "");
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    /// Negative: `class_regex` is case-sensitive — lowercase won't match `Chrome.*`.
    #[test]
    fn pipeline_class_regex_case_sensitive_mismatch() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    class_regex: Some("Chrome.*".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("chrome.exe", "", "chrome_widgetwin_1", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    /// Positive: pipeline classifies correctly when `process_path_regex` is used.
    #[test]
    fn pipeline_process_path_regex_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    process_path_regex: Some(".*\\\\Google\\\\Chrome\\\\.*".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate(
            "chrome.exe",
            "",
            "",
            "C:\\Program Files\\Google\\Chrome\\chrome.exe",
        );
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    /// Positive: `process_path_regex` is case-insensitive by default.
    #[test]
    fn pipeline_process_path_regex_case_insensitive() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    process_path_regex: Some(".*\\\\google\\\\chrome\\\\.*".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate(
            "chrome.exe",
            "",
            "",
            "C:\\Program Files\\Google\\Chrome\\chrome.exe",
        );
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    /// Negative: `process_path_regex` that doesn't match falls through.
    #[test]
    fn pipeline_process_path_regex_mismatch_falls_through() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    process_path_regex: Some(".*\\\\Firefox\\\\.*".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate(
            "chrome.exe",
            "",
            "",
            "C:\\Program Files\\Google\\Chrome\\chrome.exe",
        );
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    // --- Pipeline with invalid regex patterns (pre-compiled) ---

    /// Negative: invalid `exe_regex` pattern in pipeline is treated as non-match,
    /// not a panic. The regex is pre-compiled at pipeline construction time.
    #[test]
    fn pipeline_invalid_exe_regex_treated_as_non_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe_regex: Some("[invalid(".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("anything.exe", "", "", "");
        // Invalid regex → CompiledRegex::Invalid → non-match → falls through
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    /// Negative: invalid `title_regex` pattern in pipeline is treated as non-match.
    #[test]
    fn pipeline_invalid_title_regex_treated_as_non_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    title_regex: Some("[invalid(".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("anything.exe", "Some Title", "", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    /// Negative: invalid `class_regex` pattern in pipeline is treated as non-match.
    #[test]
    fn pipeline_invalid_class_regex_treated_as_non_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    class_regex: Some("[invalid(".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("anything.exe", "", "SomeClass", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    /// Negative: invalid `process_path_regex` pattern in pipeline is treated as non-match.
    #[test]
    fn pipeline_invalid_process_path_regex_treated_as_non_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    process_path_regex: Some("[invalid(".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("anything.exe", "", "", "C:\\path\\anything.exe");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    /// Negative: rule with ALL regex fields invalid still falls through gracefully.
    #[test]
    fn pipeline_all_invalid_regex_fields_treated_as_non_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe_regex: Some("[bad[".into()),
                    title_regex: Some("(?broken".into()),
                    class_regex: Some("[[[".into()),
                    process_path_regex: Some("*invalid".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("test.exe", "Title", "Class", "C:\\path\\test.exe");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    // --- Pipeline with mixed exact + regex fields in a single rule ---

    /// Positive: rule with both exact (`exe`) and regex (`title_regex`) fields
    /// matches when both conditions are satisfied.
    #[test]
    fn pipeline_mixed_exact_and_regex_both_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("code.exe".into()),
                    title_regex: Some(".*\\.rs - .+".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("code.exe", "main.rs - My Project", "", "");
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    /// Negative: rule with both exact and regex fields fails when exact matches
    /// but regex doesn't (AND logic).
    #[test]
    fn pipeline_mixed_exact_and_regex_regex_mismatch() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("code.exe".into()),
                    title_regex: Some(".*\\.rs - .+".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("code.exe", "settings.json - My Project", "", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    /// Negative: rule with both exact and regex fields fails when regex matches
    /// but exact doesn't (AND logic).
    #[test]
    fn pipeline_mixed_exact_and_regex_exact_mismatch() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("code.exe".into()),
                    title_regex: Some(".*\\.rs - .+".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate("other.exe", "main.rs - My Project", "", "");
        assert_eq!(p.classify(&c), WindowAction::Ignore);
    }

    /// Positive: rule combining all four regex fields with two exact fields
    /// matches when every condition is satisfied.
    #[test]
    fn pipeline_all_regex_fields_plus_exact_match() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("chrome.exe".into()),
                    title_regex: Some("New Tab.*".into()),
                    exe_regex: Some("chrome\\.exe".into()),
                    class_regex: Some("Chrome_WidgetWin_\\d+".into()),
                    process_path_regex: Some(".*\\\\Chrome\\\\.*".into()),
                    ..Default::default()
                },
                WindowAction::Tile,
            )],
            WindowAction::Ignore,
        );
        let c = candidate(
            "chrome.exe",
            "New Tab - Google Chrome",
            "Chrome_WidgetWin_1",
            "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
        );
        assert_eq!(p.classify(&c), WindowAction::Tile);
    }

    /// Positive: rule with `title_contains` (exact substring) AND `class_regex`
    /// matches when both are satisfied.
    #[test]
    fn pipeline_mixed_title_contains_and_class_regex() {
        let p = pipeline_from(
            vec![rule(
                MatchRule {
                    title_contains: Some("Visual Studio Code".into()),
                    class_regex: Some("Chrome_WidgetWin_1".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
            WindowAction::Tile,
        );
        let c = candidate(
            "code.exe",
            "main.rs - Visual Studio Code",
            "Chrome_WidgetWin_1",
            "",
        );
        assert_eq!(p.classify(&c), WindowAction::Float);
    }

    // --- Equivalence: matches_compiled_rule == matches_rule for regex fields ---

    /// Helper to compile a single rule and compare `matches_rule` vs
    /// `matches_compiled_rule`. Returns `true` if both produce the same result.
    fn check_equivalence(match_rule: &MatchRule, c: &WindowCandidate) -> bool {
        let r = rule(match_rule.clone(), WindowAction::Tile);
        let compiled_rules = compile_rules(vec![r]);
        assert_eq!(
            compiled_rules.len(),
            1,
            "compile_rules should return exactly 1 rule"
        );

        let runtime = matches_rule(c, match_rule);
        let compiled = matches_compiled_rule(c, &compiled_rules[0]);
        runtime == compiled
    }

    /// Equivalence: `exe_regex` produces identical results from both paths.
    #[test]
    fn equivalence_exe_regex_positive() {
        let mr = MatchRule {
            exe_regex: Some("chrome\\.exe".into()),
            ..Default::default()
        };
        let c = candidate("chrome.exe", "", "", "");
        assert!(check_equivalence(&mr, &c));
        assert!(matches_rule(&c, &mr), "guard: should match");
    }

    #[test]
    fn equivalence_exe_regex_negative() {
        let mr = MatchRule {
            exe_regex: Some("firefox\\.exe".into()),
            ..Default::default()
        };
        let c = candidate("chrome.exe", "", "", "");
        assert!(check_equivalence(&mr, &c));
        assert!(!matches_rule(&c, &mr), "guard: should not match");
    }

    #[test]
    fn equivalence_exe_regex_case_insensitive() {
        let mr = MatchRule {
            exe_regex: Some("CHROME\\.EXE".into()),
            ..Default::default()
        };
        let c = candidate("chrome.exe", "", "", "");
        assert!(check_equivalence(&mr, &c));
        assert!(
            matches_rule(&c, &mr),
            "guard: case-insensitive should match"
        );
    }

    /// Equivalence: `title_regex` produces identical results from both paths.
    #[test]
    fn equivalence_title_regex_positive() {
        let mr = MatchRule {
            title_regex: Some("^Settings.*".into()),
            ..Default::default()
        };
        let c = candidate("app.exe", "Settings - Display", "", "");
        assert!(check_equivalence(&mr, &c));
        assert!(matches_rule(&c, &mr), "guard: should match");
    }

    #[test]
    fn equivalence_title_regex_negative() {
        let mr = MatchRule {
            title_regex: Some("^Settings.*".into()),
            ..Default::default()
        };
        let c = candidate("app.exe", "Display - Settings", "", "");
        assert!(check_equivalence(&mr, &c));
        assert!(
            !matches_rule(&c, &mr),
            "guard: should not match (not at start)"
        );
    }

    /// Equivalence: `class_regex` produces identical results from both paths.
    #[test]
    fn equivalence_class_regex_positive() {
        let mr = MatchRule {
            class_regex: Some("Chrome_WidgetWin_\\d+".into()),
            ..Default::default()
        };
        let c = candidate("chrome.exe", "", "Chrome_WidgetWin_1", "");
        assert!(check_equivalence(&mr, &c));
        assert!(matches_rule(&c, &mr), "guard: should match");
    }

    #[test]
    fn equivalence_class_regex_negative() {
        let mr = MatchRule {
            class_regex: Some("Chrome_WidgetWin_\\d+".into()),
            ..Default::default()
        };
        let c = candidate("chrome.exe", "", "Chrome_WidgetWin_", "");
        assert!(check_equivalence(&mr, &c));
        assert!(!matches_rule(&c, &mr), "guard: should not match (no digit)");
    }

    /// Equivalence: `process_path_regex` produces identical results from both paths.
    #[test]
    fn equivalence_process_path_regex_positive() {
        let mr = MatchRule {
            process_path_regex: Some(".*\\\\Chrome\\\\.*".into()),
            ..Default::default()
        };
        let c = candidate(
            "chrome.exe",
            "",
            "",
            "C:\\Program Files\\Chrome\\chrome.exe",
        );
        assert!(check_equivalence(&mr, &c));
        assert!(matches_rule(&c, &mr), "guard: should match");
    }

    #[test]
    fn equivalence_process_path_regex_negative() {
        let mr = MatchRule {
            process_path_regex: Some(".*\\\\Chrome\\\\.*".into()),
            ..Default::default()
        };
        let c = candidate(
            "chrome.exe",
            "",
            "",
            "C:\\Program Files\\Firefox\\firefox.exe",
        );
        assert!(check_equivalence(&mr, &c));
        assert!(!matches_rule(&c, &mr), "guard: should not match");
    }

    #[test]
    fn equivalence_process_path_regex_case_insensitive() {
        let mr = MatchRule {
            process_path_regex: Some(".*\\\\chrome\\\\.*".into()),
            ..Default::default()
        };
        let c = candidate(
            "chrome.exe",
            "",
            "",
            "C:\\Program Files\\Chrome\\chrome.exe",
        );
        assert!(check_equivalence(&mr, &c));
        assert!(
            matches_rule(&c, &mr),
            "guard: case-insensitive should match"
        );
    }

    /// Equivalence: invalid regex patterns produce `false` from both paths.
    #[test]
    fn equivalence_invalid_regex_both_return_false() {
        let mr = MatchRule {
            exe_regex: Some("[invalid(".into()),
            ..Default::default()
        };
        let c = candidate("test.exe", "", "", "");
        assert!(check_equivalence(&mr, &c));
        assert!(
            !matches_rule(&c, &mr),
            "guard: invalid regex should return false"
        );
    }

    /// Equivalence: all regex fields invalid still produces same result from both paths.
    #[test]
    fn equivalence_all_invalid_regex_fields_both_return_false() {
        let mr = MatchRule {
            exe_regex: Some("[bad[".into()),
            title_regex: Some("(?broken".into()),
            class_regex: Some("[[[".into()),
            process_path_regex: Some("*invalid".into()),
            ..Default::default()
        };
        let c = candidate("test.exe", "Title", "Class", "C:\\path\\test.exe");
        assert!(check_equivalence(&mr, &c));
        assert!(!matches_rule(&c, &mr), "guard: all invalid → false");
    }

    /// Equivalence: mixed exact + regex fields produce identical results.
    #[test]
    fn equivalence_mixed_exact_and_regex_both_match() {
        let mr = MatchRule {
            exe: Some("code.exe".into()),
            title_regex: Some(".*\\.rs - .+".into()),
            ..Default::default()
        };
        let c = candidate("code.exe", "main.rs - My Project", "", "");
        assert!(check_equivalence(&mr, &c));
        assert!(matches_rule(&c, &mr), "guard: both fields match");
    }

    #[test]
    fn equivalence_mixed_exact_and_regex_partial_mismatch() {
        let mr = MatchRule {
            exe: Some("code.exe".into()),
            title_regex: Some(".*\\.rs - .+".into()),
            ..Default::default()
        };
        // exe matches but title_regex doesn't
        let c = candidate("code.exe", "settings.json - My Project", "", "");
        assert!(check_equivalence(&mr, &c));
        assert!(!matches_rule(&c, &mr), "guard: AND logic → false");
    }

    /// Equivalence: comprehensive rule with all fields specified produces
    /// identical results from both `matches_rule` and `matches_compiled_rule`.
    #[test]
    fn equivalence_comprehensive_all_fields() {
        let mr = MatchRule {
            exe: Some("chrome.exe".into()),
            exe_regex: Some("chrome\\.exe".into()),
            title: Some("New Tab - Google Chrome".into()),
            title_contains: Some("New Tab".into()),
            title_regex: Some("New Tab.*Chrome".into()),
            class: Some("Chrome_WidgetWin_1".into()),
            class_regex: Some("Chrome_WidgetWin_\\d+".into()),
            process_path: Some("C:\\Program Files\\Google\\Chrome\\chrome.exe".into()),
            process_path_regex: Some(".*\\\\Chrome\\\\.*".into()),
        };
        let c = candidate(
            "chrome.exe",
            "New Tab - Google Chrome",
            "Chrome_WidgetWin_1",
            "C:\\Program Files\\Google\\Chrome\\chrome.exe",
        );
        assert!(check_equivalence(&mr, &c));
        assert!(matches_rule(&c, &mr), "guard: all fields should match");
    }

    // --- set_user_rules (hot-reload) tests ---

    /// Positive: `set_user_rules` MUST refresh the fallback `default_action`.
    /// After reload, an unmatched candidate classifies via the NEW
    /// `default_action`, proving the field was replaced (not just the rule list).
    #[test]
    fn set_user_rules_replaces_default_action() {
        // Arrange: pipeline starts with default_action = Tile, no rules.
        let mut pipeline = pipeline_from(vec![], WindowAction::Tile);
        let unknown = candidate("unknown.exe", "", "", "");
        // Guard: initial fallback is Tile.
        assert_eq!(pipeline.classify(&unknown), WindowAction::Tile);

        // Act: hot-reload user rules with a different default_action and no rules.
        pipeline.set_user_rules(WindowRulesConfig {
            default_action: WindowAction::Float,
            rules: vec![],
        });

        // Assert: fallback now reflects the reloaded default_action.
        assert_eq!(
            pipeline.classify(&unknown),
            WindowAction::Float,
            "set_user_rules must refresh default_action"
        );
    }

    /// Positive + negative: `set_user_rules` REPLACES (not appends to) the
    /// user-rule list. After reload, a candidate matching a NEW rule classifies
    /// via it, and a candidate that matched only an OLD rule no longer matches
    /// (it falls through to `default_action`).
    #[test]
    fn set_user_rules_replaces_the_user_rule_list() {
        // Arrange: pipeline starts with one rule: "old.exe" → Ignore.
        let mut pipeline = pipeline_from(
            vec![rule(
                MatchRule {
                    exe: Some("old.exe".into()),
                    ..Default::default()
                },
                WindowAction::Ignore,
            )],
            WindowAction::Tile,
        );
        // Guard: the old rule is active before reload.
        assert_eq!(
            pipeline.classify(&candidate("old.exe", "", "", "")),
            WindowAction::Ignore
        );

        // Act: hot-reload user rules with a DIFFERENT rule: "new.exe" → Float.
        pipeline.set_user_rules(WindowRulesConfig {
            default_action: WindowAction::Tile,
            rules: vec![rule(
                MatchRule {
                    exe: Some("new.exe".into()),
                    ..Default::default()
                },
                WindowAction::Float,
            )],
        });

        // Assert (positive): the new rule classifies "new.exe" as Float.
        assert_eq!(
            pipeline.classify(&candidate("new.exe", "", "", "")),
            WindowAction::Float,
            "set_user_rules must install the reloaded rule list"
        );
        // Assert (negative): the old rule is GONE — "old.exe" falls through.
        assert_eq!(
            pipeline.classify(&candidate("old.exe", "", "", "")),
            WindowAction::Tile,
            "set_user_rules must drop rules absent from the reload"
        );
    }
}