Source file tree_diff.ml

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
(** CSS tree difference analysis for structural comparison. *)

open Cascade

(* ===== Type Definitions ===== *)

type declaration = {
  property_name : string;
  expected_value : string;
  actual_value : string;
}

type rule_diff =
  | Added of { selector : string; declarations : Css.declaration list }
  | Removed of { selector : string; declarations : Css.declaration list }
  | Content_changed of {
      selector : string;
      old_declarations : Css.declaration list;
      new_declarations : Css.declaration list;
      property_changes : declaration list;
      added_properties : string list;
      removed_properties : string list;
    }
  | Selector_changed of {
      old_selector : string;
      new_selector : string;
      declarations : Css.declaration list;
    }
  | Reordered of {
      selector : string;
      expected_pos : int;
      actual_pos : int;
      swapped_with : string option; (* Selector that moved to old position *)
      (* When only declarations order changed within the rule, we carry the
         before/after declarations to pretty-print a property reorder
         summary. *)
      old_declarations : Css.declaration list option;
      new_declarations : Css.declaration list option;
    }
  | Regrouped of {
      from_selectors : string list; (* rule selectors in expected *)
      to_selectors : string list; (* rule selectors in actual *)
    }
(* A comma group merged or split across rules with identical declarations: the
   same selectors survive, only the grouping differs. *)

type container_info = {
  container_type :
    [ `Media | `Layer | `Supports | `Container | `Property | `Nesting ];
  condition : string;
  rules : Css.statement list;
}

type container_diff =
  | Added of container_info
  | Removed of container_info
  | Modified of {
      info : container_info; (* expected *)
      actual_rules : Css.statement list; (* actual *)
      rule_changes : rule_diff list;
      container_changes : container_diff list; (* Nested container changes *)
    }
  | Reordered of { info : container_info; expected_pos : int; actual_pos : int }
  | Block_structure_changed of {
      container_type :
        [ `Media | `Layer | `Supports | `Container | `Property | `Nesting ];
      condition : string;
      expected_blocks : (int * Css.statement list) list;
          (** (position, rules) for each block in expected *)
      actual_blocks : (int * Css.statement list) list;
          (** (position, rules) for each block in actual *)
    }

type t = { rules : rule_diff list; containers : container_diff list }

(* ===== Constants ===== *)

let default_truncation_length = String_diff.default_max_width

(* ===== Helper Functions ===== *)

let is_empty d = d.rules = [] && d.containers = []

(* ===== Pretty Printing Functions ===== *)

(* Tree-style formatting helpers *)
type tree_style = {
  use_tree : bool; (* Whether to use tree-style box-drawing characters *)
  color : bool; (* Whether to wrap diff markers in ANSI colors *)
}

let default_style = { use_tree = false; color = false }
let tree_style = { use_tree = true; color = false }

(* ANSI color helpers. Plain text unless [color] is set: the printers write into
   a [Buffer.t], so tty detection cannot happen here; the caller decides. *)
let ansi code ~color s =
  if color then "\027[" ^ code ^ "m" ^ s ^ "\027[0m" else s

let ansi_green ~color s = ansi "32" ~color s
let ansi_red ~color s = ansi "31" ~color s
let ansi_yellow ~color s = ansi "33" ~color s

let style_text ~color action s =
  match action with
  | "add" -> ansi_green ~color s
  | "remove" -> ansi_red ~color s
  | _ -> s

(* Get the appropriate prefix for tree-style formatting *)
let tree_prefix ~style ~is_last ~parent_prefix =
  if not style.use_tree then ""
  else
    let connector = if is_last then "└─ " else "├─ " in
    parent_prefix ^ connector

(* Get the continuation prefix for children *)
let tree_continuation ~style ~is_last ~parent_prefix =
  if not style.use_tree then parent_prefix
  else
    let continuation = if is_last then "   " else "│  " in
    parent_prefix ^ continuation

