purple-ssh 1.27.0

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

use crate::ssh_config::model::{ConfigElement, HostEntry, SshConfigFile};

use super::config::ProviderSection;
use super::{Provider, ProviderHost};

/// Result of a sync operation.
#[derive(Debug, Default)]
pub struct SyncResult {
    pub added: usize,
    pub updated: usize,
    pub removed: usize,
    pub unchanged: usize,
    /// Alias renames: (old_alias, new_alias) pairs.
    pub renames: Vec<(String, String)>,
}

/// Sanitize a server name into a valid SSH alias component.
/// Lowercase, non-alphanumeric chars become hyphens, collapse consecutive hyphens.
/// Falls back to "server" if the result would be empty (all-symbol/unicode names).
fn sanitize_name(name: &str) -> String {
    let mut result = String::new();
    for c in name.chars() {
        if c.is_ascii_alphanumeric() {
            result.push(c.to_ascii_lowercase());
        } else if !result.ends_with('-') {
            result.push('-');
        }
    }
    let trimmed = result.trim_matches('-').to_string();
    if trimmed.is_empty() {
        "server".to_string()
    } else {
        trimmed
    }
}

/// Build an alias from prefix + sanitized name.
/// If prefix is empty, uses just the sanitized name (no leading hyphen).
fn build_alias(prefix: &str, sanitized: &str) -> String {
    if prefix.is_empty() {
        sanitized.to_string()
    } else {
        format!("{}-{}", prefix, sanitized)
    }
}

/// Whether a metadata key is volatile (changes frequently without user action).
/// Volatile keys are excluded from the sync diff comparison so that a status
/// change alone does not trigger an SSH config rewrite. The value is still
/// stored and displayed when the host is updated for other reasons.
fn is_volatile_meta(key: &str) -> bool {
    key == "status"
}

/// Sync hosts from a cloud provider into the SSH config.
pub fn sync_provider(
    config: &mut SshConfigFile,
    provider: &dyn Provider,
    remote_hosts: &[ProviderHost],
    section: &ProviderSection,
    remove_deleted: bool,
    dry_run: bool,
) -> SyncResult {
    sync_provider_with_options(
        config,
        provider,
        remote_hosts,
        section,
        remove_deleted,
        dry_run,
        false,
    )
}