(* Print a list of CSS declarations with an action prefix *)
let pp_declarations ?(style = default_style) ?(parent_prefix = "") buf action
    decls =
  let prefix_symbol =
    match action with
    | "add" -> "+"
    | "remove" -> "-"
    | _ -> action (* fallback for other actions like "declarations" *)
  in
  (* Properties don't get tree connectors - just indentation continuation *)
  let indent =
    if style.use_tree then parent_prefix ^ "   " else parent_prefix ^ "    "
  in
  List.iter
    (fun decl ->
      let prop_name = Css.declaration_name decl in
      (* Use non-minified values to preserve unit differences like 0px vs 0 *)
      let prop_value = Css.declaration_value ~minify:false decl in
      let truncated_value =
        String_diff.truncate_middle default_truncation_length prop_value
      in
      Buffer.add_string buf
        (indent
        ^ style_text ~color:style.color action
            (prefix_symbol ^ " " ^ prop_name ^ " " ^ truncated_value)
        ^ "\n"))
    decls

let pp_property_diff ?(style = default_style) ?(parent_prefix = "") buf
    { property_name; expected_value; actual_value } =
  let indent =
    if style.use_tree then parent_prefix ^ "   " else parent_prefix ^ "    "
  in
  match String_diff.first_diff_pos expected_value actual_value with
  | None ->
      (* Shouldn't happen but handle gracefully *)
      Buffer.add_string buf
        (indent ^ "* " ^ property_name ^ ": (no diff detected)\n")
  | Some _ ->
      let len1 = String.length expected_value in
      let len2 = String.length actual_value in
      if len1 <= 30 && len2 <= 30 then
        (* Short values: show inline with red for old, green for new *)
        Buffer.add_string buf
          (indent ^ "* " ^ property_name ^ ": "
          ^ ansi_red ~color:style.color expected_value
          ^ " -> "
          ^ ansi_green ~color:style.color actual_value
          ^ "\n")
      else
        (* Long values: truncate and show as separate lines *)
        let exp_truncated =
          String_diff.truncate_middle default_truncation_length expected_value
        in
        let act_truncated =
          String_diff.truncate_middle default_truncation_length actual_value
        in
        Buffer.add_string buf (indent ^ "* " ^ property_name ^ ":\n");
        Buffer.add_string buf
          (indent ^ "  "
          ^ ansi_red ~color:style.color ("- " ^ exp_truncated)
          ^ "\n");
        Buffer.add_string buf
          (indent ^ "  "
          ^ ansi_green ~color:style.color ("+ " ^ act_truncated)
          ^ "\n")

let pp_property_diffs ?(style = default_style) ?(parent_prefix = "") buf
    prop_diffs =
  List.iter (pp_property_diff ~style ~parent_prefix buf) prop_diffs

(* Helper to find adjacent property swap *)
let adjacent_swap lst1 lst2 =
  let rec scan l1 l2 =
    match (l1, l2) with
    | x1 :: x2 :: _, y1 :: y2 :: _ when x1 = y2 && x2 = y1 -> Some (x1, x2)
    | _ :: rest1, _ :: rest2 -> scan rest1 rest2
    | _, _ -> None
  in
  scan lst1 lst2

(* Helper to find property moves (up to max_count) *)
let index_of_property name names =
  let rec find_idx i = function
    | [] -> -1
    | x :: _ when x = name -> i
    | _ :: rest -> find_idx (i + 1) rest
  in
  find_idx 0 names

let property_moves ~max_count prop_names1 prop_names2 =
  let rec scan lst1 lst2 acc count =
    if count >= max_count then List.rev acc
    else
      match (lst1, lst2) with
      | x1 :: rest1, x2 :: rest2 when x1 <> x2 ->
          let new_pos = index_of_property x1 prop_names2 in
          scan rest1 rest2 ((x1, new_pos) :: acc) (count + 1)
      | _ :: rest1, _ :: rest2 -> scan rest1 rest2 acc count
      | _, _ -> List.rev acc
  in
  scan prop_names1 prop_names2 [] 0

(* Helper to print property moves *)
let pp_property_moves buf indent moves total_diffs =
  Buffer.add_string buf (indent ^ "* reorder: ");
  List.iteri
    (fun i (prop, new_pos) ->
      if i > 0 then Buffer.add_string buf ", ";
      if new_pos >= 0 then
        Buffer.add_string buf (prop ^ "\xe2\x86\x92" ^ string_of_int new_pos)
      else Buffer.add_string buf prop)
    moves;
  if total_diffs > List.length moves then
    Buffer.add_string buf
      (" (and " ^ string_of_int (total_diffs - List.length moves) ^ " more)");
  Buffer.add_char buf '\n'

let pp_property_move_summary buf indent prop_names1 prop_names2 =
  let moves = property_moves ~max_count:3 prop_names1 prop_names2 in
  if moves <> [] then
    let total_diffs =
      List.fold_left2
        (fun acc p1 p2 -> if p1 <> p2 then acc + 1 else acc)
        0 prop_names1 prop_names2
    in
    pp_property_moves buf indent moves total_diffs

let pp_same_property_reorder buf indent prop_names1 prop_names2 =
  match adjacent_swap prop_names1 prop_names2 with
  | Some (prop1, prop2) ->
      let truncate s = String_diff.truncate_middle 20 s in
      Buffer.add_string buf
        (indent ^ "* " ^ truncate prop1 ^ " \xe2\x86\x94 " ^ truncate prop2
       ^ "\n")
  | None -> pp_property_move_summary buf indent prop_names1 prop_names2

(* A declaration reorder changes the cascade only when two overlapping
   declarations swap relative order; disjoint declarations commute, so their
   reorder is no difference (README contract). Duplicated property names are a
   same-property override, reported conservatively. *)
let reorder_is_significant decls1 decls2 =
  let name = Css.declaration_name in
  let names1 = List.map name decls1 in
  let has_dup =
    let s = List.sort String.compare names1 in
    let rec go = function a :: (b :: _ as t) -> a = b || go t | _ -> false in
    go s
  in
  has_dup
  ||
  let pos2 = Hashtbl.create 16 in
  List.iteri (fun i d -> Hashtbl.replace pos2 (name d) i) decls2;
  let pos d = Option.value ~default:(-1) (Hashtbl.find_opt pos2 (name d)) in
  let arr = Array.of_list decls1 in
  let n = Array.length arr in
  let flipped = ref false in
  for i = 0 to n - 1 do
    for j = i + 1 to n - 1 do
      if
        Shorthand.declarations_overlap arr.(i) arr.(j)
        && pos arr.(i) >= pos arr.(j)
      then flipped := true
    done
  done;
  !flipped

let pp_reorder ?(style = default_style) ?(parent_prefix = "") decls1 decls2 buf
    =
  let indent =
    if style.use_tree then parent_prefix ^ "   " else parent_prefix ^ "    "
  in
  let prop_names1 = List.map Css.declaration_name decls1 in
  let prop_names2 = List.map Css.declaration_name decls2 in
  let same_props =
    List.length prop_names1 = List.length prop_names2
    && List.sort String.compare prop_names1
       = List.sort String.compare prop_names2
  in
  if
    same_props && prop_names1 <> prop_names2
    && reorder_is_significant decls1 decls2
  then pp_same_property_reorder buf indent prop_names1 prop_names2

let pp_content_changed ~style ~prefix ~child_prefix buf ~selector
    ~old_declarations ~new_declarations ~property_changes ~added_properties
    ~removed_properties =
  let indent =
    if style.use_tree then child_prefix ^ "   " else child_prefix ^ "    "
  in
  let has_any_changes =
    property_changes <> [] || added_properties <> [] || removed_properties <> []
  in
  if (not has_any_changes) && old_declarations = new_declarations then ()
  else (
    Buffer.add_string buf (prefix ^ selector ^ "\n");
    List.iter
      (fun prop_name ->
        Buffer.add_string buf
          (indent ^ ansi_red ~color:style.color ("- " ^ prop_name) ^ "\n"))
      removed_properties;
    List.iter
      (fun prop_name ->
        Buffer.add_string buf
          (indent ^ ansi_green ~color:style.color ("+ " ^ prop_name) ^ "\n"))
      added_properties;
    pp_property_diffs ~style ~parent_prefix:child_prefix buf property_changes;
    pp_reorder ~style ~parent_prefix:child_prefix old_declarations
      new_declarations buf;
    if (not has_any_changes) && old_declarations <> new_declarations then
      let old_count = List.length old_declarations in
      let new_count = List.length new_declarations in
      if old_count <> new_count then
        Buffer.add_string buf
          (indent ^ "(declaration count: " ^ string_of_int old_count ^ " -> "
         ^ string_of_int new_count ^ ")\n")
      else
        Buffer.add_string buf (indent ^ "(declarations differ in subtle ways)\n"))

let pp_position_reorder ~prefix buf ~selector ~expected_pos ~actual_pos
    ~swapped_with =
  assert (expected_pos <> actual_pos);
  let truncate s = String_diff.truncate_middle 40 s in
  match swapped_with with
  | Some other when abs (expected_pos - actual_pos) = 1 ->
      Buffer.add_string buf
        (prefix ^ truncate selector ^ " \xe2\x86\x94  " ^ truncate other ^ "\n")
  | Some other ->
      Buffer.add_string buf
        (prefix ^ truncate selector ^ " (position " ^ string_of_int actual_pos
       ^ ") \xe2\x86\x94  " ^ truncate other ^ " (position "
       ^ string_of_int expected_pos ^ ")\n")
  | None ->
      Buffer.add_string buf
        (prefix ^ truncate selector ^ " (position " ^ string_of_int expected_pos
       ^ " \xe2\x86\x92 " ^ string_of_int actual_pos ^ ")\n")

let pp_regrouped ~style ~prefix ~child_prefix buf ~from_selectors ~to_selectors
    =
  let nf = List.length from_selectors and nt = List.length to_selectors in
  let verb =
    if nf > nt then "merged" else if nf < nt then "split" else "regrouped"
  in
  Buffer.add_string buf (prefix ^ "selectors " ^ verb ^ "\n");
  let indent =
    if style.use_tree then child_prefix ^ "   " else child_prefix ^ "    "
  in
  List.iter
    (fun s ->
      Buffer.add_string buf
        (indent ^ ansi_red ~color:style.color ("- " ^ s) ^ "\n"))
    from_selectors;
  List.iter
    (fun s ->
      Buffer.add_string buf
        (indent ^ ansi_green ~color:style.color ("+ " ^ s) ^ "\n"))
    to_selectors

let pp_rule_diff ?(style = default_style) ?(is_last = false)
    ?(parent_prefix = "") buf (diff : rule_diff) =
  match diff with
  | Added { selector; declarations } ->
      let prefix = tree_prefix ~style ~is_last ~parent_prefix in
      let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
      Buffer.add_string buf (prefix ^ selector ^ "\n");
      pp_declarations ~style ~parent_prefix:child_prefix buf "add" declarations
  | Removed { selector; declarations } ->
      let prefix = tree_prefix ~style ~is_last ~parent_prefix in
      let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
      Buffer.add_string buf (prefix ^ selector ^ "\n");
      pp_declarations ~style ~parent_prefix:child_prefix buf "remove"
        declarations
  | Content_changed r ->
      let prefix = tree_prefix ~style ~is_last ~parent_prefix in
      let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
      pp_content_changed ~style ~prefix ~child_prefix buf ~selector:r.selector
        ~old_declarations:r.old_declarations
        ~new_declarations:r.new_declarations
        ~property_changes:r.property_changes
        ~added_properties:r.added_properties
        ~removed_properties:r.removed_properties
  | Selector_changed { old_selector; new_selector; declarations } ->
      let prefix = tree_prefix ~style ~is_last ~parent_prefix in
      let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
      Buffer.add_string buf (prefix ^ "selector changed:\n");
      let indent =
        if style.use_tree then child_prefix ^ "   " else child_prefix ^ "    "
      in
      Buffer.add_string buf (indent ^ "from: " ^ old_selector ^ "\n");
      Buffer.add_string buf (indent ^ "to:   " ^ new_selector ^ "\n");
      if declarations <> [] then
        pp_declarations ~style ~parent_prefix:child_prefix buf "declarations"
          declarations
  | Reordered r -> (
      let prefix = tree_prefix ~style ~is_last ~parent_prefix in
      match (r.old_declarations, r.new_declarations) with
      | Some old_decls, Some new_decls ->
          let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
          Buffer.add_string buf (prefix ^ r.selector ^ "\n");
          pp_reorder ~style ~parent_prefix:child_prefix old_decls new_decls buf
      | _ ->
          pp_position_reorder ~prefix buf ~selector:r.selector
            ~expected_pos:r.expected_pos ~actual_pos:r.actual_pos
            ~swapped_with:r.swapped_with)
  | Regrouped { from_selectors; to_selectors } ->
      let prefix = tree_prefix ~style ~is_last ~parent_prefix in
      let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
      pp_regrouped ~style ~prefix ~child_prefix buf ~from_selectors
        ~to_selectors

let pp_rule_diff_simple buf (diff : rule_diff) =
  match diff with
  | Added { selector; _ } -> Buffer.add_string buf ("Added(" ^ selector ^ ")")
  | Removed { selector; _ } ->
      Buffer.add_string buf ("Removed(" ^ selector ^ ")")
  | Content_changed { selector; _ } ->
      Buffer.add_string buf ("Changed(" ^ selector ^ ")")
  | Selector_changed { old_selector; new_selector; _ } ->
      Buffer.add_string buf
        ("SelectorChanged(" ^ old_selector ^ "->" ^ new_selector ^ ")")
  | Reordered { selector; expected_pos; actual_pos; _ } ->
      Buffer.add_string buf
        ("Reordered(" ^ selector ^ ":" ^ string_of_int expected_pos ^ "->"
       ^ string_of_int actual_pos ^ ")")
  | Regrouped { from_selectors; to_selectors } ->
      Buffer.add_string buf
        ("Regrouped("
        ^ String.concat " | " from_selectors
        ^ "->"
        ^ String.concat " | " to_selectors
        ^ ")")

let meaningful_rules (rules : rule_diff list) =
  List.filter
    (fun (diff : rule_diff) ->
      match diff with
      | Reordered _ -> false
      | Content_changed
          {
            property_changes = [];
            added_properties = [];
            removed_properties = [];
            old_declarations;
            new_declarations;
            _;
          }
        when old_declarations = new_declarations ->
          (* Filter out rules that moved to different nesting but have no
             changes *)
          false
      | _ -> true)
    rules

(** Query functions *)
let single_rule_diff (diff : t) =
  match diff.rules with [ rule ] -> Some rule | _ -> None

let rec count_containers_in_list container_type containers =
  List.fold_left
    (fun count cont ->
      let this_count =
        match cont with
        | Added { container_type = ct; _ }
        | Removed { container_type = ct; _ }
        | Reordered { info = { container_type = ct; _ }; _ }
        | Block_structure_changed { container_type = ct; _ } ->
            if ct = container_type then 1 else 0
        | Modified { info = { container_type = ct; _ }; container_changes; _ }
          ->
            let nested_count =
              count_containers_in_list container_type container_changes
            in
            (if ct = container_type then 1 else 0) + nested_count
      in
      count + this_count)
    0 containers

let count_containers_by_type container_type (diff : t) =
  count_containers_in_list container_type diff.containers

let has_container_added_of_type container_type (diff : t) =
  List.exists
    (function
      | Added { container_type = ct; _ } -> ct = container_type | _ -> false)
    diff.containers

let has_container_removed_of_type container_type (diff : t) =
  List.exists
    (function
      | Removed { container_type = ct; _ } -> ct = container_type | _ -> false)
    diff.containers

let container_prefix = function
  | `Media -> "@media"
  | `Layer -> "@layer"
  | `Supports -> "@supports"
  | `Container -> "@container"
  | `Property -> "@property"
  | `Nesting -> "&"

let pp_container_rules ~style ~parent_prefix ~label buf rules =
  if rules <> [] then
    let rule_count = List.length rules in
    List.iteri
      (fun i stmt ->
        match Css.as_rule stmt with
        | Some (selector, _, _) ->
            let rule_prefix =
              tree_prefix ~style ~is_last:(i = rule_count - 1) ~parent_prefix
            in
            Buffer.add_string buf
              (rule_prefix
              ^ Css.Selector.to_string selector
              ^ " (" ^ label ^ ")\n")
        | None -> ())
      rules

let count_rule_changes (rule_changes : rule_diff list) =
  let count pred = List.length (List.filter pred rule_changes) in
  let parts =
    List.filter_map Fun.id
      [
        (let n =
           count (fun (diff : rule_diff) ->
               match diff with Added _ -> true | _ -> false)
         in
         if n > 0 then Some (string_of_int n ^ " added") else None);
        (let n =
           count (fun (diff : rule_diff) ->
               match diff with Removed _ -> true | _ -> false)
         in
         if n > 0 then Some (string_of_int n ^ " removed") else None);
        (let n =
           count (fun (diff : rule_diff) ->
               match diff with Content_changed _ -> true | _ -> false)
         in
         if n > 0 then Some (string_of_int n ^ " modified") else None);
        (let n =
           count (fun (diff : rule_diff) ->
               match diff with Reordered _ -> true | _ -> false)
         in
         if n > 0 then Some (string_of_int n ^ " reordered") else None);
        (let n =
           count (fun (diff : rule_diff) ->
               match diff with Selector_changed _ -> true | _ -> false)
         in
         if n > 0 then Some (string_of_int n ^ " selector changed") else None);
        (let n =
           count (fun (diff : rule_diff) ->
               match diff with Regrouped _ -> true | _ -> false)
         in
         if n > 0 then Some (string_of_int n ^ " regrouped") else None);
      ]
  in
  parts

let selectors_of_rules rules =
  List.filter_map
    (fun stmt ->
      match Css.as_rule stmt with
      | Some (sel, _, _) -> Some (Css.Selector.to_string sel)
      | None -> None)
    rules

let pp_block_structure_changed ~style ~is_last ~parent_prefix buf
    ~container_type ~condition ~expected_blocks ~actual_blocks =
  let cont_prefix = container_prefix container_type in
  let prefix = tree_prefix ~style ~is_last ~parent_prefix in
  let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
  let indent =
    if style.use_tree then child_prefix ^ "   " else child_prefix ^ "    "
  in

  (* Show the merge/split summary *)
  let exp_count = List.length expected_blocks in
  let act_count = List.length actual_blocks in

  (* Report block structure changes - this is a meaningful difference even if
     selectors are identical *)
  if exp_count > act_count then
    Buffer.add_string buf
      (prefix ^ cont_prefix ^ " " ^ condition ^ " (" ^ string_of_int exp_count
     ^ " blocks merged into " ^ string_of_int act_count ^ ")\n")
  else if exp_count < act_count then
    Buffer.add_string buf
      (prefix ^ cont_prefix ^ " " ^ condition ^ " (" ^ string_of_int exp_count
     ^ " block split into " ^ string_of_int act_count ^ ")\n")
  else
    (* Same count but different positions *)
    Buffer.add_string buf
      (prefix ^ cont_prefix ^ " " ^ condition ^ " (" ^ string_of_int exp_count
     ^ " blocks at different positions)\n");

  let pp_blocks sign style_fn blocks =
    List.iter
      (fun (pos, rules) ->
        let selectors = selectors_of_rules rules in
        if selectors <> [] then
          Buffer.add_string buf
            (indent
            ^ style_fn
                (sign ^ " Block at position " ^ string_of_int pos ^ ": "
                ^ String.concat ", " selectors)
            ^ "\n"))
      blocks
  in
  pp_blocks "-" (ansi_red ~color:style.color) expected_blocks;
  pp_blocks "+" (ansi_green ~color:style.color) actual_blocks

let pp_container_add_remove ~style ~is_last ~parent_prefix ~label buf
    container_type condition rules =
  let prefix = tree_prefix ~style ~is_last ~parent_prefix in
  let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
  Buffer.add_string buf
    (prefix
    ^ container_prefix container_type
    ^ " " ^ condition ^ " (" ^ label ^ ")\n");
  pp_container_rules ~style ~parent_prefix:child_prefix ~label buf rules

let rec pp_container_diff ?(style = default_style) ?(is_last = false)
    ?(parent_prefix = "") buf = function
  | Added { container_type; condition; rules } ->
      pp_container_add_remove ~style ~is_last ~parent_prefix ~label:"added" buf
        container_type condition rules
  | Removed { container_type; condition; rules } ->
      pp_container_add_remove ~style ~is_last ~parent_prefix ~label:"removed"
        buf container_type condition rules
  | Modified
      {
        info = { container_type; condition; rules = _ };
        actual_rules = _;
        rule_changes;
        container_changes;
      } ->
      let cont_prefix = container_prefix container_type in
      let prefix = tree_prefix ~style ~is_last ~parent_prefix in
      let child_prefix = tree_continuation ~style ~is_last ~parent_prefix in
      let changes_parts = count_rule_changes rule_changes in
      Buffer.add_string buf (prefix ^ cont_prefix ^ " " ^ condition ^ " ");
      if changes_parts <> [] then
        Buffer.add_string buf ("(" ^ String.concat ", " changes_parts ^ ")\n")
      else if container_changes = [] then
        Buffer.add_string buf "(position changed)\n"
      else Buffer.add_char buf '\n';

      (* Show rule changes at this level *)
      List.iteri
        (fun i rule_diff ->
          let is_last_item =
            i = List.length rule_changes - 1 && container_changes = []
          in
          pp_rule_diff ~style ~is_last:is_last_item ~parent_prefix:child_prefix
            buf rule_diff)
        rule_changes;
      (* Show nested container changes with increased indentation *)
      let container_count = List.length container_changes in
      List.iteri
        (fun i cont_diff ->
          let is_last_cont = i = container_count - 1 in
          pp_container_diff ~style ~is_last:is_last_cont
            ~parent_prefix:child_prefix buf cont_diff)
        container_changes
  | Reordered
      { info = { container_type; condition; _ }; expected_pos; actual_pos } ->
      let cont_prefix = container_prefix container_type in
      let prefix = tree_prefix ~style ~is_last ~parent_prefix in
      Buffer.add_string buf
        (prefix ^ cont_prefix ^ " " ^ condition ^ " (position "
       ^ string_of_int expected_pos ^ " \xe2\x86\x92 "
       ^ string_of_int actual_pos ^ ")\n")
  | Block_structure_changed
      { container_type; condition; expected_blocks; actual_blocks } ->
      pp_block_structure_changed ~style ~is_last ~parent_prefix buf
        ~container_type ~condition ~expected_blocks ~actual_blocks

let pp_diff_headers ~color buf expected actual =
  Buffer.add_string buf
    (ansi_yellow ~color "---" ^ " " ^ ansi_yellow ~color expected ^ "\n");
  Buffer.add_string buf
    (ansi_yellow ~color "+++" ^ " " ^ ansi_yellow ~color actual ^ "\n")

let pp_rule_list ~style ~container_count buf rule_list =
  let rule_count = List.length rule_list in
  List.iteri
    (fun i rule_diff ->
      let is_last = i = rule_count - 1 && container_count = 0 in
      pp_rule_diff ~style ~is_last ~parent_prefix:"" buf rule_diff)
    rule_list

let pp_reordered_section ~style ~container_count buf = function
  | [] -> ()
  | lst ->
      Buffer.add_string buf
        ("Rules reordered (" ^ string_of_int (List.length lst) ^ " rules):\n");
      pp_rule_list ~style ~container_count buf lst

let pp_containers_section ~style buf containers =
  let container_count = List.length containers in
  List.iteri
    (fun i cont_diff ->
      let is_last = i = container_count - 1 in
      pp_container_diff ~style ~is_last ~parent_prefix:"" buf cont_diff)
    containers

let pp ?(expected = "Expected") ?(actual = "Actual") ?(color = false) buf
    { rules; containers } =
  if rules = [] && containers = [] then
    Buffer.add_string buf
      "Structural differences detected in nested contexts (e.g., @media inside \
       @layer)\n\
       but no rule-level differences found.\n\
       This may indicate reordering or subtle changes in rule organization."
  else (
    pp_diff_headers ~color buf expected actual;
    let meaningful = meaningful_rules rules in
    let reordered_rules =
      List.filter
        (fun (diff : rule_diff) ->
          match diff with Reordered _ -> true | _ -> false)
        rules
    in
    let style = { tree_style with color } in
    let container_count = List.length containers in
    pp_rule_list ~style ~container_count buf meaningful;
    pp_reordered_section ~style ~container_count buf reordered_rules;
    pp_containers_section ~style buf containers)

(* ===== Tree Diff Computation Functions ===== *)

(* Helper to extract rule information from statements *)
let strings_of_rule stmt =
  match Css.as_rule stmt with
  | Some (selector, decls, _) ->
      let selector_str = Css.Selector.to_string selector in
      (selector_str, decls)
  | None -> ("", [])

let decl_to_prop_value decl =
  let name = Css.declaration_name decl in
  let value = Css.declaration_value_for_equivalence decl in
  let value =
    if Css.declaration_is_important decl then value ^ " !important" else value
  in
  (name, value)

let decls_signature (decls : Css.declaration list) =
  List.map decl_to_prop_value decls |> List.sort compare

(* Normalize a selector string by sorting comma-separated selector items. This
   ensures we consider ".a,.b" equivalent to ".b,.a" when matching.

   Policy: Selector lists with the same items in different orders are considered
   equivalent for matching purposes. This means: - ".a, .b" and ".b, .a" will
   match as the same selector - Reordering within a list is not considered a
   structural change - This prevents false positives when CSS tools reorder
   selector lists *)
let rule_selector stmt =
  match Css.statement_selector stmt with
  | Some s -> s
  | None -> Css.Selector.universal

(* [selector_key_of_*] is called O(N M) times during structural rule diffs. Use
   the typed selector AST as the key: normalise a [List] of selectors by sorting
   the alternatives so [h1, h2] and [h2, h1] map to the same key, then rely on
   structural equality + [Hashtbl.hash]. Avoids serialising through
   [Pp.to_string] for every comparison. *)
let selector_key_of_selector (sel : Css.Selector.t) : Css.Selector.t =
  match sel with List subs -> List (List.sort compare subs) | _ -> sel

let selector_key_of_stmt stmt = selector_key_of_selector (rule_selector stmt)

let rule_declarations stmt =
  match Css.statement_declarations stmt with Some d -> d | None -> []

let rule_nested stmt =
  match Css.as_rule stmt with Some (_, _, nested) -> nested | None -> []

(* Generic helper for finding added/removed/modified items between two lists.
   Works with any item type that has a key for comparison.

   Each item's key is computed once and threaded through the N*M cross checks
   below; without this every [List.exists] pass would re-call [key_of] for every
   item it visits. *)
let diffs ~(key_of : 'item -> 'key) ~(key_equal : 'key -> 'key -> bool)
    ~(is_empty_diff : 'item -> 'item -> bool) items1 items2 =
  let items1_keyed = List.map (fun i -> (i, key_of i)) items1 in
  let items2_keyed = List.map (fun i -> (i, key_of i)) items2 in
  let find_by_key key items =
    List.find_opt (fun (_, k) -> key_equal k key) items
  in
  let added =
    List.filter_map
      (fun (item2, key2) ->
        if List.exists (fun (_, k1) -> key_equal k1 key2) items1_keyed then None
        else Some item2)
      items2_keyed
  in
  let removed =
    List.filter_map
      (fun (item1, key1) ->
        if List.exists (fun (_, k2) -> key_equal key1 k2) items2_keyed then None
        else Some item1)
      items1_keyed
  in
  let modified =
    List.filter_map
      (fun (item1, key1) ->
        match find_by_key key1 items2_keyed with
        | Some (item2, _) when not (is_empty_diff item1 item2) ->
            Some (item1, item2)
        | _ -> None)
      items1_keyed
  in
  (added, removed, modified)

let rules_added_diff rules1 rules2 =
  let key_of = selector_key_of_stmt in
  let key_equal = ( = ) in
  let is_empty_diff _ _ = true in
  let added, _removed, _modified =
    diffs ~key_of ~key_equal ~is_empty_diff rules1 rules2
  in
  added

let rules_removed_diff rules1 rules2 =
  let key_of = selector_key_of_stmt in
  let key_equal = ( = ) in
  let is_empty_diff _ _ = true in
  let _added, removed, _modified =
    diffs ~key_of ~key_equal ~is_empty_diff rules1 rules2
  in
  removed

let selectors_share_parent sel1_str sel2_str =
  (* Check if two selectors share a common parent context *)
  let parts1 = String.split_on_char ' ' sel1_str |> List.rev in
  let parts2 = String.split_on_char ' ' sel2_str |> List.rev in
  match (parts1, parts2) with
  | _ :: p1_rest, _ :: p2_rest ->
      List.rev p1_rest = List.rev p2_rest && p1_rest <> []
  | _ -> false

let build_rule_lookup_tables rules2 =
  (* Create lookup tables for O(1) access *)
  let rules2_by_key = Hashtbl.create (List.length rules2) in
  let rules2_by_props = Hashtbl.create (List.length rules2) in

  (* Populate lookup tables *)
  List.iter
    (fun r ->
      let key = selector_key_of_stmt r in
      let decls = rule_declarations r in
      let props = decls_signature decls in

      (* Add to key-based lookup (multiple rules can have same key) *)
      let existing_key =
        try Hashtbl.find rules2_by_key key with Not_found -> []
      in
      Hashtbl.replace rules2_by_key key (r :: existing_key);

      (* Add to props-based lookup (multiple rules can have same props) *)
      let existing_props =
        try Hashtbl.find rules2_by_props props with Not_found -> []
      in
      Hashtbl.replace rules2_by_props props (r :: existing_props))
    rules2;
  (rules2_by_key, rules2_by_props)

(* Try to find an exact match by selector key and declarations *)
(* Returns: Some (Some diff) if selectors differ, Some None if exact match with same selectors, None if no exact match *)
let try_exact_match rules2_by_key used_rules r1 key1 d1 =
  let candidates = try Hashtbl.find rules2_by_key key1 with Not_found -> [] in
  match
    List.find_opt
      (fun r ->
        (not (Hashtbl.mem used_rules r))
        && rule_declarations r = d1
        && rule_nested r = rule_nested r1)
      candidates
  with
  | Some exact ->
      Hashtbl.replace used_rules exact ();
      let sel1 = rule_selector r1 in
      let sel2 = rule_selector exact in
      let sel1_str = Css.Selector.to_string sel1 in
      let sel2_str = Css.Selector.to_string sel2 in
      if sel1_str <> sel2_str then Some (Some (sel1, sel2, d1, d1))
      else Some None
  | None -> None

(* Try to find any rule with the same selector key *)
let try_same_key_match rules2_by_key used_rules r1 key1 d1 =
  let candidates = try Hashtbl.find rules2_by_key key1 with Not_found -> [] in
  match List.find_opt (fun r -> not (Hashtbl.mem used_rules r)) candidates with
  | Some r2 ->
      Hashtbl.replace used_rules r2 ();
      let d2 = rule_declarations r2 in
      Some (rule_selector r1, rule_selector r2, d1, d2)
  | None -> None

(* Try to find equivalent rule by properties with shared parent *)
let try_equivalent_props_match rules2_by_props used_rules r1 d1 props1 =
  let candidates =
    try Hashtbl.find rules2_by_props props1 with Not_found -> []
  in
  let sel1_str = Css.Selector.to_string (rule_selector r1) in
  match
    List.find_opt
      (fun r ->
        if Hashtbl.mem used_rules r then false
        else
          let sel2_str = Css.Selector.to_string (rule_selector r) in
          selectors_share_parent sel1_str sel2_str)
      candidates
  with
  | Some r2 ->
      Hashtbl.replace used_rules r2 ();
      let d2 = rule_declarations r2 in
      Some (rule_selector r1, rule_selector r2, d1, d2)
  | None -> None

let pick_non_exact_rule rules2_by_key rules2_by_props used_rules r1 key1 d1
    props1 =
  match try_same_key_match rules2_by_key used_rules r1 key1 d1 with
  | Some result -> Some result
  | None -> try_equivalent_props_match rules2_by_props used_rules r1 d1 props1

let pick_modified_rule rules2_by_key rules2_by_props used_rules r1 key1 d1
    props1 =
  match try_exact_match rules2_by_key used_rules r1 key1 d1 with
  | Some (Some result) -> Some result
  | Some None -> None
  | None ->
      pick_non_exact_rule rules2_by_key rules2_by_props used_rules r1 key1 d1
        props1

let rules_modified_diff rules1 rules2 =
  let rules2_by_key, rules2_by_props = build_rule_lookup_tables rules2 in
  let used_rules = Hashtbl.create (List.length rules2) in

  let rec aux acc = function
    | [] -> List.rev acc
    | r1 :: t1 ->
        let key1 = selector_key_of_stmt r1 in
        let d1 = rule_declarations r1 in
        let props1 = decls_signature d1 in
        let pick =
          pick_modified_rule rules2_by_key rules2_by_props used_rules r1 key1 d1
            props1
        in
        let acc = match pick with None -> acc | Some x -> x :: acc in
        aux acc t1
  in
  aux [] rules1

let has_same_selectors rules1 rules2 =
  if List.length rules1 <> List.length rules2 then false
  else
    (* Use hash table for O(n) comparison instead of O(n log n) sorting *)
    let keys1_counts = Hashtbl.create (List.length rules1) in
    List.iter
      (fun r ->
        let key = selector_key_of_stmt r in
        let count = try Hashtbl.find keys1_counts key with Not_found -> 0 in
        Hashtbl.replace keys1_counts key (count + 1))
      rules1;

    let keys2_counts = Hashtbl.create (List.length rules2) in
    List.iter
      (fun r ->
        let key = selector_key_of_stmt r in
        let count = try Hashtbl.find keys2_counts key with Not_found -> 0 in
        Hashtbl.replace keys2_counts key (count + 1))
      rules2;

    (* Check if hash tables are equivalent *)
    try
      Hashtbl.iter
        (fun key count1 ->
          let count2 =
            try Hashtbl.find keys2_counts key with Not_found -> 0
          in
          if count1 <> count2 then raise Exit)
        keys1_counts;

      Hashtbl.iter
        (fun key count2 ->
          let count1 =
            try Hashtbl.find keys1_counts key with Not_found -> 0
          in
          if count1 <> count2 then raise Exit)
        keys2_counts;

      true
    with Exit -> false

let build_selector_map rules =
  (* Create map from selector to declarations *)
  List.fold_left
    (fun acc rule ->
      let sel = rule_selector rule in
      let decls = rule_declarations rule in
      (sel, decls) :: acc)
    [] rules
  |> List.rev

let selector_in_list sel_key remaining =
  (* Check if selector key exists in remaining list *)
  List.exists (fun (s, _) -> selector_key_of_selector s = sel_key) remaining

(* Locate matching declarations in map2 for a given selector key *)
let matching_decls_in_map2 sel1_key decls1 map2 decls2 =
  (* Prefer an exact declaration match for the same selector key if available *)
  match
    List.find_opt
      (fun (s, d) -> selector_key_of_selector s = sel1_key && d = decls1)
      map2
  with
  | Some (s, d) -> (d, Some s)
  | None -> (
      match
        List.find_opt (fun (s, _) -> selector_key_of_selector s = sel1_key) map2
      with
      | Some (s, d) -> (d, Some s)
      | None -> (decls2, None))

let add_ordering_issue map2 remaining1 remaining2 acc sel1 decls1 sel2 decls2 =
  let sel1_key = selector_key_of_selector sel1 in
  let sel2_key = selector_key_of_selector sel2 in
  if sel1_key = sel2_key then
    (* Same selector at this position: a difference only when its declarations
       differ, i.e. same-selector rules were reordered so the cascade winner
       flips. *)
    if decls_signature decls1 = decls_signature decls2 then acc
    else (sel1, sel2, decls1, decls2) :: acc
  else if
    selector_in_list sel1_key remaining2 && selector_in_list sel2_key remaining1
  then
    let decls1_from_map2, sel2_opt =
      matching_decls_in_map2 sel1_key decls1 map2 decls2
    in
    let sel2 = match sel2_opt with Some s -> s | None -> sel1 in
    (sel1, sel2, decls1, decls1_from_map2) :: acc
  else acc

(* no-op: pure rule ordering is handled in handle_structural_diff via
   has_ordering_changes/ordering_diff *)

let ordering_diff rules1 rules2 =
  let map1 = build_selector_map rules1 in
  let map2 = build_selector_map rules2 in

  let rec find_ordering_issues acc remaining1 remaining2 =
    match (remaining1, remaining2) with
    | [], [] -> List.rev acc
    | (sel1, decls1) :: rest1, (sel2, decls2) :: rest2 ->
        let acc =
          add_ordering_issue map2 remaining1 remaining2 acc sel1 decls1 sel2
            decls2
        in
        find_ordering_issues acc rest1 rest2
    | _, _ -> List.rev acc
  in

  find_ordering_issues [] map1 map2

let extract_base_parent_selector sel =
  let sel_str = Css.Selector.to_string sel in
  match String.index_opt sel_str ' ' with
  | None -> None
  | Some sp ->
      let parent = String.sub sel_str 0 sp in
      let stripped =
        match String.index_opt parent ':' with
        | Some idx -> String.sub parent 0 idx
        | None -> parent
      in
      Some stripped

let selectors_share_parent_ast sel1 sel2 =
  match
    (extract_base_parent_selector sel1, extract_base_parent_selector sel2)
  with
  | Some p1, Some p2 -> p1 = p2
  | _ -> false

let selector_changes all_added_candidates all_removed_candidates =
  (* Index added rules by their declaration signature so the inner loop is a
     hashtable lookup, not a linear scan over [all_added_candidates]. With N
     removed and M added rules, the previous shape was O(N M) [decls_signature]
     computations; now it's O(N + M) plus the per-bucket scan for the
     share-parent check (buckets are typically small). *)
  let added_by_props : (string list, Css.statement list) Hashtbl.t =
    Hashtbl.create (List.length all_added_candidates)
  in
  List.iter
    (fun added ->
      let props = decls_signature (rule_declarations added) |> List.map snd in
      let prev =
        Hashtbl.find_opt added_by_props props |> Option.value ~default:[]
      in
      Hashtbl.replace added_by_props props (added :: prev))
    all_added_candidates;
  let added_with_props_sig sig_strings =
    Hashtbl.find_opt added_by_props sig_strings |> Option.value ~default:[]
  in
  let matched_added = ref [] in
  let matched_removed = ref [] in
  let changes = ref [] in
  List.iter
    (fun removed_rule ->
      let removed_sel = rule_selector removed_rule in
      let removed_decls = rule_declarations removed_rule in
      let removed_props = decls_signature removed_decls |> List.map snd in
      let matching_added =
        List.find_opt
          (fun added_rule ->
            let added_sel = rule_selector added_rule in
            removed_sel <> added_sel
            && selectors_share_parent_ast removed_sel added_sel)
          (added_with_props_sig removed_props)
      in
      match matching_added with
      | Some added_rule ->
          let added_sel = rule_selector added_rule in
          changes :=
            (removed_sel, added_sel, removed_decls, removed_decls) :: !changes;
          matched_removed := removed_rule :: !matched_removed;
          matched_added := added_rule :: !matched_added
      | None -> ())
    all_removed_candidates;
  (!changes, !matched_added, !matched_removed)

(* Filter other_modified to exclude changes already captured as selector
   changes *)
let exclude_modified_selector_changes sel_changes other_modified =
  let sel_change_selectors =
    List.map
      (fun (sel1, sel2, _, _) ->
        (Css.Selector.to_string sel1, Css.Selector.to_string sel2))
      sel_changes
  in
  List.filter
    (fun (sel1, sel2, _, _) ->
      let sel1_str = Css.Selector.to_string sel1 in
      let sel2_str = Css.Selector.to_string sel2 in
      not (List.mem (sel1_str, sel2_str) sel_change_selectors))
    other_modified

(* The single selectors and declaration signature of a flat rule (no nested
   body); [None] for any other statement. *)
let flat_rule_parts stmt =
  match Css.as_rule stmt with
  | Some (sel, decls, []) ->
      let subs = match sel with List subs -> subs | s -> [ s ] in
      Some (decls, subs, decls_signature decls)
  | _ -> None

let grouping_pair_count rules =
  let h = Hashtbl.create 16 in
  List.iter
    (fun stmt ->
      match flat_rule_parts stmt with
      | Some (_, subs, sign) ->
          List.iter
            (fun sub ->
              let p = (selector_key_of_selector sub, sign) in
              Hashtbl.replace h p
                (1 + Option.value ~default:0 (Hashtbl.find_opt h p)))
            subs
      | None -> ())
    rules;
  h

(* Drop each selector whose pair the [common] budget still covers; keep the rule
   unchanged when none drop, trim it to the survivors otherwise, remove it when
   all drop. *)
let trim_reconciled_grouping common rules =
  let budget = Hashtbl.copy common in
  List.filter_map
    (fun stmt ->
      match flat_rule_parts stmt with
      | Some (decls, subs, sign) ->
          let kept =
            List.filter
              (fun sub ->
                let p = (selector_key_of_selector sub, sign) in
                match Hashtbl.find_opt budget p with
                | Some n when n > 0 ->
                    Hashtbl.replace budget p (n - 1);
                    false
                | _ -> true)
              subs
          in
          if kept = [] then None
          else if List.compare_lengths kept subs = 0 then Some stmt
          else
            let selector =
              match kept with [ s ] -> s | many -> Css.Selector.list many
            in
            Some (Css.rule ~selector decls)
      | None -> Some stmt)
    rules

(* A comma-grouped rule split or merged across rules with identical declarations
   ([.a, .b { x }] vs [.a { x } .b { x }]) is not a semantic change: the same
   [(single selector, declarations)] pairs survive, only regrouped. Reconcile
   the leftover add/remove candidates at the pair level so the regrouping does
   not read as add/remove noise - a pair on both sides is unchanged and drops
   from each, trimming the rule's selector list, or dropping the rule when no
   selector survives. Restricted to flat rules: a nested rule's [(selector,
   declarations)] pair does not capture its nested body. *)
let partial_trim added removed =
  let added_count = grouping_pair_count added in
  let removed_count = grouping_pair_count removed in
  let common = Hashtbl.create 16 in
  Hashtbl.iter
    (fun p ac ->
      match Hashtbl.find_opt removed_count p with
      | Some rc -> Hashtbl.replace common p (min ac rc)
      | None -> ())
    added_count;
  if Hashtbl.length common = 0 then (added, removed)
  else
    ( trim_reconciled_grouping common added,
      trim_reconciled_grouping common removed )

let rule_sig stmt = Option.map (fun (_, _, s) -> s) (flat_rule_parts stmt)

let rule_selector_str stmt =
  Option.map (fun (s, _, _) -> Css.Selector.to_string s) (Css.as_rule stmt)

(* A declaration signature is a pure regroup when its removed and added flat
   rules carry the same multiset of single selectors (only the grouping moved).
   Emit a [Regrouped] note for it; the rules are dropped from add/remove. *)
let detect_pure_regroups added removed =
  let with_sig s rules = List.filter (fun r -> rule_sig r = Some s) rules in
  let single_keys rules =
    List.concat_map
      (fun r ->
        match flat_rule_parts r with
        | Some (_, subs, _) -> List.map selector_key_of_selector subs
        | None -> [])
      rules
    |> List.sort compare
  in
  List.filter_map rule_sig (added @ removed)
  |> List.sort_uniq compare
  |> List.filter_map (fun s ->
      let radd = with_sig s added and rrem = with_sig s removed in
      if radd <> [] && rrem <> [] && single_keys radd = single_keys rrem then
        Some
          ( s,
            (Regrouped
               {
                 from_selectors = List.filter_map rule_selector_str rrem;
                 to_selectors = List.filter_map rule_selector_str radd;
               }
              : rule_diff) )
      else None)