/// Sync hosts from a cloud provider into the SSH config.
/// When `reset_tags` is true, local tags are replaced with provider tags
/// instead of being merged (cleans up stale tags).
pub fn sync_provider_with_options(
    config: &mut SshConfigFile,
    provider: &dyn Provider,
    remote_hosts: &[ProviderHost],
    section: &ProviderSection,
    remove_deleted: bool,
    dry_run: bool,
    reset_tags: bool,
) -> SyncResult {
    let mut result = SyncResult::default();

    // Build map of server_id -> alias (top-level only, no Include files).
    // Keep first occurrence if duplicate provider markers exist (e.g. manual copy).
    let existing = config.find_hosts_by_provider(provider.name());
    let mut existing_map: HashMap<String, String> = HashMap::new();
    for (alias, server_id) in &existing {
        existing_map
            .entry(server_id.clone())
            .or_insert_with(|| alias.clone());
    }

    // Build alias -> HostEntry lookup once (avoids quadratic host_entries() calls)
    let entries_map: HashMap<String, HostEntry> = config
        .host_entries()
        .into_iter()
        .map(|e| (e.alias.clone(), e))
        .collect();

    // Track which server IDs are still in the remote set (also deduplicates)
    let mut remote_ids: std::collections::HashSet<String> = std::collections::HashSet::new();

    // Only add group header if this provider has no existing hosts in config
    let mut needs_header = !dry_run && existing_map.is_empty();

    for remote in remote_hosts {
        if !remote_ids.insert(remote.server_id.clone()) {
            continue; // Skip duplicate server_id in same response
        }

        // Empty IP means the resource exists but has no resolvable address
        // (e.g. stopped VM, no static IP). Count it in remote_ids so --remove
        // won't delete it, but skip add/update.
        if remote.ip.is_empty() {
            if existing_map.contains_key(&remote.server_id) {
                result.unchanged += 1;
            }
            continue;
        }

        if let Some(existing_alias) = existing_map.get(&remote.server_id) {
            // Host exists, check if alias, IP or tags changed
            if let Some(entry) = entries_map.get(existing_alias) {
                // Included hosts are read-only; recognize them for dedup but skip mutations
                if entry.source_file.is_some() {
                    result.unchanged += 1;
                    continue;
                }

                // Check if alias prefix changed (e.g. "do" → "ocean")
                let sanitized = sanitize_name(&remote.name);
                let expected_alias = build_alias(&section.alias_prefix, &sanitized);
                let alias_changed = *existing_alias != expected_alias;

                let ip_changed = entry.hostname != remote.ip;
                let meta_changed = {
                    let mut local: Vec<(&str, &str)> = entry
                        .provider_meta
                        .iter()
                        .filter(|(k, _)| !is_volatile_meta(k))
                        .map(|(k, v)| (k.as_str(), v.as_str()))
                        .collect();
                    local.sort();
                    let mut remote_m: Vec<(&str, &str)> = remote
                        .metadata
                        .iter()
                        .filter(|(k, _)| !is_volatile_meta(k))
                        .map(|(k, v)| (k.as_str(), v.as_str()))
                        .collect();
                    remote_m.sort();
                    local != remote_m
                };
                let trimmed_remote: Vec<String> =
                    remote.tags.iter().map(|t| t.trim().to_string()).collect();
                let tags_changed = if reset_tags {
                    // Exact comparison (case-insensitive): replace local tags with provider tags
                    let mut sorted_local: Vec<String> =
                        entry.tags.iter().map(|t| t.to_lowercase()).collect();
                    sorted_local.sort();
                    let mut sorted_remote: Vec<String> =
                        trimmed_remote.iter().map(|t| t.to_lowercase()).collect();
                    sorted_remote.sort();
                    sorted_local != sorted_remote
                } else {
                    // Subset check (case-insensitive): only trigger when provider tags are missing locally
                    trimmed_remote.iter().any(|rt| {
                        !entry
                            .tags
                            .iter()
                            .any(|lt| lt.eq_ignore_ascii_case(rt))
                    })
                };
                if alias_changed || ip_changed || tags_changed || meta_changed {
                    if dry_run {
                        result.updated += 1;
                    } else {
                        // Compute the final alias (dedup handles collisions,
                        // excluding the host being renamed so it doesn't collide with itself)
                        let new_alias = if alias_changed {
                            config.deduplicate_alias_excluding(
                                &expected_alias,
                                Some(existing_alias),
                            )
                        } else {
                            existing_alias.clone()
                        };
                        // Re-evaluate: dedup may resolve back to the current alias
                        let alias_changed = new_alias != *existing_alias;

                        if alias_changed || ip_changed || tags_changed || meta_changed {
                            if alias_changed || ip_changed {
                                let updated = HostEntry {
                                    alias: new_alias.clone(),
                                    hostname: remote.ip.clone(),
                                    ..entry.clone()
                                };
                                config.update_host(existing_alias, &updated);
                            }
                            // Tags lookup uses the new alias after rename
                            let tags_alias =
                                if alias_changed { &new_alias } else { existing_alias };
                            if tags_changed {
                                if reset_tags {
                                    config.set_host_tags(tags_alias, &trimmed_remote);
                                } else {
                                    // Merge (case-insensitive): keep existing local tags, add missing remote tags
                                    let mut merged = entry.tags.clone();
                                    for rt in &trimmed_remote {
                                        if !merged.iter().any(|t| t.eq_ignore_ascii_case(rt)) {
                                            merged.push(rt.clone());
                                        }
                                    }
                                    config.set_host_tags(tags_alias, &merged);
                                }
                            }
                            // Update provider marker with new alias
                            if alias_changed {
                                config.set_host_provider(
                                    &new_alias,
                                    provider.name(),
                                    &remote.server_id,
                                );
                                result.renames.push((existing_alias.clone(), new_alias.clone()));
                            }
                            // Update metadata
                            if meta_changed {
                                config.set_host_meta(tags_alias, &remote.metadata);
                            }
                            result.updated += 1;
                        } else {
                            result.unchanged += 1;
                        }
                    }
                } else {
                    result.unchanged += 1;
                }
            } else {
                result.unchanged += 1;
            }
        } else {
            // New host
            let sanitized = sanitize_name(&remote.name);
            let base_alias = build_alias(&section.alias_prefix, &sanitized);
            let alias = if dry_run {
                base_alias
            } else {
                config.deduplicate_alias(&base_alias)
            };

            if !dry_run {
                // Add group header before the very first host for this provider
                let wrote_header = needs_header;
                if needs_header {
                    if !config.elements.is_empty() && !config.last_element_has_trailing_blank() {
                        config
                            .elements
                            .push(ConfigElement::GlobalLine(String::new()));
                    }
                    config
                        .elements
                        .push(ConfigElement::GlobalLine(format!(
                            "# purple:group {}",
                            super::provider_display_name(provider.name())
                        )));
                    needs_header = false;
                }

                let entry = HostEntry {
                    alias: alias.clone(),
                    hostname: remote.ip.clone(),
                    user: section.user.clone(),
                    identity_file: section.identity_file.clone(),
                    tags: remote.tags.clone(),
                    provider: Some(provider.name().to_string()),
                    ..Default::default()
                };

                // Add blank line separator before host (skip when preceded by group header
                // so the header stays adjacent to the first host)
                if !wrote_header
                    && !config.elements.is_empty()
                    && !config.last_element_has_trailing_blank()
                {
                    config
                        .elements
                        .push(ConfigElement::GlobalLine(String::new()));
                }

                let block = SshConfigFile::entry_to_block(&entry);
                config.elements.push(ConfigElement::HostBlock(block));
                config.set_host_provider(&alias, provider.name(), &remote.server_id);
                if !remote.tags.is_empty() {
                    config.set_host_tags(&alias, &remote.tags);
                }
                if !remote.metadata.is_empty() {
                    config.set_host_meta(&alias, &remote.metadata);
                }
            }

            result.added += 1;
        }
    }

    // Remove deleted hosts (skip included hosts which are read-only)
    if remove_deleted && !dry_run {
        let to_remove: Vec<String> = existing_map
            .iter()
            .filter(|(id, _)| !remote_ids.contains(id.as_str()))
            .filter(|(_, alias)| {
                entries_map
                    .get(alias.as_str())
                    .is_none_or(|e| e.source_file.is_none())
            })
            .map(|(_, alias)| alias.clone())
            .collect();
        for alias in &to_remove {
            config.delete_host(alias);
        }
        result.removed = to_remove.len();

        // Clean up orphan provider header if all hosts for this provider were removed
        if config.find_hosts_by_provider(provider.name()).is_empty() {
            let header_text = format!("# purple:group {}", super::provider_display_name(provider.name()));
            config
                .elements
                .retain(|e| !matches!(e, ConfigElement::GlobalLine(line) if line == &header_text));
        }
    } else if remove_deleted {
        result.removed = existing_map
            .iter()
            .filter(|(id, _)| !remote_ids.contains(id.as_str()))
            .filter(|(_, alias)| {
                entries_map
                    .get(alias.as_str())
                    .is_none_or(|e| e.source_file.is_none())
            })
            .count();
    }

    result
}

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

    fn empty_config() -> SshConfigFile {
        SshConfigFile {
            elements: Vec::new(),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        }
    }

    fn make_section() -> ProviderSection {
        ProviderSection {
            provider: "digitalocean".to_string(),
            token: "test".to_string(),
            alias_prefix: "do".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        }
    }

    struct MockProvider;
    impl Provider for MockProvider {
        fn name(&self) -> &str {
            "digitalocean"
        }
        fn short_label(&self) -> &str {
            "do"
        }
        fn fetch_hosts_cancellable(
            &self,
            _token: &str,
            _cancel: &std::sync::atomic::AtomicBool,
        ) -> Result<Vec<ProviderHost>, super::super::ProviderError> {
            Ok(Vec::new())
        }
    }

    #[test]
    fn test_build_alias() {
        assert_eq!(build_alias("do", "web-1"), "do-web-1");
        assert_eq!(build_alias("", "web-1"), "web-1");
        assert_eq!(build_alias("ocean", "db"), "ocean-db");
    }

    #[test]
    fn test_sanitize_name() {
        assert_eq!(sanitize_name("web-1"), "web-1");
        assert_eq!(sanitize_name("My Server"), "my-server");
        assert_eq!(sanitize_name("test.prod.us"), "test-prod-us");
        assert_eq!(sanitize_name("--weird--"), "weird");
        assert_eq!(sanitize_name("UPPER"), "upper");
        assert_eq!(sanitize_name("a--b"), "a-b");
        assert_eq!(sanitize_name(""), "server");
        assert_eq!(sanitize_name("..."), "server");
    }

    #[test]
    fn test_sync_adds_new_hosts() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![
            ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("456".to_string(), "db-1".to_string(), "5.6.7.8".to_string(), Vec::new()),
        ];

        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 2);
        assert_eq!(result.updated, 0);
        assert_eq!(result.unchanged, 0);

        let entries = config.host_entries();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].alias, "do-web-1");
        assert_eq!(entries[0].hostname, "1.2.3.4");
        assert_eq!(entries[1].alias, "do-db-1");
    }

    #[test]
    fn test_sync_updates_changed_ip() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add host
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Second sync: IP changed
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "9.8.7.6".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.updated, 1);
        assert_eq!(result.added, 0);

        let entries = config.host_entries();
        assert_eq!(entries[0].hostname, "9.8.7.6");
    }

    #[test]
    fn test_sync_unchanged() {
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Same data again
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.added, 0);
        assert_eq!(result.updated, 0);
    }

    #[test]
    fn test_sync_removes_deleted() {
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 1);

        // Sync with empty remote list + remove_deleted
        let result =
            sync_provider(&mut config, &MockProvider, &[], &section, true, false);
        assert_eq!(result.removed, 1);
        assert_eq!(config.host_entries().len(), 0);
    }

    #[test]
    fn test_sync_dry_run_no_mutations() {
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];

        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, true);
        assert_eq!(result.added, 1);
        assert_eq!(config.host_entries().len(), 0); // No actual changes
    }

    #[test]
    fn test_sync_dedup_server_id_in_response() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![
            ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("123".to_string(), "web-1-dup".to_string(), "5.6.7.8".to_string(), Vec::new()),
        ];

        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 1);
        assert_eq!(config.host_entries().len(), 1);
        assert_eq!(config.host_entries()[0].alias, "do-web-1");
    }

    #[test]
    fn test_sync_duplicate_local_server_id_keeps_first() {
        // If duplicate provider markers exist locally, sync should use the first alias
        let content = "\
Host do-web-1
  HostName 1.2.3.4
  # purple:provider digitalocean:123

Host do-web-1-copy
  HostName 1.2.3.4
  # purple:provider digitalocean:123
";
        let mut config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };
        let section = make_section();

        // Remote has same server_id with updated IP
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "5.6.7.8".to_string(), Vec::new())];

        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        // Should update the first alias (do-web-1), not the copy
        assert_eq!(result.updated, 1);
        assert_eq!(result.added, 0);
        let entries = config.host_entries();
        let first = entries.iter().find(|e| e.alias == "do-web-1").unwrap();
        assert_eq!(first.hostname, "5.6.7.8");
        // Copy should remain unchanged
        let copy = entries.iter().find(|e| e.alias == "do-web-1-copy").unwrap();
        assert_eq!(copy.hostname, "1.2.3.4");
    }

    #[test]
    fn test_sync_no_duplicate_header_on_repeated_sync() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: adds header + host
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Second sync: new host added at provider
        let remote = vec![
            ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("456".to_string(), "db-1".to_string(), "5.6.7.8".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Should have exactly one header
        let header_count = config
            .elements
            .iter()
            .filter(|e| matches!(e, ConfigElement::GlobalLine(line) if line == "# purple:group DigitalOcean"))
            .count();
        assert_eq!(header_count, 1);
        assert_eq!(config.host_entries().len(), 2);
    }

    #[test]
    fn test_sync_removes_orphan_header() {
        let mut config = empty_config();
        let section = make_section();

        // Add a host
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Verify header exists
        let has_header = config
            .elements
            .iter()
            .any(|e| matches!(e, ConfigElement::GlobalLine(line) if line == "# purple:group DigitalOcean"));
        assert!(has_header);

        // Remove all hosts (empty remote + remove_deleted)
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, false);
        assert_eq!(result.removed, 1);

        // Header should be cleaned up
        let has_header = config
            .elements
            .iter()
            .any(|e| matches!(e, ConfigElement::GlobalLine(line) if line == "# purple:group DigitalOcean"));
        assert!(!has_header);
    }

    #[test]
    fn test_sync_writes_provider_tags() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["production".to_string(), "us-east".to_string()])];

        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        let entries = config.host_entries();
        assert_eq!(entries[0].tags, vec!["production", "us-east"]);
    }

    #[test]
    fn test_sync_updates_changed_tags() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add with tags
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["staging".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].tags, vec!["staging"]);

        // Second sync: new provider tags added — existing tags are preserved (merge)
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["production".to_string(), "us-east".to_string()])];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.updated, 1);
        assert_eq!(
            config.host_entries()[0].tags,
            vec!["staging", "production", "us-east"]
        );
    }

    #[test]
    fn test_sync_combined_add_update_remove() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add two hosts
        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.1.1.1".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "db".to_string(), "2.2.2.2".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 2);

        // Second sync: host 1 IP changed, host 2 removed, host 3 added
        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "9.9.9.9".to_string(), Vec::new()),
            ProviderHost::new("3".to_string(), "cache".to_string(), "3.3.3.3".to_string(), Vec::new()),
        ];
        let result =
            sync_provider(&mut config, &MockProvider, &remote, &section, true, false);
        assert_eq!(result.updated, 1);
        assert_eq!(result.added, 1);
        assert_eq!(result.removed, 1);

        let entries = config.host_entries();
        assert_eq!(entries.len(), 2); // web (updated) + cache (added), db removed
        assert_eq!(entries[0].alias, "do-web");
        assert_eq!(entries[0].hostname, "9.9.9.9");
        assert_eq!(entries[1].alias, "do-cache");
    }

    #[test]
    fn test_sync_tag_order_insensitive() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: tags in one order
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["beta".to_string(), "alpha".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Second sync: same tags, different order
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["alpha".to_string(), "beta".to_string()])];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 0);
    }

    fn config_with_include_provider_host() -> SshConfigFile {
        use crate::ssh_config::model::{IncludeDirective, IncludedFile};

        // Build an included host block with provider marker
        let content = "Host do-included\n  HostName 1.2.3.4\n  User root\n  # purple:provider digitalocean:inc1\n";
        let included_elements = SshConfigFile::parse_content(content);

        SshConfigFile {
            elements: vec![ConfigElement::Include(IncludeDirective {
                raw_line: "Include conf.d/*".to_string(),
                pattern: "conf.d/*".to_string(),
                resolved_files: vec![IncludedFile {
                    path: PathBuf::from("/tmp/included.conf"),
                    elements: included_elements,
                }],
            })],
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        }
    }

    #[test]
    fn test_sync_include_host_skips_update() {
        let mut config = config_with_include_provider_host();
        let section = make_section();

        // Remote has same server with different IP — should NOT update included host
        let remote = vec![ProviderHost::new("inc1".to_string(), "included".to_string(), "9.9.9.9".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 0);
        assert_eq!(result.added, 0);

        // Verify IP was NOT changed
        let entries = config.host_entries();
        let included = entries.iter().find(|e| e.alias == "do-included").unwrap();
        assert_eq!(included.hostname, "1.2.3.4");
    }

    #[test]
    fn test_sync_include_host_skips_remove() {
        let mut config = config_with_include_provider_host();
        let section = make_section();

        // Empty remote + remove_deleted — should NOT remove included host
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, false);
        assert_eq!(result.removed, 0);
        assert_eq!(config.host_entries().len(), 1);
    }

    #[test]
    fn test_sync_dry_run_remove_count() {
        let mut config = empty_config();
        let section = make_section();

        // Add two hosts
        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.1.1.1".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "db".to_string(), "2.2.2.2".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 2);

        // Dry-run remove with empty remote — should count but not mutate
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, true);
        assert_eq!(result.removed, 2);
        assert_eq!(config.host_entries().len(), 2); // Still there
    }

    #[test]
    fn test_sync_tags_cleared_remotely_preserved_locally() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: host with tags
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["production".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].tags, vec!["production"]);

        // Second sync: remote tags empty — local tags preserved (may be user-added)
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(config.host_entries()[0].tags, vec!["production"]);
    }

    #[test]
    fn test_sync_deduplicates_alias() {
        let content = "Host do-web-1\n  HostName 10.0.0.1\n";
        let mut config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };
        let section = make_section();

        let remote = vec![ProviderHost::new("999".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];

        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        let entries = config.host_entries();
        // Should have the original + a deduplicated one
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].alias, "do-web-1");
        assert_eq!(entries[1].alias, "do-web-1-2");
    }

    #[test]
    fn test_sync_renames_on_prefix_change() {
        let mut config = empty_config();
        let section = make_section(); // prefix = "do"

        // First sync: add host with "do" prefix
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].alias, "do-web-1");

        // Second sync: prefix changed to "ocean"
        let new_section = ProviderSection {
            alias_prefix: "ocean".to_string(),
            ..section
        };
        let result = sync_provider(&mut config, &MockProvider, &remote, &new_section, false, false);
        assert_eq!(result.updated, 1);
        assert_eq!(result.unchanged, 0);

        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].alias, "ocean-web-1");
        assert_eq!(entries[0].hostname, "1.2.3.4");
    }

    #[test]
    fn test_sync_rename_and_ip_change() {
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Change both prefix and IP
        let new_section = ProviderSection {
            alias_prefix: "ocean".to_string(),
            ..section
        };
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "9.9.9.9".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &new_section, false, false);
        assert_eq!(result.updated, 1);

        let entries = config.host_entries();
        assert_eq!(entries[0].alias, "ocean-web-1");
        assert_eq!(entries[0].hostname, "9.9.9.9");
    }

    #[test]
    fn test_sync_rename_dry_run_no_mutation() {
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        let new_section = ProviderSection {
            alias_prefix: "ocean".to_string(),
            ..section
        };
        let result = sync_provider(&mut config, &MockProvider, &remote, &new_section, false, true);
        assert_eq!(result.updated, 1);

        // Config should be unchanged (dry run)
        assert_eq!(config.host_entries()[0].alias, "do-web-1");
    }

    #[test]
    fn test_sync_no_rename_when_prefix_unchanged() {
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Same prefix, same everything — should be unchanged
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 0);
        assert_eq!(config.host_entries()[0].alias, "do-web-1");
    }

    #[test]
    fn test_sync_manual_comment_survives_cleanup() {
        // A manual "# DigitalOcean" comment (without purple:group prefix)
        // should NOT be removed when provider hosts are deleted
        let content = "# DigitalOcean\nHost do-web\n  HostName 1.2.3.4\n  User root\n  # purple:provider digitalocean:123\n";
        let mut config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };
        let section = make_section();

        // Remove all hosts (empty remote + remove_deleted)
        sync_provider(&mut config, &MockProvider, &[], &section, true, false);

        // The manual "# DigitalOcean" comment should survive (it doesn't have purple:group prefix)
        let has_manual = config
            .elements
            .iter()
            .any(|e| matches!(e, ConfigElement::GlobalLine(line) if line == "# DigitalOcean"));
        assert!(has_manual, "Manual comment without purple:group prefix should survive cleanup");
    }

    #[test]
    fn test_sync_rename_skips_included_host() {
        let mut config = config_with_include_provider_host();

        let new_section = ProviderSection {
            provider: "digitalocean".to_string(),
            token: "test".to_string(),
            alias_prefix: "ocean".to_string(), // Different prefix
            user: "root".to_string(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        };

        // Remote has the included host's server_id with a different prefix
        let remote = vec![ProviderHost::new("inc1".to_string(), "included".to_string(), "1.2.3.4".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &new_section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 0);

        // Alias should remain unchanged (included hosts are read-only)
        assert_eq!(config.host_entries()[0].alias, "do-included");
    }

    #[test]
    fn test_sync_rename_stable_with_manual_collision() {
        let mut config = empty_config();
        let section = make_section(); // prefix = "do"

        // First sync: add provider host
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].alias, "do-web-1");

        // Manually add a host that will collide with the renamed alias
        let manual = HostEntry {
            alias: "ocean-web-1".to_string(),
            hostname: "5.5.5.5".to_string(),
            ..Default::default()
        };
        config.add_host(&manual);

        // Second sync: prefix changes to "ocean", collides with manual host
        let new_section = ProviderSection {
            alias_prefix: "ocean".to_string(),
            ..section.clone()
        };
        let result = sync_provider(&mut config, &MockProvider, &remote, &new_section, false, false);
        assert_eq!(result.updated, 1);

        let entries = config.host_entries();
        let provider_host = entries.iter().find(|e| e.hostname == "1.2.3.4").unwrap();
        assert_eq!(provider_host.alias, "ocean-web-1-2");

        // Third sync: same state. Should be stable (not flip to -3)
        let result = sync_provider(&mut config, &MockProvider, &remote, &new_section, false, false);
        assert_eq!(result.unchanged, 1, "Should be unchanged on repeat sync");

        let entries = config.host_entries();
        let provider_host = entries.iter().find(|e| e.hostname == "1.2.3.4").unwrap();
        assert_eq!(provider_host.alias, "ocean-web-1-2", "Alias should be stable across syncs");
    }

    #[test]
    fn test_sync_preserves_user_tags() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add host with provider tag
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["nyc1".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].tags, vec!["nyc1"]);

        // User manually adds a tag via the TUI
        config.set_host_tags("do-web-1", &["nyc1".to_string(), "prod".to_string()]);
        assert_eq!(config.host_entries()[0].tags, vec!["nyc1", "prod"]);

        // Second sync: same provider tags — user tag "prod" must survive
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(config.host_entries()[0].tags, vec!["nyc1", "prod"]);
    }

    #[test]
    fn test_sync_merges_new_provider_tag_with_user_tags() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add host with provider tag
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["nyc1".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // User manually adds a tag
        config.set_host_tags("do-web-1", &["nyc1".to_string(), "critical".to_string()]);

        // Second sync: provider adds a new tag — user tag must be preserved
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["nyc1".to_string(), "v2".to_string()])];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.updated, 1);
        let tags = &config.host_entries()[0].tags;
        assert!(tags.contains(&"nyc1".to_string()));
        assert!(tags.contains(&"critical".to_string()));
        assert!(tags.contains(&"v2".to_string()));
    }

    #[test]
    fn test_sync_reset_tags_replaces_local_tags() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add host with provider tag
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["nyc1".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // User manually adds a tag
        config.set_host_tags("do-web-1", &["nyc1".to_string(), "prod".to_string()]);
        assert_eq!(config.host_entries()[0].tags, vec!["nyc1", "prod"]);

        // Sync with reset_tags: user tag "prod" is removed
        let result = sync_provider_with_options(
            &mut config, &MockProvider, &remote, &section, false, false, true,
        );
        assert_eq!(result.updated, 1);
        assert_eq!(config.host_entries()[0].tags, vec!["nyc1"]);
    }

    #[test]
    fn test_sync_reset_tags_clears_stale_tags() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: host with tags
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["staging".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Second sync with reset_tags: provider removed all tags
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        let result = sync_provider_with_options(
            &mut config, &MockProvider, &remote, &section, false, false, true,
        );
        assert_eq!(result.updated, 1);
        assert!(config.host_entries()[0].tags.is_empty());
    }

    #[test]
    fn test_sync_reset_tags_unchanged_when_matching() {
        let mut config = empty_config();
        let section = make_section();

        // Sync: add host with tags
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string(), "nyc1".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Reset-tags sync with same tags (different order): unchanged
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["nyc1".to_string(), "prod".to_string()])];
        let result = sync_provider_with_options(
            &mut config, &MockProvider, &remote, &section, false, false, true,
        );
        assert_eq!(result.unchanged, 1);
    }

    #[test]
    fn test_sync_merge_case_insensitive() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add host with lowercase tag
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].tags, vec!["prod"]);

        // Second sync: provider returns same tag with different casing — no duplicate
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["Prod".to_string()])];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(config.host_entries()[0].tags, vec!["prod"]);
    }

    #[test]
    fn test_sync_reset_tags_case_insensitive_unchanged() {
        let mut config = empty_config();
        let section = make_section();

        // Sync: add host with tag
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Reset-tags sync with different casing: unchanged (case-insensitive comparison)
        let remote = vec![ProviderHost::new("123".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), vec!["Prod".to_string()])];
        let result = sync_provider_with_options(
            &mut config, &MockProvider, &remote, &section, false, false, true,
        );
        assert_eq!(result.unchanged, 1);
    }

    // --- Empty IP (stopped/no-IP VM) tests ---

    #[test]
    fn test_sync_empty_ip_not_added() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("100".to_string(), "stopped-vm".to_string(), String::new(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 0);
        assert_eq!(config.host_entries().len(), 0);
    }

    #[test]
    fn test_sync_empty_ip_existing_host_unchanged() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add host with IP
        let remote = vec![ProviderHost::new("100".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 1);
        assert_eq!(config.host_entries()[0].hostname, "1.2.3.4");

        // Second sync: VM stopped, empty IP. Host should stay unchanged.
        let remote = vec![ProviderHost::new("100".to_string(), "web".to_string(), String::new(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 0);
        assert_eq!(config.host_entries()[0].hostname, "1.2.3.4");
    }

    #[test]
    fn test_sync_remove_skips_empty_ip_hosts() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add two hosts
        let remote = vec![
            ProviderHost::new("100".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("200".to_string(), "db".to_string(), "5.6.7.8".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 2);

        // Second sync with --remove: web is running, db is stopped (empty IP).
        // db must NOT be removed.
        let remote = vec![
            ProviderHost::new("100".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("200".to_string(), "db".to_string(), String::new(), Vec::new()),
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, true, false);
        assert_eq!(result.removed, 0);
        assert_eq!(result.unchanged, 2);
        assert_eq!(config.host_entries().len(), 2);
    }

    #[test]
    fn test_sync_remove_deletes_truly_gone_hosts() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add two hosts
        let remote = vec![
            ProviderHost::new("100".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("200".to_string(), "db".to_string(), "5.6.7.8".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 2);

        // Second sync with --remove: only web exists. db is truly deleted.
        let remote = vec![ProviderHost::new("100".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, true, false);
        assert_eq!(result.removed, 1);
        assert_eq!(config.host_entries().len(), 1);
        assert_eq!(config.host_entries()[0].alias, "do-web");
    }

    #[test]
    fn test_sync_mixed_resolved_empty_and_missing() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: add three hosts
        let remote = vec![
            ProviderHost::new("1".to_string(), "running".to_string(), "1.1.1.1".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "stopped".to_string(), "2.2.2.2".to_string(), Vec::new()),
            ProviderHost::new("3".to_string(), "deleted".to_string(), "3.3.3.3".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 3);

        // Second sync with --remove:
        // - "running" has new IP (updated)
        // - "stopped" has empty IP (unchanged, not removed)
        // - "deleted" not in list (removed)
        let remote = vec![
            ProviderHost::new("1".to_string(), "running".to_string(), "9.9.9.9".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "stopped".to_string(), String::new(), Vec::new()),
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, true, false);
        assert_eq!(result.updated, 1);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.removed, 1);

        let entries = config.host_entries();
        assert_eq!(entries.len(), 2);
        // Running host got new IP
        let running = entries.iter().find(|e| e.alias == "do-running").unwrap();
        assert_eq!(running.hostname, "9.9.9.9");
        // Stopped host kept old IP
        let stopped = entries.iter().find(|e| e.alias == "do-stopped").unwrap();
        assert_eq!(stopped.hostname, "2.2.2.2");
    }

    // =========================================================================
    // sanitize_name edge cases
    // =========================================================================

    #[test]
    fn test_sanitize_name_unicode() {
        // Unicode chars become hyphens, collapsed
        assert_eq!(sanitize_name("서버-1"), "1");
    }

    #[test]
    fn test_sanitize_name_numbers_only() {
        assert_eq!(sanitize_name("12345"), "12345");
    }

    #[test]
    fn test_sanitize_name_mixed_special_chars() {
        assert_eq!(sanitize_name("web@server#1!"), "web-server-1");
    }

    #[test]
    fn test_sanitize_name_tabs_and_newlines() {
        assert_eq!(sanitize_name("web\tserver\n1"), "web-server-1");
    }

    #[test]
    fn test_sanitize_name_consecutive_specials() {
        assert_eq!(sanitize_name("a!!!b"), "a-b");
    }

    #[test]
    fn test_sanitize_name_trailing_special() {
        assert_eq!(sanitize_name("web-"), "web");
    }

    #[test]
    fn test_sanitize_name_leading_special() {
        assert_eq!(sanitize_name("-web"), "web");
    }

    // =========================================================================
    // build_alias edge cases
    // =========================================================================

    #[test]
    fn test_build_alias_prefix_with_hyphen() {
        // If prefix already ends with hyphen, double hyphen results
        // The caller is expected to provide clean prefixes
        assert_eq!(build_alias("do-", "web-1"), "do--web-1");
    }

    #[test]
    fn test_build_alias_long_names() {
        assert_eq!(build_alias("my-provider", "my-very-long-server-name"), "my-provider-my-very-long-server-name");
    }

    // =========================================================================
    // sync with user and identity_file
    // =========================================================================

    #[test]
    fn test_sync_applies_user_from_section() {
        let mut config = empty_config();
        let mut section = make_section();
        section.user = "admin".to_string();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let entries = config.host_entries();
        assert_eq!(entries[0].user, "admin");
    }

    #[test]
    fn test_sync_applies_identity_file_from_section() {
        let mut config = empty_config();
        let mut section = make_section();
        section.identity_file = "~/.ssh/id_rsa".to_string();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let entries = config.host_entries();
        assert_eq!(entries[0].identity_file, "~/.ssh/id_rsa");
    }

    #[test]
    fn test_sync_empty_user_not_set() {
        let mut config = empty_config();
        let mut section = make_section();
        section.user = String::new(); // explicitly clear user
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let entries = config.host_entries();
        assert!(entries[0].user.is_empty());
    }

    // =========================================================================
    // SyncResult struct
    // =========================================================================

    #[test]
    fn test_sync_result_default() {
        let result = SyncResult::default();
        assert_eq!(result.added, 0);
        assert_eq!(result.updated, 0);
        assert_eq!(result.removed, 0);
        assert_eq!(result.unchanged, 0);
        assert!(result.renames.is_empty());
    }

    // =========================================================================
    // sync with multiple operations in one call
    // =========================================================================

    #[test]
    fn test_sync_server_name_change_updates_alias() {
        let mut config = empty_config();
        let section = make_section();
        // Add initial host
        let remote = vec![ProviderHost::new("1".to_string(), "old-name".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].alias, "do-old-name");

        // Sync with new name (same server_id)
        let remote_renamed = vec![ProviderHost::new("1".to_string(), "new-name".to_string(), "1.2.3.4".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote_renamed, &section, false, false);
        // Should rename the alias
        assert!(!result.renames.is_empty() || result.updated > 0);
    }

    #[test]
    fn test_sync_idempotent_same_data() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 0);
        assert_eq!(result.updated, 0);
        assert_eq!(result.unchanged, 1);
    }

    // =========================================================================
    // Tag merge edge cases
    // =========================================================================

    #[test]
    fn test_sync_tag_merge_case_insensitive_no_duplicate() {
        let mut config = empty_config();
        let section = make_section();
        // Add host with tag "Prod"
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["Prod".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Sync again with "prod" (lowercase) - should NOT add duplicate
        let remote2 = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string()])];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 0);
    }

    #[test]
    fn test_sync_tag_merge_adds_new_remote_tag() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Sync with additional tag "us-east"
        let remote2 = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string(), "us-east".to_string()])];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.updated, 1);

        // Verify both tags present
        let entries = config.host_entries();
        let entry = entries.iter().find(|e| e.alias == "do-web").unwrap();
        assert!(entry.tags.iter().any(|t| t == "prod"));
        assert!(entry.tags.iter().any(|t| t == "us-east"));
    }

    #[test]
    fn test_sync_tag_merge_preserves_local_tags() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Manually add a local tag
        config.set_host_tags("do-web", &["prod".to_string(), "my-custom".to_string()]);

        // Sync again with only "prod" - local "my-custom" should survive
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        let entries = config.host_entries();
        let entry = entries.iter().find(|e| e.alias == "do-web").unwrap();
        assert!(entry.tags.iter().any(|t| t == "my-custom"));
    }

    #[test]
    fn test_sync_reset_tags_replaces_local() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Add local-only tag
        config.set_host_tags("do-web", &["prod".to_string(), "my-custom".to_string()]);

        // Sync with reset_tags=true
        let remote2 = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["prod".to_string(), "new-tag".to_string()])];
        let result = sync_provider_with_options(&mut config, &MockProvider, &remote2, &section, false, false, true);
        assert_eq!(result.updated, 1);

        let entries = config.host_entries();
        let entry = entries.iter().find(|e| e.alias == "do-web").unwrap();
        assert!(entry.tags.iter().any(|t| t == "new-tag"));
        // "my-custom" should be gone with reset_tags
        assert!(!entry.tags.iter().any(|t| t == "my-custom"));
    }

    // =========================================================================
    // Rename + tag change simultaneously
    // =========================================================================

    #[test]
    fn test_sync_rename_and_ip_change_simultaneously() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "old-name".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Both name and IP change
        let remote2 = vec![ProviderHost::new("1".to_string(), "new-name".to_string(), "9.8.7.6".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.updated, 1);
        assert_eq!(result.renames.len(), 1);
        assert_eq!(result.renames[0].0, "do-old-name");
        assert_eq!(result.renames[0].1, "do-new-name");

        let entries = config.host_entries();
        let entry = entries.iter().find(|e| e.alias == "do-new-name").unwrap();
        assert_eq!(entry.hostname, "9.8.7.6");
    }

    // =========================================================================
    // Duplicate server_id in remote response
    // =========================================================================

    #[test]
    fn test_sync_duplicate_server_id_deduped() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("1".to_string(), "web-copy".to_string(), "5.6.7.8".to_string(), Vec::new()), // duplicate server_id
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 1); // Only first one added
        assert_eq!(config.host_entries().len(), 1);
    }

    // =========================================================================
    // Empty remote list with remove_deleted
    // =========================================================================

    #[test]
    fn test_sync_remove_all_when_remote_empty() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "db".to_string(), "5.6.7.8".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 2);

        // Sync with empty remote list and remove_deleted
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, false);
        assert_eq!(result.removed, 2);
        assert_eq!(config.host_entries().len(), 0);
    }

    // =========================================================================
    // Header management
    // =========================================================================

    #[test]
    fn test_sync_adds_group_header_on_first_host() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Check that a GlobalLine with group header exists
        let has_header = config.elements.iter().any(|e| {
            matches!(e, ConfigElement::GlobalLine(line) if line.contains("purple:group") && line.contains("DigitalOcean"))
        });
        assert!(has_header);
    }

    #[test]
    fn test_sync_removes_header_when_all_hosts_deleted() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Remove all hosts
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, false);
        assert_eq!(result.removed, 1);

        // Header should be cleaned up
        let has_header = config.elements.iter().any(|e| {
            matches!(e, ConfigElement::GlobalLine(line) if line.contains("purple:group") && line.contains("DigitalOcean"))
        });
        assert!(!has_header);
    }

    // =========================================================================
    // Identity file applied on new hosts
    // =========================================================================

    #[test]
    fn test_sync_identity_file_set_on_new_host() {
        let mut config = empty_config();
        let mut section = make_section();
        section.identity_file = "~/.ssh/do_key".to_string();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let entries = config.host_entries();
        assert_eq!(entries[0].identity_file, "~/.ssh/do_key");
    }

    // =========================================================================
    // Alias collision deduplication
    // =========================================================================

    #[test]
    fn test_sync_alias_collision_dedup() {
        let mut config = empty_config();
        let section = make_section();
        // Two remote hosts with same sanitized name but different server_ids
        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "web".to_string(), "5.6.7.8".to_string(), Vec::new()), // same name, different server
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 2);

        let entries = config.host_entries();
        let aliases: Vec<&str> = entries.iter().map(|e| e.alias.as_str()).collect();
        assert!(aliases.contains(&"do-web"));
        assert!(aliases.contains(&"do-web-2")); // Deduped with suffix
    }

    // =========================================================================
    // Empty alias_prefix
    // =========================================================================

    #[test]
    fn test_sync_empty_alias_prefix() {
        let mut config = empty_config();
        let mut section = make_section();
        section.alias_prefix = String::new();
        let remote = vec![ProviderHost::new("1".to_string(), "web-1".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let entries = config.host_entries();
        assert_eq!(entries[0].alias, "web-1"); // No prefix, just sanitized name
    }

    // =========================================================================
    // Dry-run counts consistency
    // =========================================================================

    #[test]
    fn test_sync_dry_run_add_count() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "db".to_string(), "5.6.7.8".to_string(), Vec::new()),
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, true);
        assert_eq!(result.added, 2);
        // Config should be unchanged in dry-run
        assert_eq!(config.host_entries().len(), 0);
    }

    #[test]
    fn test_sync_dry_run_remove_count_preserves_config() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries().len(), 1);

        // Dry-run remove
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, true);
        assert_eq!(result.removed, 1);
        // Config should still have the host
        assert_eq!(config.host_entries().len(), 1);
    }

    // =========================================================================
    // Result struct
    // =========================================================================

    #[test]
    fn test_sync_result_counts_add_up() {
        let mut config = empty_config();
        let section = make_section();
        // Add 3 hosts
        let remote = vec![
            ProviderHost::new("1".to_string(), "a".to_string(), "1.1.1.1".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "b".to_string(), "2.2.2.2".to_string(), Vec::new()),
            ProviderHost::new("3".to_string(), "c".to_string(), "3.3.3.3".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Sync with: 1 unchanged, 1 ip changed, 1 removed (missing from remote)
        let remote2 = vec![
            ProviderHost::new("1".to_string(), "a".to_string(), "1.1.1.1".to_string(), Vec::new()), // unchanged
            ProviderHost::new("2".to_string(), "b".to_string(), "9.9.9.9".to_string(), Vec::new()), // IP changed
            // server_id "3" missing -> removed
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, true, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 1);
        assert_eq!(result.removed, 1);
        assert_eq!(result.added, 0);
    }

    // =========================================================================
    // Multiple renames in single sync
    // =========================================================================

    #[test]
    fn test_sync_multiple_renames() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![
            ProviderHost::new("1".to_string(), "old-a".to_string(), "1.1.1.1".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "old-b".to_string(), "2.2.2.2".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        let remote2 = vec![
            ProviderHost::new("1".to_string(), "new-a".to_string(), "1.1.1.1".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "new-b".to_string(), "2.2.2.2".to_string(), Vec::new()),
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.renames.len(), 2);
        assert_eq!(result.updated, 2);
    }

    // =========================================================================
    // Tag whitespace trimming
    // =========================================================================

    #[test]
    fn test_sync_tag_whitespace_trimmed_on_store() {
        let mut config = empty_config();
        let section = make_section();
        // Tags with whitespace get trimmed when written to config and parsed back
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["  production  ".to_string(), " us-east ".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let entries = config.host_entries();
        // Tags are trimmed during the write+parse roundtrip via set_host_tags
        assert_eq!(entries[0].tags, vec!["production", "us-east"]);
    }

    #[test]
    fn test_sync_tag_trimmed_remote_triggers_merge() {
        let mut config = empty_config();
        let section = make_section();
        // First sync: clean tags
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["production".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Second sync: same tag but trimmed comparison works correctly
        let remote2 = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["  production  ".to_string()])]; // whitespace trimmed before comparison
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        // Trimmed "production" matches existing "production" case-insensitively
        assert_eq!(result.unchanged, 1);
    }

    // =========================================================================
    // Cross-provider coexistence
    // =========================================================================

    struct MockProvider2;
    impl Provider for MockProvider2 {
        fn name(&self) -> &str {
            "vultr"
        }
        fn short_label(&self) -> &str {
            "vultr"
        }
        fn fetch_hosts_cancellable(
            &self,
            _token: &str,
            _cancel: &std::sync::atomic::AtomicBool,
        ) -> Result<Vec<ProviderHost>, super::super::ProviderError> {
            Ok(Vec::new())
        }
    }

    #[test]
    fn test_sync_two_providers_independent() {
        let mut config = empty_config();

        let do_section = make_section(); // prefix = "do"
        let vultr_section = ProviderSection {
            provider: "vultr".to_string(),
            token: "test".to_string(),
            alias_prefix: "vultr".to_string(),
            user: String::new(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        };

        // Sync DO hosts
        let do_remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &do_remote, &do_section, false, false);

        // Sync Vultr hosts
        let vultr_remote = vec![ProviderHost::new("abc".to_string(), "web".to_string(), "5.6.7.8".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider2, &vultr_remote, &vultr_section, false, false);

        let entries = config.host_entries();
        assert_eq!(entries.len(), 2);
        let aliases: Vec<&str> = entries.iter().map(|e| e.alias.as_str()).collect();
        assert!(aliases.contains(&"do-web"));
        assert!(aliases.contains(&"vultr-web"));
    }

    #[test]
    fn test_sync_remove_only_affects_own_provider() {
        let mut config = empty_config();
        let do_section = make_section();
        let vultr_section = ProviderSection {
            provider: "vultr".to_string(),
            token: "test".to_string(),
            alias_prefix: "vultr".to_string(),
            user: String::new(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        };

        // Add hosts from both providers
        let do_remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &do_remote, &do_section, false, false);

        let vultr_remote = vec![ProviderHost::new("abc".to_string(), "db".to_string(), "5.6.7.8".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider2, &vultr_remote, &vultr_section, false, false);
        assert_eq!(config.host_entries().len(), 2);

        // Remove all DO hosts - Vultr host should survive
        let result = sync_provider(&mut config, &MockProvider, &[], &do_section, true, false);
        assert_eq!(result.removed, 1);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].alias, "vultr-db");
    }

    // =========================================================================
    // Rename + tag change simultaneously
    // =========================================================================

    #[test]
    fn test_sync_rename_and_tag_change_simultaneously() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "old-name".to_string(), "1.2.3.4".to_string(), vec!["staging".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].alias, "do-old-name");
        assert_eq!(config.host_entries()[0].tags, vec!["staging"]);

        // Change name and add new tag
        let remote2 = vec![ProviderHost::new("1".to_string(), "new-name".to_string(), "1.2.3.4".to_string(), vec!["staging".to_string(), "prod".to_string()])];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.updated, 1);
        assert_eq!(result.renames.len(), 1);

        let entries = config.host_entries();
        let entry = entries.iter().find(|e| e.alias == "do-new-name").unwrap();
        assert!(entry.tags.contains(&"staging".to_string()));
        assert!(entry.tags.contains(&"prod".to_string()));
    }

    // =========================================================================
    // All-symbol server name fallback
    // =========================================================================

    #[test]
    fn test_sync_all_symbol_name_uses_server_fallback() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "!!!".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let entries = config.host_entries();
        assert_eq!(entries[0].alias, "do-server");
    }

    #[test]
    fn test_sync_unicode_name_uses_ascii_fallback() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "서버".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        let entries = config.host_entries();
        // Korean chars stripped, fallback to "server"
        assert_eq!(entries[0].alias, "do-server");
    }

    // =========================================================================
    // Dry-run update doesn't mutate
    // =========================================================================

    #[test]
    fn test_sync_dry_run_update_preserves_config() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Dry-run with IP change
        let remote2 = vec![ProviderHost::new("1".to_string(), "web".to_string(), "9.9.9.9".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, true);
        assert_eq!(result.updated, 1);
        // Config should still have old IP
        assert_eq!(config.host_entries()[0].hostname, "1.2.3.4");
    }

    // =========================================================================
    // No-op sync on empty config with empty remote
    // =========================================================================

    #[test]
    fn test_sync_empty_remote_empty_config_noop() {
        let mut config = empty_config();
        let section = make_section();
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, false);
        assert_eq!(result.added, 0);
        assert_eq!(result.updated, 0);
        assert_eq!(result.removed, 0);
        assert_eq!(result.unchanged, 0);
        assert!(config.host_entries().is_empty());
    }

    // =========================================================================
    // Large batch sync
    // =========================================================================

    #[test]
    fn test_sync_large_batch() {
        let mut config = empty_config();
        let section = make_section();
        let remote: Vec<ProviderHost> = (0..100)
            .map(|i| ProviderHost::new(format!("{}", i), format!("server-{}", i), format!("10.0.0.{}", i % 256), vec!["batch".to_string()]))
            .collect();
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 100);
        assert_eq!(config.host_entries().len(), 100);

        // Re-sync unchanged
        let result2 = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result2.unchanged, 100);
        assert_eq!(result2.added, 0);
    }

    // =========================================================================
    // Rename collision with self-exclusion
    // =========================================================================

    #[test]
    fn test_sync_rename_self_exclusion_no_collision() {
        // When renaming and the expected alias is already taken by this host itself,
        // deduplicate_alias_excluding should handle it (no -2 suffix)
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].alias, "do-web");

        // Re-sync with same name but different IP -> update, no rename
        let remote2 = vec![ProviderHost::new("1".to_string(), "web".to_string(), "9.9.9.9".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.updated, 1);
        assert!(result.renames.is_empty());
        assert_eq!(config.host_entries()[0].alias, "do-web"); // No suffix
    }

    // =========================================================================
    // Reset tags with rename: tags applied to new alias
    // =========================================================================

    #[test]
    fn test_sync_reset_tags_with_rename() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "old-name".to_string(), "1.2.3.4".to_string(), vec!["staging".to_string()])];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        config.set_host_tags("do-old-name", &["staging".to_string(), "custom".to_string()]);

        // Rename + reset_tags
        let remote2 = vec![ProviderHost::new("1".to_string(), "new-name".to_string(), "1.2.3.4".to_string(), vec!["production".to_string()])];
        let result = sync_provider_with_options(
            &mut config, &MockProvider, &remote2, &section, false, false, true,
        );
        assert_eq!(result.updated, 1);
        assert_eq!(result.renames.len(), 1);

        let entries = config.host_entries();
        let entry = entries.iter().find(|e| e.alias == "do-new-name").unwrap();
        assert_eq!(entry.tags, vec!["production"]);
        assert!(!entry.tags.contains(&"custom".to_string()));
    }

    // =========================================================================
    // Empty IP in first sync never added
    // =========================================================================

    #[test]
    fn test_sync_empty_ip_with_tags_not_added() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "stopped".to_string(), String::new(), vec!["prod".to_string()])];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 0);
        assert!(config.host_entries().is_empty());
    }

    // =========================================================================
    // Existing host not in entries_map (orphaned provider marker)
    // =========================================================================

    #[test]
    fn test_sync_orphaned_provider_marker_counts_unchanged() {
        // If a provider marker exists but the host block is somehow broken/missing
        // from host_entries(), the code path at line 217 counts it as unchanged.
        // This is hard to trigger naturally, but we can verify the behavior with
        // a host that has a provider marker but also exists in entries_map.
        let content = "\
Host do-web
  HostName 1.2.3.4
  # purple:provider digitalocean:123
";
        let mut config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };
        let section = make_section();
        let remote = vec![ProviderHost::new("123".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
    }

    // =========================================================================
    // Separator between hosts (no double blank lines)
    // =========================================================================

    #[test]
    fn test_sync_no_double_blank_between_hosts() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "db".to_string(), "5.6.7.8".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Verify no consecutive blank GlobalLines
        let mut prev_blank = false;
        for elem in &config.elements {
            if let ConfigElement::GlobalLine(line) = elem {
                let is_blank = line.trim().is_empty();
                assert!(!(prev_blank && is_blank), "Found consecutive blank lines");
                prev_blank = is_blank;
            } else {
                prev_blank = false;
            }
        }
    }

    // =========================================================================
    // Remove without remove_deleted flag does nothing
    // =========================================================================

    #[test]
    fn test_sync_without_remove_flag_keeps_deleted() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Sync without remove_deleted - host 1 gone from remote
        let result = sync_provider(&mut config, &MockProvider, &[], &section, false, false);
        assert_eq!(result.removed, 0);
        assert_eq!(config.host_entries().len(), 1); // Still there
    }

    // =========================================================================
    // Dry-run rename doesn't track renames
    // =========================================================================

    #[test]
    fn test_sync_dry_run_rename_no_renames_tracked() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "old".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        let new_section = ProviderSection {
            alias_prefix: "ocean".to_string(),
            ..section
        };
        let result = sync_provider(&mut config, &MockProvider, &remote, &new_section, false, true);
        assert_eq!(result.updated, 1);
        // Dry-run: renames vec stays empty since no actual mutation
        assert!(result.renames.is_empty());
    }

    // =========================================================================
    // sanitize_name additional edge cases
    // =========================================================================

    #[test]
    fn test_sanitize_name_whitespace_only() {
        assert_eq!(sanitize_name("   "), "server");
    }

    #[test]
    fn test_sanitize_name_single_char() {
        assert_eq!(sanitize_name("a"), "a");
        assert_eq!(sanitize_name("Z"), "z");
        assert_eq!(sanitize_name("5"), "5");
    }

    #[test]
    fn test_sanitize_name_single_special_char() {
        assert_eq!(sanitize_name("!"), "server");
        assert_eq!(sanitize_name("-"), "server");
        assert_eq!(sanitize_name("."), "server");
    }

    #[test]
    fn test_sanitize_name_emoji() {
        assert_eq!(sanitize_name("server🚀"), "server");
        assert_eq!(sanitize_name("🔥hot🔥"), "hot");
    }

    #[test]
    fn test_sanitize_name_long_mixed_separators() {
        assert_eq!(sanitize_name("a!@#$%^&*()b"), "a-b");
    }

    #[test]
    fn test_sanitize_name_dots_and_underscores() {
        assert_eq!(sanitize_name("web.prod_us-east"), "web-prod-us-east");
    }

    // =========================================================================
    // find_hosts_by_provider with includes
    // =========================================================================

    #[test]
    fn test_find_hosts_by_provider_in_includes() {
        use crate::ssh_config::model::{IncludeDirective, IncludedFile};

        let include_content = "Host do-included\n  HostName 1.2.3.4\n  # purple:provider digitalocean:inc1\n";
        let included_elements = SshConfigFile::parse_content(include_content);

        let config = SshConfigFile {
            elements: vec![ConfigElement::Include(IncludeDirective {
                raw_line: "Include conf.d/*".to_string(),
                pattern: "conf.d/*".to_string(),
                resolved_files: vec![IncludedFile {
                    path: PathBuf::from("/tmp/included.conf"),
                    elements: included_elements,
                }],
            })],
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        let hosts = config.find_hosts_by_provider("digitalocean");
        assert_eq!(hosts.len(), 1);
        assert_eq!(hosts[0].0, "do-included");
        assert_eq!(hosts[0].1, "inc1");
    }

    #[test]
    fn test_find_hosts_by_provider_mixed_includes_and_toplevel() {
        use crate::ssh_config::model::{IncludeDirective, IncludedFile};

        // Top-level host
        let top_content = "Host do-web\n  HostName 1.2.3.4\n  # purple:provider digitalocean:1\n";
        let top_elements = SshConfigFile::parse_content(top_content);

        // Included host
        let inc_content = "Host do-db\n  HostName 5.6.7.8\n  # purple:provider digitalocean:2\n";
        let inc_elements = SshConfigFile::parse_content(inc_content);

        let mut elements = top_elements;
        elements.push(ConfigElement::Include(IncludeDirective {
            raw_line: "Include conf.d/*".to_string(),
            pattern: "conf.d/*".to_string(),
            resolved_files: vec![IncludedFile {
                path: PathBuf::from("/tmp/included.conf"),
                elements: inc_elements,
            }],
        }));

        let config = SshConfigFile {
            elements,
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        let hosts = config.find_hosts_by_provider("digitalocean");
        assert_eq!(hosts.len(), 2);
    }

    #[test]
    fn test_find_hosts_by_provider_empty_includes() {
        use crate::ssh_config::model::{IncludeDirective, IncludedFile};

        let config = SshConfigFile {
            elements: vec![ConfigElement::Include(IncludeDirective {
                raw_line: "Include conf.d/*".to_string(),
                pattern: "conf.d/*".to_string(),
                resolved_files: vec![IncludedFile {
                    path: PathBuf::from("/tmp/empty.conf"),
                    elements: vec![],
                }],
            })],
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        let hosts = config.find_hosts_by_provider("digitalocean");
        assert!(hosts.is_empty());
    }

    #[test]
    fn test_find_hosts_by_provider_wrong_provider_name() {
        let content = "Host do-web\n  HostName 1.2.3.4\n  # purple:provider digitalocean:1\n";
        let config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        let hosts = config.find_hosts_by_provider("vultr");
        assert!(hosts.is_empty());
    }

    // =========================================================================
    // deduplicate_alias_excluding
    // =========================================================================

    #[test]
    fn test_deduplicate_alias_excluding_self() {
        // When renaming do-web to do-web (same alias), exclude prevents collision
        let content = "Host do-web\n  HostName 1.2.3.4\n";
        let config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        let alias = config.deduplicate_alias_excluding("do-web", Some("do-web"));
        assert_eq!(alias, "do-web"); // Self-excluded, no collision
    }

    #[test]
    fn test_deduplicate_alias_excluding_other() {
        // do-web exists, exclude is "do-db" (not the colliding one)
        let content = "Host do-web\n  HostName 1.2.3.4\n";
        let config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        let alias = config.deduplicate_alias_excluding("do-web", Some("do-db"));
        assert_eq!(alias, "do-web-2"); // do-web is taken, do-db doesn't help
    }

    #[test]
    fn test_deduplicate_alias_excluding_chain() {
        // do-web and do-web-2 exist, exclude is "do-web"
        let content = "Host do-web\n  HostName 1.1.1.1\n\nHost do-web-2\n  HostName 2.2.2.2\n";
        let config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        let alias = config.deduplicate_alias_excluding("do-web", Some("do-web"));
        // do-web is excluded, so it's "available" → returns do-web
        assert_eq!(alias, "do-web");
    }

    #[test]
    fn test_deduplicate_alias_excluding_none() {
        let content = "Host do-web\n  HostName 1.2.3.4\n";
        let config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        // None exclude means normal deduplication
        let alias = config.deduplicate_alias_excluding("do-web", None);
        assert_eq!(alias, "do-web-2");
    }

    // =========================================================================
    // set_host_tags with empty tags
    // =========================================================================

    #[test]
    fn test_set_host_tags_empty_clears_tags() {
        let content = "Host do-web\n  HostName 1.2.3.4\n  # purple:tags prod,staging\n";
        let mut config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        config.set_host_tags("do-web", &[]);
        let entries = config.host_entries();
        assert!(entries[0].tags.is_empty());
    }

    #[test]
    fn test_set_host_provider_updates_existing() {
        let content = "Host do-web\n  HostName 1.2.3.4\n  # purple:provider digitalocean:old-id\n";
        let mut config = SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        config.set_host_provider("do-web", "digitalocean", "new-id");
        let hosts = config.find_hosts_by_provider("digitalocean");
        assert_eq!(hosts.len(), 1);
        assert_eq!(hosts[0].1, "new-id");
    }

    // =========================================================================
    // Sync with provider hosts in includes (read-only recognized)
    // =========================================================================

    #[test]
    fn test_sync_recognizes_include_hosts_prevents_duplicate_add() {
        use crate::ssh_config::model::{IncludeDirective, IncludedFile};

        let include_content = "Host do-web\n  HostName 1.2.3.4\n  # purple:provider digitalocean:123\n";
        let included_elements = SshConfigFile::parse_content(include_content);

        let mut config = SshConfigFile {
            elements: vec![ConfigElement::Include(IncludeDirective {
                raw_line: "Include conf.d/*".to_string(),
                pattern: "conf.d/*".to_string(),
                resolved_files: vec![IncludedFile {
                    path: PathBuf::from("/tmp/included.conf"),
                    elements: included_elements,
                }],
            })],
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        let section = make_section();
        let remote = vec![ProviderHost::new("123".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];

        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.added, 0);
        // The host should NOT be duplicated in main config
        let top_hosts = config.elements.iter().filter(|e| matches!(e, ConfigElement::HostBlock(_))).count();
        assert_eq!(top_hosts, 0, "No host blocks added to top-level config");
    }

    // =========================================================================
    // Dedup resolves back to the same alias -> counted as unchanged
    // =========================================================================

    #[test]
    fn test_sync_dedup_resolves_back_to_same_alias_unchanged() {
        let mut config = empty_config();
        let section = make_section();

        // Add a host with name "web" -> alias "do-web"
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].alias, "do-web");

        // Manually add another host "do-new-web" that would collide after rename
        let other = vec![ProviderHost::new("2".to_string(), "new-web".to_string(), "5.5.5.5".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &other, &section, false, false);

        // Now rename the remote host "1" to "new-web", but alias "do-new-web" is taken by host "2".
        // dedup will produce "do-new-web-2". This is not the same as "do-web" so it IS a rename.
        // But let's create a scenario where dedup resolves back:
        // Change prefix so expected alias = "do-web" (same as existing)
        // This tests the else branch where alias_changed is initially true (prefix changed)
        // but dedup resolves to the same alias.
        // Actually, let's test it differently: rename where nothing else changes
        let remote_same = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "new-web".to_string(), "5.5.5.5".to_string(), Vec::new()),
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote_same, &section, false, false);
        assert_eq!(result.unchanged, 2);
        assert_eq!(result.updated, 0);
        assert!(result.renames.is_empty());
    }

    // =========================================================================
    // Orphan server_id: existing_map has alias not found in entries_map
    // =========================================================================

    #[test]
    fn test_sync_host_in_entries_map_but_alias_changed_by_another_provider() {
        // When two hosts have the same server name, the second gets a -2 suffix.
        // Test that deduplicate_alias handles this correctly.
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.1.1.1".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "web".to_string(), "2.2.2.2".to_string(), Vec::new()),
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 2);

        let entries = config.host_entries();
        assert_eq!(entries[0].alias, "do-web");
        assert_eq!(entries[1].alias, "do-web-2");

        // Re-sync: both should be unchanged
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 2);
    }

    // =========================================================================
    // Dry-run remove with included hosts: included hosts NOT counted in remove
    // =========================================================================

    #[test]
    fn test_sync_dry_run_remove_excludes_included_hosts() {
        use crate::ssh_config::model::{IncludeDirective, IncludedFile};

        let include_content =
            "Host do-included\n  HostName 1.1.1.1\n  # purple:provider digitalocean:inc1\n";
        let included_elements = SshConfigFile::parse_content(include_content);

        // Top-level host
        let mut config = SshConfigFile {
            elements: vec![ConfigElement::Include(IncludeDirective {
                raw_line: "Include conf.d/*".to_string(),
                pattern: "conf.d/*".to_string(),
                resolved_files: vec![IncludedFile {
                    path: PathBuf::from("/tmp/included.conf"),
                    elements: included_elements,
                }],
            })],
            path: PathBuf::from("/tmp/test_config"),
            crlf: false,
        };

        // Add a non-included host
        let section = make_section();
        let remote = vec![ProviderHost::new("top1".to_string(), "toplevel".to_string(), "2.2.2.2".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Dry-run with empty remote (both hosts would be "deleted")
        // Only the top-level host should be counted, NOT the included one
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, true);
        assert_eq!(result.removed, 1, "Only top-level host counted in dry-run remove");
    }

    // =========================================================================
    // Group header: config already has trailing blank (no extra added)
    // =========================================================================

    #[test]
    fn test_sync_group_header_with_existing_trailing_blank() {
        let mut config = empty_config();
        // Add a pre-existing global line followed by a blank
        config.elements.push(ConfigElement::GlobalLine("# some comment".to_string()));
        config.elements.push(ConfigElement::GlobalLine(String::new()));

        let section = make_section();
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 1);

        // Count blank lines: there should be exactly one blank line before the group header
        // (the pre-existing one), NOT two
        let blank_count = config
            .elements
            .iter()
            .filter(|e| matches!(e, ConfigElement::GlobalLine(l) if l.is_empty()))
            .count();
        assert_eq!(blank_count, 1, "No extra blank line when one already exists");
    }

    // =========================================================================
    // Adding second host to existing provider: no group header added
    // =========================================================================

    #[test]
    fn test_sync_no_group_header_for_second_host() {
        let mut config = empty_config();
        let section = make_section();

        // First sync: one host, group header added
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        let header_count_before = config
            .elements
            .iter()
            .filter(|e| matches!(e, ConfigElement::GlobalLine(l) if l.starts_with("# purple:group")))
            .count();
        assert_eq!(header_count_before, 1);

        // Second sync: add another host
        let remote2 = vec![
            ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new()),
            ProviderHost::new("2".to_string(), "db".to_string(), "5.5.5.5".to_string(), Vec::new()),
        ];
        sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);

        // Still only one group header
        let header_count_after = config
            .elements
            .iter()
            .filter(|e| matches!(e, ConfigElement::GlobalLine(l) if l.starts_with("# purple:group")))
            .count();
        assert_eq!(header_count_after, 1, "No duplicate group header");
    }

    // =========================================================================
    // Duplicate server_id in remote is skipped
    // =========================================================================

    #[test]
    fn test_sync_duplicate_server_id_in_remote_skipped() {
        let mut config = empty_config();
        let section = make_section();

        // Remote with duplicate server_id
        let remote = vec![
            ProviderHost::new("dup".to_string(), "first".to_string(), "1.1.1.1".to_string(), Vec::new()),
            ProviderHost::new("dup".to_string(), "second".to_string(), "2.2.2.2".to_string(), Vec::new()),
        ];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 1, "Only the first instance is added");
        assert_eq!(config.host_entries()[0].alias, "do-first");
    }

    // =========================================================================
    // Empty IP existing host counted as unchanged (no removal)
    // =========================================================================

    #[test]
    fn test_sync_empty_ip_existing_host_counted_unchanged() {
        let mut config = empty_config();
        let section = make_section();

        // Add host
        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Re-sync with empty IP (VM stopped)
        let remote2 = vec![ProviderHost::new("1".to_string(), "web".to_string(), String::new(), Vec::new())];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, true);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.removed, 0, "Host with empty IP not removed");
        assert_eq!(config.host_entries()[0].hostname, "1.2.3.4");
    }

    // =========================================================================
    // Reset tags exact comparison (case-insensitive)
    // =========================================================================

    #[test]
    fn test_sync_reset_tags_case_insensitive_no_update() {
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["Production".to_string()])];
        sync_provider_with_options(
            &mut config, &MockProvider, &remote, &section, false, false, true,
        );

        // Same tag but different case -> unchanged with reset_tags
        let remote2 = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), vec!["production".to_string()])];
        let result = sync_provider_with_options(
            &mut config, &MockProvider, &remote2, &section, false, false, true,
        );
        assert_eq!(result.unchanged, 1, "Case-insensitive tag match = unchanged");
    }

    // =========================================================================
    // Remove deletes group header when all hosts removed
    // =========================================================================

    #[test]
    fn test_sync_remove_cleans_up_group_header() {
        let mut config = empty_config();
        let section = make_section();

        let remote = vec![ProviderHost::new("1".to_string(), "web".to_string(), "1.2.3.4".to_string(), Vec::new())];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Verify group header exists
        let has_header = config.elements.iter().any(|e| {
            matches!(e, ConfigElement::GlobalLine(l) if l.starts_with("# purple:group"))
        });
        assert!(has_header, "Group header present after add");

        // Remove all hosts (empty remote + remove_deleted=true, dry_run=false)
        let result = sync_provider(&mut config, &MockProvider, &[], &section, true, false);
        assert_eq!(result.removed, 1);

        // Group header should be cleaned up
        let has_header_after = config.elements.iter().any(|e| {
            matches!(e, ConfigElement::GlobalLine(l) if l.starts_with("# purple:group"))
        });
        assert!(!has_header_after, "Group header removed when all hosts gone");
    }

    // =========================================================================
    // Metadata sync tests
    // =========================================================================

    #[test]
    fn test_sync_adds_host_with_metadata() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![
                ("region".to_string(), "nyc3".to_string()),
                ("plan".to_string(), "s-1vcpu-1gb".to_string()),
            ],
        }];
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.added, 1);
        let entries = config.host_entries();
        assert_eq!(entries[0].provider_meta.len(), 2);
        assert_eq!(entries[0].provider_meta[0], ("region".to_string(), "nyc3".to_string()));
        assert_eq!(entries[0].provider_meta[1], ("plan".to_string(), "s-1vcpu-1gb".to_string()));
    }

    #[test]
    fn test_sync_updates_changed_metadata() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![("region".to_string(), "nyc3".to_string())],
        }];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Update metadata (region changed, plan added)
        let remote2 = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![
                ("region".to_string(), "sfo3".to_string()),
                ("plan".to_string(), "s-2vcpu-2gb".to_string()),
            ],
        }];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.updated, 1);
        let entries = config.host_entries();
        assert_eq!(entries[0].provider_meta.len(), 2);
        assert_eq!(entries[0].provider_meta[0].1, "sfo3");
        assert_eq!(entries[0].provider_meta[1].1, "s-2vcpu-2gb");
    }

    #[test]
    fn test_sync_metadata_unchanged_no_update() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![("region".to_string(), "nyc3".to_string())],
        }];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Same metadata again
        let result = sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 0);
    }

    #[test]
    fn test_sync_metadata_order_insensitive() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![
                ("region".to_string(), "nyc3".to_string()),
                ("plan".to_string(), "s-1vcpu-1gb".to_string()),
            ],
        }];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Same metadata, different order
        let remote2 = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![
                ("plan".to_string(), "s-1vcpu-1gb".to_string()),
                ("region".to_string(), "nyc3".to_string()),
            ],
        }];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.unchanged, 1);
        assert_eq!(result.updated, 0);
    }

    #[test]
    fn test_sync_metadata_with_rename() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "old-name".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![("region".to_string(), "nyc3".to_string())],
        }];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);
        assert_eq!(config.host_entries()[0].provider_meta[0].1, "nyc3");

        // Rename + metadata change
        let remote2 = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "new-name".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![("region".to_string(), "sfo3".to_string())],
        }];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.updated, 1);
        assert!(!result.renames.is_empty());
        let entries = config.host_entries();
        assert_eq!(entries[0].alias, "do-new-name");
        assert_eq!(entries[0].provider_meta[0].1, "sfo3");
    }

    #[test]
    fn test_sync_metadata_dry_run_no_mutation() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![("region".to_string(), "nyc3".to_string())],
        }];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Dry-run with metadata change
        let remote2 = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: Vec::new(),
            metadata: vec![("region".to_string(), "sfo3".to_string())],
        }];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, true);
        assert_eq!(result.updated, 1);
        // Config should still have old metadata
        assert_eq!(config.host_entries()[0].provider_meta[0].1, "nyc3");
    }

    #[test]
    fn test_sync_metadata_only_change_triggers_update() {
        let mut config = empty_config();
        let section = make_section();
        let remote = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: vec!["prod".to_string()],
            metadata: vec![("region".to_string(), "nyc3".to_string())],
        }];
        sync_provider(&mut config, &MockProvider, &remote, &section, false, false);

        // Only metadata changes (IP, tags, alias all the same)
        let remote2 = vec![ProviderHost {
            server_id: "1".to_string(),
            name: "web".to_string(),
            ip: "1.2.3.4".to_string(),
            tags: vec!["prod".to_string()],
            metadata: vec![
                ("region".to_string(), "nyc3".to_string()),
                ("plan".to_string(), "s-1vcpu-1gb".to_string()),
            ],
        }];
        let result = sync_provider(&mut config, &MockProvider, &remote2, &section, false, false);
        assert_eq!(result.updated, 1);
        assert_eq!(config.host_entries()[0].provider_meta.len(), 2);
    }
}