let reconcile_selector_grouping added removed =
  let pure = detect_pure_regroups added removed in
  let pure_sigs = List.map fst pure in
  let in_pure r =
    match rule_sig r with Some s -> List.mem s pure_sigs | None -> false
  in
  let added = List.filter (fun r -> not (in_pure r)) added in
  let removed = List.filter (fun r -> not (in_pure r)) removed in
  let added, removed = partial_trim added removed in
  (added, removed, List.map snd pure)

let handle_structural_diff rules1 rules2 =
  let all_added_candidates = rules_added_diff rules1 rules2 in
  let all_removed_candidates = rules_removed_diff rules1 rules2 in

  let sel_changes, matched_added, matched_removed =
    selector_changes all_added_candidates all_removed_candidates
  in

  let added =
    List.filter (fun r -> not (List.memq r matched_added)) all_added_candidates
  in
  let removed =
    List.filter
      (fun r -> not (List.memq r matched_removed))
      all_removed_candidates
  in
  let added, removed, regrouped = reconcile_selector_grouping added removed in

  let other_modified = rules_modified_diff rules1 rules2 in
  let filtered_other_modified =
    exclude_modified_selector_changes sel_changes other_modified
  in

  let modified = sel_changes @ filtered_other_modified in

  let has_structural_changes =
    added <> [] || removed <> [] || modified <> [] || regrouped <> []
  in
  (* Key reorder detection on the (selector, declarations) sequence, not the
     selector alone: two same-selector rules with conflicting declarations
     cascade last-wins, so swapping them is a real change. *)
  let order_signature stmts =
    List.map
      (fun s -> (selector_key_of_stmt s, decls_signature (rule_declarations s)))
      stmts
  in
  let has_ordering_changes =
    (not has_structural_changes)
    && has_same_selectors rules1 rules2
    && order_signature rules1 <> order_signature rules2
  in

  let modified_with_order =
    if has_ordering_changes then ordering_diff rules1 rules2 @ modified
    else modified
  in

  (added, removed, modified_with_order, regrouped)

let rule_diffs rules1 rules2 = handle_structural_diff rules1 rules2

(* Helper function to compute property diffs between two declaration lists,
   including added and removed properties *)
let properties_diff decls1 decls2 : declaration list * string list * string list
    =
  let props1 = List.map decl_to_prop_value decls1 in
  let props2 = List.map decl_to_prop_value decls2 in

  (* Find modified properties *)
  let modified =
    List.fold_left
      (fun acc (p1, v1) ->
        match List.assoc_opt p1 props2 with
        | Some v2 when v1 <> v2 ->
            { property_name = p1; expected_value = v1; actual_value = v2 }
            :: acc
        | _ -> acc)
      [] props1
    |> List.rev
  in

  (* Find added properties (in actual but not in expected) *)
  let added =
    List.fold_left
      (fun acc (p2, _v2) ->
        if not (List.mem_assoc p2 props1) then p2 :: acc else acc)
      [] props2
    |> List.rev
  in

  (* Find removed properties (in expected but not in actual) *)
  let removed =
    List.fold_left
      (fun acc (p1, _v1) ->
        if not (List.mem_assoc p1 props2) then p1 :: acc else acc)
      [] props1
    |> List.rev
  in

  (modified, added, removed)

(* Helper functions for converting rule changes - moved here for mutual
   recursion *)
let convert_added_rule stmt =
  let sel, decls = strings_of_rule stmt in
  (Added { selector = sel; declarations = decls } : rule_diff)

let convert_removed_rule stmt =
  let sel, decls = strings_of_rule stmt in
  (Removed { selector = sel; declarations = decls } : rule_diff)

let describe_statement stmt =
  let try_desc f = f stmt in
  let matchers =
    [
      (fun s ->
        Option.map (fun (s, _, _) -> Css.Selector.to_string s) (Css.as_rule s));
      (fun s ->
        Option.map
          (fun (c, _) -> "@media " ^ Css.Media.to_string c)
          (Css.as_media s));
      (fun s ->
        Option.map
          (fun (n, _) ->
            match n with Some name -> "@layer " ^ name | None -> "@layer")
          (Css.as_layer s));
      (fun s ->
        Option.map
          (fun (n, c, _) ->
            let prefix = match n with Some n -> n ^ " " | None -> "" in
            let cond_str =
              match c with Some c -> Css.Container.to_string c | None -> ""
            in
            "@container " ^ prefix ^ cond_str)
          (Css.as_container s));
      (fun s ->
        Option.map
          (fun (c, _) -> "@supports " ^ Css.Supports.to_string c)
          (Css.as_supports s));
      (fun s -> Option.map (fun _ -> "@property") (Css.as_property s));
      (fun s ->
        Option.map (fun (name, _) -> "@keyframes " ^ name) (Css.as_keyframes s));
      (fun s -> Option.map (fun _ -> "@font-face") (Css.as_font_face s));
    ]
  in
  match List.find_map try_desc matchers with
  | Some desc -> Some desc
  | None -> Some "(other statement)"

let selector_position sel rules =
  let sel_key = selector_key_of_selector sel in
  List.mapi
    (fun i stmt ->
      match Css.as_rule stmt with
      | Some (s, _, _) when selector_key_of_selector s = sel_key -> Some i
      | _ -> None)
    rules
  |> List.find_map Fun.id |> Option.value ~default:(-1)

let selector_at_position pos rules =
  Option.bind (List.nth_opt rules pos) describe_statement

let content_changed selector old_decls new_decls =
  let property_changes, added_props, removed_props =
    properties_diff old_decls new_decls
  in
  Content_changed
    {
      selector;
      old_declarations = old_decls;
      new_declarations = new_decls;
      property_changes;
      added_properties = added_props;
      removed_properties = removed_props;
    }

let reordered ~rules1 ~rules2 sel1 sel2 selector : rule_diff =
  let expected_pos = selector_position sel1 rules1 in
  let actual_pos = selector_position sel2 rules2 in
  let swapped_with = selector_at_position expected_pos rules2 in
  (Reordered
     {
       selector;
       expected_pos;
       actual_pos;
       swapped_with;
       old_declarations = None;
       new_declarations = None;
     }
    : rule_diff)

let position_changed ~rules1 ~rules2 sel1 sel2 =
  let expected_pos = selector_position sel1 rules1 in
  let actual_pos = selector_position sel2 rules2 in
  expected_pos <> actual_pos

let is_pure_decl_reordering decls1 decls2 =
  let property_changes, added_props, removed_props =
    properties_diff decls1 decls2
  in
  let pure =
    property_changes = [] && added_props = [] && removed_props = []
    && decls_signature decls1 = decls_signature decls2
  in
  (pure, property_changes, added_props, removed_props)

let decl_level_reorder selector decls1 decls2 : rule_diff =
  (Reordered
     {
       selector;
       expected_pos = -1;
       actual_pos = -1;
       swapped_with = None;
       old_declarations = Some decls1;
       new_declarations = Some decls2;
     }
    : rule_diff)

let decls_str_equal d1 d2 =
  List.length d1 = List.length d2
  && List.for_all2
       (fun x y -> decl_to_prop_value x = decl_to_prop_value y)
       d1 d2

let convert_modified_rule ~rules1 ~rules2 (sel1, sel2, decls1, decls2) =
  let sel1_str = Css.Selector.to_string sel1 in
  let sel2_str = Css.Selector.to_string sel2 in
  let position_changed () = position_changed ~rules1 ~rules2 sel1 sel2 in
  let reordered selector = reordered ~rules1 ~rules2 sel1 sel2 selector in
  let reorder_or_content selector d1 d2 =
    if position_changed () then Some (reordered selector)
    else Some (content_changed selector d1 d2)
  in

  (* Handle each modification case *)
  match (decls1, decls2) with
  | [], [] -> reorder_or_content sel1_str decls1 decls2
  | [], _ | _, [] -> Some (content_changed sel1_str decls1 decls2)
  | _, _ when sel1_str <> sel2_str ->
      Some
        (Selector_changed
           {
             old_selector = sel1_str;
             new_selector = sel2_str;
             declarations = decls2;
           })
  | _, _ when decls1 = decls2 -> reorder_or_content sel1_str decls1 decls2
  | _, _ ->
      let pure, property_changes, added_props, removed_props =
        is_pure_decl_reordering decls1 decls2
      in
      if pure then
        if position_changed () then Some (reordered sel1_str)
        else if decls_str_equal decls1 decls2 then
          (* OCaml ASTs differ but string output is identical (e.g., Nested vs
             bare expression after calc() normalization) — no real difference *)
          None
        else if reorder_is_significant decls1 decls2 then
          Some (decl_level_reorder sel1_str decls1 decls2)
        else (* cascade-neutral reorder of disjoint declarations *) None
      else if property_changes <> [] || added_props <> [] || removed_props <> []
      then Some (content_changed sel1_str decls1 decls2)
      else reorder_or_content sel1_str decls1 decls2

(* Assemble rule changes (added/removed/modified) between two rule lists *)
let to_rule_changes rules1 rules2 : rule_diff list =
  let r_added, r_removed, r_modified, r_regrouped = rule_diffs rules1 rules2 in
  List.map convert_added_rule r_added
  @ List.map convert_removed_rule r_removed
  @ List.filter_map (convert_modified_rule ~rules1 ~rules2) r_modified
  @ r_regrouped

(* Generic helpers for processing nested containers *)
let extract_items_with_positions extract_fn stmts =
  List.mapi
    (fun i stmt ->
      match extract_fn stmt with
      | Some (cond, rules) -> Some (i, cond, rules)
      | None -> None)
    stmts
  |> List.filter_map (fun x -> x)

let group_by_condition items =
  let tbl = Hashtbl.create 16 in
  List.iter
    (fun (pos, cond, rules) ->
      let existing = try Hashtbl.find tbl cond with Not_found -> [] in
      Hashtbl.replace tbl cond (existing @ [ (pos, rules) ]))
    items;
  tbl

let block_positions_differ blocks1_list blocks2_list =
  List.length blocks1_list = List.length blocks2_list
  &&
  let pos1_list = List.map fst blocks1_list in
  let pos2_list = List.map fst blocks2_list in
  List.exists2 (fun p1 p2 -> abs (p1 - p2) > 10) pos1_list pos2_list

let block_structure_differs blocks1_list blocks2_list =
  List.length blocks1_list <> List.length blocks2_list
  || block_positions_differ blocks1_list blocks2_list

let detect_block_structure_changes blocks1 blocks2 =
  let block_structure_changed = Hashtbl.create 16 in
  Hashtbl.iter
    (fun cond blocks1_list ->
      match Hashtbl.find_opt blocks2 cond with
      | Some blocks2_list ->
          if block_structure_differs blocks1_list blocks2_list then
            Hashtbl.replace block_structure_changed cond
              (blocks1_list, blocks2_list)
      | _ -> ())
    blocks1;
  block_structure_changed

let only_declaration_reorders rule_changes nested_containers =
  rule_changes <> []
  && List.for_all
       (fun (diff : rule_diff) ->
         match diff with
         | Reordered { old_declarations = Some _; new_declarations = Some _; _ }
           ->
             true
         | _ -> false)
       rule_changes
  && nested_containers = []

let container_position extract_fn cond stmts =
  let rec go i = function
    | [] -> None
    | stmt :: rest -> (
        match extract_fn stmt with
        | Some (c, _) when c = cond -> Some i
        | _ -> go (i + 1) rest)
  in
  go 0 stmts

let reordered_container container_type cond rules1 pos1 pos2 =
  Reordered
    {
      info = { container_type; condition = cond; rules = rules1 };
      expected_pos = pos1;
      actual_pos = pos2;
    }

let modified_container container_type cond rules1 rules2 rule_changes
    nested_containers =
  Modified
    {
      info = { container_type; condition = cond; rules = rules1 };
      actual_rules = rules2;
      rule_changes;
      container_changes = nested_containers;
    }

let detect_order_only_change ~container_type added removed items1 items2 =
  if added <> [] || removed <> [] then None
  else if List.length items1 <> List.length items2 || items1 = [] then None
  else
    let conds1 = List.map fst items1 in
    let conds2 = List.map fst items2 in
    if conds1 = conds2 then None
    else
      match (items1, items2) with
      | (cond, rules1) :: _, (_, rules2) :: _ ->
          Some
            (Modified
               {
                 info = { container_type; condition = cond; rules = rules1 };
                 actual_rules = rules2;
                 rule_changes = [];
                 container_changes = [];
               })
      | _ -> None

let property_diff items1 items2 =
  let key_of (Css.Property_info { name; _ }) = name in
  let key_equal = String.equal in
  let is_empty_diff prop1 prop2 =
    let (Css.Property_info { name = n1; inherits = i1; _ }) = prop1 in
    let (Css.Property_info { name = n2; inherits = i2; _ }) = prop2 in
    n1 = n2 && i1 = i2
  in
  let added, removed, modified_pairs =
    diffs ~key_of ~key_equal ~is_empty_diff items1 items2
  in
  let added =
    List.map (fun (Css.Property_info { name; _ }) -> (name, [])) added
  in
  let removed =
    List.map (fun (Css.Property_info { name; _ }) -> (name, [])) removed
  in
  let modified =
    List.map
      (fun (Css.Property_info { name; _ }, _) -> (name, [], []))
      modified_pairs
  in
  (added, removed, modified)

let property_reorder_diff names2 (i1, name1) =
  let i2 = List.find_index (( = ) name1) names2 |> Option.value ~default:i1 in
  if i1 = i2 then None
  else
    let swapped_with =
      if i1 < List.length names2 then Some ("@property " ^ List.nth names2 i1)
      else None
    in
    (Some
       (Reordered
          {
            selector = "@property " ^ name1;
            expected_pos = i1;
            actual_pos = i2;
            swapped_with;
            old_declarations = None;
            new_declarations = None;
          })
      : rule_diff option)

let property_reorder_container stmts1 stmts2 reorder_diffs =
  match reorder_diffs with
  | [] -> []
  | _ ->
      [
        Modified
          {
            info =
              {
                container_type = `Property;
                condition = "@property rules";
                rules = stmts1;
              };
            actual_rules = stmts2;
            rule_changes = reorder_diffs;
            container_changes = [];
          };
      ]

let property_reorder_diffs stmts1 stmts2 items1 items2 =
  let get_names items =
    List.map (fun (Css.Property_info { name; _ }) -> name) items
  in
  let names1 = get_names items1 in
  let names2 = get_names items2 in
  let names1_set = List.sort String.compare names1 in
  let names2_set = List.sort String.compare names2 in
  if not (names1_set = names2_set && names1 <> names2 && names1 <> []) then []
  else
    let reorder_diffs =
      List.filter_map
        (property_reorder_diff names2)
        (List.mapi (fun i n -> (i, n)) names1)
    in
    property_reorder_container stmts1 stmts2 reorder_diffs

let extract_media_as_string stmt =
  match Css.as_media stmt with
  | Some (cond, rules) -> Some (Css.Media.to_string cond, rules)
  | None -> None

let extract_supports_as_string stmt =
  match Css.as_supports stmt with
  | Some (cond, rules) -> Some (Css.Supports.to_string cond, rules)
  | None -> None

let keyframes_container_info name =
  { container_type = `Layer; condition = "@keyframes " ^ name; rules = [] }

let keyframe_frames_diff frames1 frames2 =
  let key_of (frame : Css.keyframe) = frame.selector in
  let key_equal = Css.Keyframe.selector_equal in
  let is_empty_diff (f1 : Css.keyframe) (f2 : Css.keyframe) =
    Css.Keyframe.selector_equal f1.selector f2.selector
    && f1.declarations = f2.declarations
  in
  let added, removed, modified_pairs =
    diffs ~key_of ~key_equal ~is_empty_diff frames1 frames2
  in
  let selector_str (frame : Css.keyframe) =
    Css.Keyframe.string_of_selector frame.selector
  in
  let added_changes =
    List.map
      (fun (frame : Css.keyframe) ->
        (Added { selector = selector_str frame; declarations = [] } : rule_diff))
      added
  in
  let removed_changes =
    List.map
      (fun (frame : Css.keyframe) ->
        (Removed { selector = selector_str frame; declarations = [] }
          : rule_diff))
      removed
  in
  let modified_changes =
    List.filter_map
      (fun ((f1 : Css.keyframe), (f2 : Css.keyframe)) ->
        if f1.declarations <> f2.declarations then
          Some
            (Content_changed
               {
                 selector = selector_str f1;
                 old_declarations = [];
                 new_declarations = [];
                 property_changes = [];
                 added_properties = [];
                 removed_properties = [];
               })
        else None)
      modified_pairs
  in
  added_changes @ removed_changes @ modified_changes

let keyframes_diff items1 items2 =
  let key_of (name, _) = name in
  let key_equal = String.equal in
  let is_empty_diff (name1, frames1) (name2, frames2) =
    name1 = name2 && frames1 = frames2
  in
  diffs ~key_of ~key_equal ~is_empty_diff items1 items2

let process_nested_keyframes ~depth:_ stmts1 stmts2 =
  let items1 = List.filter_map Css.as_keyframes stmts1 in
  let items2 = List.filter_map Css.as_keyframes stmts2 in
  let added, removed, modified = keyframes_diff items1 items2 in
  let added_diffs =
    List.map
      (fun (name, _frames) -> Added (keyframes_container_info name))
      added
  in
  let removed_diffs =
    List.map
      (fun (name, _frames) -> Removed (keyframes_container_info name))
      removed
  in
  let modified_diffs =
    List.filter_map
      (fun ((name, frames1), (_, frames2)) ->
        let frame_diffs = keyframe_frames_diff frames1 frames2 in
        if frame_diffs <> [] then
          Some
            (Modified
               {
                 info = keyframes_container_info name;
                 actual_rules = [];
                 rule_changes = frame_diffs;
                 container_changes = [];
               })
        else None)
      modified
  in
  added_diffs @ removed_diffs @ modified_diffs

let process_font_face_rules ~depth:_ stmts1 stmts2 =
  let items1 = List.filter_map Css.as_font_face stmts1 in
  let items2 = List.filter_map Css.as_font_face stmts2 in
  let diffs = ref [] in
  match (items1, items2) with
  | [], [] -> []
  | [], _ ->
      diffs :=
        Added { container_type = `Layer; condition = "@font-face"; rules = [] }
        :: !diffs;
      !diffs
  | _, [] ->
      diffs :=
        Removed
          { container_type = `Layer; condition = "@font-face"; rules = [] }
        :: !diffs;
      !diffs
  | descs1 :: _, descs2 :: _ ->
      if descs1 <> descs2 then
        diffs :=
          Modified
            {
              info =
                {
                  container_type = `Layer;
                  condition = "@font-face";
                  rules = [];
                };
              actual_rules = [];
              rule_changes = [];
              container_changes = [];
            }
          :: !diffs;
      !diffs

let container_condition_string name_opt condition =
  let cond_str =
    match condition with Some c -> Css.Container.to_string c | None -> ""
  in
  match name_opt with Some name -> name ^ " " ^ cond_str | None -> cond_str

let container_key (name_opt, condition, _) =
  (* Use both name and condition as key to distinguish different containers. *)
  String.concat ":"
    [
      Option.value ~default:"" name_opt;
      Option.fold ~none:"" ~some:Css.Container.to_string condition;
    ]

let condition_rules_of_container (name_opt, condition, rules) =
  (container_condition_string name_opt condition, rules)

let modified_container_of_pair ((name_opt, condition, rules1), (_, _, rules2)) =
  (container_condition_string name_opt condition, rules1, rules2)

(* Mutual recursion declarations *)
(* Check if two rule-lists under the same media condition differ *)
let rec media_condition_differs rules_list1 rules_list2 =
  let block_count_differs =
    List.length rules_list1 <> List.length rules_list2
  in
  let all_rules1 = List.concat rules_list1 in
  let all_rules2 = List.concat rules_list2 in
  let added_r, removed_r, modified_r, regrouped_r =
    rule_diffs all_rules1 all_rules2
  in
  let has_immediate =
    added_r <> [] || removed_r <> [] || modified_r <> [] || regrouped_r <> []
  in
  let has_nested = nested_differences ~depth:1 all_rules1 all_rules2 <> [] in
  if has_immediate || has_nested || block_count_differs then
    Some (all_rules1, all_rules2)
  else None

and media_diff items1 items2 =
  let group items =
    let tbl = Hashtbl.create 16 in
    List.iter
      (fun (cond, rules) ->
        let existing = try Hashtbl.find tbl cond with Not_found -> [] in
        Hashtbl.replace tbl cond (existing @ [ rules ]))
      items;
    tbl
  in
  let groups1 = group items1 in
  let groups2 = group items2 in
  let added = ref [] in
  let removed = ref [] in
  let modified = ref [] in
  Hashtbl.iter
    (fun cond rules_list1 ->
      match Hashtbl.find_opt groups2 cond with
      | None ->
          List.iter
            (fun rules -> removed := (cond, rules) :: !removed)
            rules_list1
      | Some rules_list2 -> (
          match media_condition_differs rules_list1 rules_list2 with
          | Some (r1, r2) -> modified := (cond, r1, r2) :: !modified
          | None -> ()))
    groups1;
  Hashtbl.iter
    (fun cond rules_list2 ->
      if not (Hashtbl.mem groups1 cond) then
        List.iter (fun rules -> added := (cond, rules) :: !added) rules_list2)
    groups2;
  (!added, !removed, !modified)

and process_modified_container ~container_type ~extract_fn ~depth ~stmts1
    ~stmts2 ~block_structure_changed cond rules1 rules2 =
  (* Skip if this condition has a block structure change *)
  if Hashtbl.mem block_structure_changed cond then None
  else
    let rule_changes = to_rule_changes rules1 rules2 in
    (* Recursively check deeper nesting *)
    let nested_containers =
      nested_differences ~depth:(depth + 1) rules1 rules2
    in
    (* Check for position changes within parent container *)
    let pos1 =
      container_position extract_fn cond stmts1 |> Option.value ~default:(-1)
    in
    let pos2 =
      container_position extract_fn cond stmts2 |> Option.value ~default:(-1)
    in
    let position_changed = pos1 >= 0 && pos2 >= 0 && abs (pos2 - pos1) > 3 in

    (* If only position changed with no content changes, report as reordered *)
    if position_changed && rule_changes = [] && nested_containers = [] then
      Some (reordered_container container_type cond rules1 pos1 pos2)
    else if not (only_declaration_reorders rule_changes nested_containers) then
      (* Container was modified in content, not just position *)
      Some
        (modified_container container_type cond rules1 rules2 rule_changes
           nested_containers)
    else None

and process_nested_containers ~container_type ~extract_fn ~diff_fn ~depth stmts1
    stmts2 =
  let items_with_pos1 = extract_items_with_positions extract_fn stmts1 in
  let items_with_pos2 = extract_items_with_positions extract_fn stmts2 in
  let block_structure_changed =
    detect_block_structure_changes
      (group_by_condition items_with_pos1)
      (group_by_condition items_with_pos2)
  in
  let items1 = List.filter_map extract_fn stmts1 in
  let items2 = List.filter_map extract_fn stmts2 in
  let added, removed, modified = diff_fn items1 items2 in
  let diffs = ref [] in
  Hashtbl.iter
    (fun cond (expected_blocks, actual_blocks) ->
      diffs :=
        Block_structure_changed
          { container_type; condition = cond; expected_blocks; actual_blocks }
        :: !diffs)
    block_structure_changed;
  List.iter
    (fun (cond, rules) ->
      diffs := Added { container_type; condition = cond; rules } :: !diffs)
    added;
  List.iter
    (fun (cond, rules) ->
      diffs := Removed { container_type; condition = cond; rules } :: !diffs)
    removed;
  List.iter
    (fun (cond, rules1, rules2) ->
      match
        process_modified_container ~container_type ~extract_fn ~depth ~stmts1
          ~stmts2 ~block_structure_changed cond rules1 rules2
      with
      | Some diff -> diffs := diff :: !diffs
      | None -> ())
    modified;
  (if !diffs = [] then
     match
       detect_order_only_change ~container_type added removed items1 items2
     with
     | Some d -> diffs := [ d ]
     | None -> ());
  !diffs

(* Layer diff function *)
and layer_diff items1 items2 =
  let key_of (name_opt, _) = Option.value ~default:"" name_opt in
  let key_equal = String.equal in
  let is_empty_diff (_, rules1) (_, rules2) =
    let a_r, r_r, m_r, rg_r = rule_diffs rules1 rules2 in
    let has_immediate_diffs =
      a_r <> [] || r_r <> [] || m_r <> [] || rg_r <> []
    in
    if has_immediate_diffs then false
    else
      (* Also check for nested differences *)
      let nested_diffs = nested_differences ~depth:1 rules1 rules2 in
      nested_diffs = []
  in
  let added, removed, modified_pairs =
    diffs ~key_of ~key_equal ~is_empty_diff items1 items2
  in
  (* Transform to consistent format with media_diff *)
  let added =
    List.map
      (fun (name_opt, rules) -> (Option.value ~default:"" name_opt, rules))
      added
  in
  let removed =
    List.map
      (fun (name_opt, rules) -> (Option.value ~default:"" name_opt, rules))
      removed
  in
  let modified =
    List.map
      (fun ((name_opt, rules1), (_, rules2)) ->
        (Option.value ~default:"" name_opt, rules1, rules2))
      modified_pairs
  in
  (added, removed, modified)

(* Shared helper: collect added/removed container diffs and process modified
   containers with the standard rule-change + nesting logic. *)
and collect_container_diffs ~container_type ~depth added removed modified =
  let diffs = ref [] in
  List.iter
    (fun (condition, rules) ->
      diffs := Added { container_type; condition; rules } :: !diffs)
    added;
  List.iter
    (fun (condition, rules) ->
      diffs := Removed { container_type; condition; rules } :: !diffs)
    removed;
  List.iter
    (fun (condition, rules1, rules2) ->
      let rule_changes = to_rule_changes rules1 rules2 in
      let nested_containers =
        nested_differences ~depth:(depth + 1) rules1 rules2
      in
      if
        (rule_changes <> [] || nested_containers <> [])
        && not (only_declaration_reorders rule_changes nested_containers)
      then
        diffs :=
          Modified
            {
              info = { container_type; condition; rules = rules1 };
              actual_rules = rules2;
              rule_changes;
              container_changes = nested_containers;
            }
          :: !diffs)
    modified;
  !diffs

(* Process layers separately due to different type signature *)
and process_nested_layers ~depth stmts1 stmts2 =
  let items1 = List.filter_map Css.as_layer stmts1 in
  let items2 = List.filter_map Css.as_layer stmts2 in
  let added, removed, modified = layer_diff items1 items2 in
  collect_container_diffs ~container_type:`Layer ~depth added removed modified

and container_has_no_diff (_, _, rules1) (_, _, rules2) =
  let a_r, r_r, m_r, rg_r = rule_diffs rules1 rules2 in
  let has_immediate_diffs = a_r <> [] || r_r <> [] || m_r <> [] || rg_r <> [] in
  if has_immediate_diffs then false
  else nested_differences ~depth:1 rules1 rules2 = []

(* Container diff function for @container rules *)
and container_diff items1 items2 =
  let key_equal = String.equal in
  let added, removed, modified_pairs =
    diffs ~key_of:container_key ~key_equal ~is_empty_diff:container_has_no_diff
      items1 items2
  in
  (* Transform to consistent format with media_diff. *)
  let added = List.map condition_rules_of_container added in
  let removed = List.map condition_rules_of_container removed in
  let modified = List.map modified_container_of_pair modified_pairs in
  (added, removed, modified)

(* Process container rules *)
and process_nested_containers_with_name ~depth stmts1 stmts2 =
  let items1 = List.filter_map Css.as_container stmts1 in
  let items2 = List.filter_map Css.as_container stmts2 in
  let added, removed, modified = container_diff items1 items2 in
  collect_container_diffs ~container_type:`Container ~depth added removed
    modified

(* Process property rules *)
and process_nested_properties ~depth stmts1 stmts2 =
  let items1 = List.filter_map Css.as_property stmts1 in
  let items2 = List.filter_map Css.as_property stmts2 in
  let added, removed, modified = property_diff items1 items2 in
  let diffs = ref [] in
  List.iter
    (fun (name, rules) ->
      diffs :=
        Added { container_type = `Property; condition = name; rules } :: !diffs)
    added;
  List.iter
    (fun (name, rules) ->
      diffs :=
        Removed { container_type = `Property; condition = name; rules }
        :: !diffs)
    removed;
  List.iter
    (fun (name, rules1, rules2) ->
      let rule_changes = to_rule_changes rules1 rules2 in
      let nested_containers =
        nested_differences ~depth:(depth + 1) rules1 rules2
      in
      diffs :=
        Modified
          {
            info =
              { container_type = `Property; condition = name; rules = rules1 };
            actual_rules = rules2;
            rule_changes;
            container_changes = nested_containers;
          }
        :: !diffs)
    modified;
  !diffs @ property_reorder_diffs stmts1 stmts2 items1 items2

(* Process CSS nesting: rules with nested child rules (& .foo { ... }) *)
and process_nested_rules ~depth stmts1 stmts2 =
  (* Extract (selector_key, nested_statements) for all rules, including those
     with empty nesting. This allows detecting when nesting is added/removed. *)
  let extract_nesting stmts =
    List.filter_map
      (fun stmt ->
        match Css.as_rule stmt with
        | Some (sel, _decls, nested) -> Some (Css.Selector.to_string sel, nested)
        | None -> None)
      stmts
  in
  let items1 = extract_nesting stmts1 in
  let items2 = extract_nesting stmts2 in
  (* Match by selector key and diff nested statements *)
  let diffs = ref [] in
  List.iter
    (fun (sel1, nested1) ->
      match List.find_opt (fun (s, _) -> s = sel1) items2 with
      | Some (_, nested2) when nested1 <> nested2 ->
          let rule_changes = to_rule_changes nested1 nested2 in
          let nested_containers =
            nested_differences ~depth:(depth + 1) nested1 nested2
          in
          if rule_changes <> [] || nested_containers <> [] then
            diffs :=
              Modified
                {
                  info =
                    {
                      container_type = `Nesting;
                      condition = sel1;
                      rules = nested1;
                    };
                  actual_rules = nested2;
                  rule_changes;
                  container_changes = nested_containers;
                }
              :: !diffs
      | Some _ -> () (* Same nesting *)
      | None -> ())
    items1;
  !diffs

(* Main recursive function for nested differences *)
and nested_differences ?(depth = 0) (stmts1 : Css.statement list)
    (stmts2 : Css.statement list) : container_diff list =
  if depth > 3 then [] (* Prevent infinite recursion *)
  else
    (* Process CSS nesting (& .foo { ... } inside rules) *)
    process_nested_rules ~depth stmts1 stmts2
    (* Process media queries *)
    @ process_nested_containers ~container_type:`Media
        ~extract_fn:extract_media_as_string ~diff_fn:media_diff ~depth stmts1
        stmts2
    (* Process layers - different type signature *)
    @ process_nested_layers ~depth stmts1 stmts2
    (* Process supports - reuses media_diff since they have the same
       structure *)
    @ process_nested_containers ~container_type:`Supports
        ~extract_fn:extract_supports_as_string ~diff_fn:media_diff ~depth stmts1
        stmts2
    (* Process container queries *)
    @ process_nested_containers_with_name ~depth stmts1 stmts2
    (* Process property declarations *)
    @ process_nested_properties ~depth stmts1 stmts2
    (* Process keyframes animations *)
    @ process_nested_keyframes ~depth stmts1 stmts2
    (* Process font-face rules *)
    @ process_font_face_rules ~depth stmts1 stmts2

(* Check if containers appear at different positions in statement sequence *)
let detect_container_position_changes stmts1 stmts2 containers =
  (* Build position maps for @media containers *)
  let build_media_position_map stmts =
    List.mapi
      (fun i stmt ->
        match Css.as_media stmt with
        | Some (cond, _) -> Some (Css.Media.to_string cond, i)
        | None -> None)
      stmts
    |> List.filter_map (fun x -> x)
    |> List.fold_left
         (fun acc (cond, pos) ->
           let existing = try List.assoc cond acc with Not_found -> [] in
           (cond, pos :: existing) :: List.remove_assoc cond acc)
         []
  in

  let pos_map1 = build_media_position_map stmts1 in
  let pos_map2 = build_media_position_map stmts2 in

  (* Enhance container_diffs with position info *)
  List.map
    (function
      | Modified
          ({
             info = { container_type = `Media; condition; _ };
             rule_changes;
             container_changes;
             _;
           } as cm)
        when rule_changes = [] && container_changes = [] ->
          (* No content changes - check if position changed *)
          let pos1 =
            try List.assoc condition pos_map1 |> List.hd
            with Not_found | Failure _ -> -1
          in
          let pos2 =
            try List.assoc condition pos_map2 |> List.hd
            with Not_found | Failure _ -> -1
          in
          if pos1 >= 0 && pos2 >= 0 && abs (pos2 - pos1) > 5 then
            (* Significant position change - report as structure difference *)
            Modified
              { cm with info = { cm.info with rules = [] }; actual_rules = [] }
          else Modified cm
      | other -> other)
    containers

(* Main diff function *)
(* @import and the other selectorless leaf rules collapse onto the universal
   selector key in [rule_diffs], so two distinct imports match as identical and
   their differences vanish. Compare them here on their serialised form, which
   captures the target URL, layer, supports condition and media query. Import
   order is cascade-significant, so a pure reorder is a difference too. *)
let import_strings stmts =
  List.filter_map
    (fun s ->
      match Css.as_import s with
      | Some _ ->
          Some
            (Css.Stylesheet.to_string ~minify:true (Css.v [ s ]) |> String.trim)
      | None -> None)
    stmts

(* [items] minus one occurrence for each element of [remove]. *)
let multiset_remove_each ~remove items =
  let counts = Hashtbl.create 16 in
  List.iter
    (fun x ->
      Hashtbl.replace counts x
        (1 + try Hashtbl.find counts x with Not_found -> 0))
    remove;
  List.filter
    (fun x ->
      match Hashtbl.find_opt counts x with
      | Some n when n > 0 ->
          Hashtbl.replace counts x (n - 1);
          false
      | _ -> true)
    items

(* Precondition: [l1] and [l2] hold the same imports in a different order. *)
let import_reorder l1 l2 : rule_diff option =
  let arr2 = Array.of_list l2 in
  let index_in_l2 s =
    let rec idx j =
      if j >= Array.length arr2 then 0
      else if arr2.(j) = s then j
      else idx (j + 1)
    in
    idx 0
  in
  let rec first_moved i = function
    | x :: rest ->
        if i < Array.length arr2 && arr2.(i) = x then first_moved (i + 1) rest
        else Some (i, x)
    | [] -> None
  in
  match first_moved 0 l1 with
  | None -> None
  | Some (expected_pos, moved) ->
      Some
        (Reordered
           {
             selector = moved;
             expected_pos;
             actual_pos = index_in_l2 moved;
             swapped_with = None;
             old_declarations = None;
             new_declarations = None;
           })

let process_imports stmts1 stmts2 : rule_diff list =
  let l1 = import_strings stmts1 and l2 = import_strings stmts2 in
  if l1 = l2 then []
  else if List.sort compare l1 = List.sort compare l2 then
    Option.to_list (import_reorder l1 l2)
  else
    List.map
      (fun s -> (Removed { selector = s; declarations = [] } : rule_diff))
      (multiset_remove_each ~remove:l2 l1)
    @ List.map
        (fun s -> (Added { selector = s; declarations = [] } : rule_diff))
        (multiset_remove_each ~remove:l1 l2)

let diff ~(expected : Css.t) ~(actual : Css.t) : t =
  let all1 = Css.statements expected in
  let all2 = Css.statements actual in
  (* Imports are diffed separately ([process_imports]); excluding them here
     keeps [rule_diffs] from matching every import on the universal key. *)
  let rules1 = List.filter (fun s -> Css.as_import s = None) all1 in
  let rules2 = List.filter (fun s -> Css.as_import s = None) all2 in
  let added, removed, modified, regrouped = rule_diffs rules1 rules2 in

  let rule_changes =
    List.map convert_added_rule added
    @ List.map convert_removed_rule removed
    @ List.filter_map (convert_modified_rule ~rules1 ~rules2) modified
    @ regrouped @ process_imports all1 all2
  in

  (* Delegate all container and nested-container diffs to the generic walker *)
  let containers =
    let base_containers = nested_differences ~depth:0 all1 all2 in
    detect_container_position_changes all1 all2 base_containers
  in

  { rules = rule_changes; containers }