kto 0.1.5

A generic, flexible web change watcher with AI-powered analysis
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
//! Watch management commands: new, list, show, edit, delete, pause, resume

use std::thread;

use chrono::Utc;
use colored::Colorize;
use inquire::{Confirm, Select, Text};
use uuid::Uuid;

use kto::agent::{self, DeepResearchResult, EnhancedSetupSuggestion};
use kto::config::Config;
use kto::db::Database;
use kto::extract;
use kto::fetch::{self, check_playwright, PageContent, PlaywrightStatus};
use kto::normalize::{hash_content, normalize};
use kto::transforms::{self, Intent, TransformMatch};
use kto::watch::{AgentConfig, Engine, Extraction, Snapshot, Watch};
use kto::error::Result;

use crate::utils::{extract_url, format_interval, get_clipboard_content, parse_interval_str, truncate_str};
use super::platform_detect;
use super::prompt_notification_setup;

/// Confidence threshold below which we show low-confidence UI
const CONFIDENCE_THRESHOLD: f32 = 0.7;

/// Check if kto daemon is currently running
pub fn is_daemon_running() -> bool {
    // Method 1: Check PID file (manual daemon start)
    let home = match std::env::var("HOME") {
        Ok(h) => h,
        Err(_) => return check_daemon_process(),
    };
    let pid_path = std::path::Path::new(&home).join(".local/share/kto/daemon.pid");
    if let Ok(pid_str) = std::fs::read_to_string(&pid_path) {
        if let Ok(pid) = pid_str.trim().parse::<u32>() {
            if std::path::Path::new("/proc").join(pid.to_string()).exists() {
                return true;
            }
        }
    }

    // Method 2: Check systemd user service
    if let Ok(output) = std::process::Command::new("systemctl")
        .args(["--user", "is-active", "kto"])
        .output()
    {
        if output.status.success() {
            let status = String::from_utf8_lossy(&output.stdout);
            if status.trim() == "active" {
                return true;
            }
        }
    }

    // Method 3: Check for running kto daemon process
    check_daemon_process()
}

/// Check if there's a kto daemon process running via pgrep
fn check_daemon_process() -> bool {
    if let Ok(output) = std::process::Command::new("pgrep")
        .args(["-f", "kto daemon"])
        .output()
    {
        return output.status.success() && !output.stdout.is_empty();
    }
    false
}

/// Create a new watch
pub fn cmd_new(
    description: Option<String>,
    name_override: Option<String>,
    interval_str: String,
    use_js: bool,
    use_rss: bool,
    use_shell: bool,
    use_agent: bool,
    agent_instructions: Option<String>,
    selector: Option<String>,
    clipboard: bool,
    tags: Vec<String>,
    use_profile: bool,
    research: bool,
    yes: bool,
) -> Result<()> {
    let db = Database::open()?;

    // Parse interval (supports 30s, 5m, 2h, 1d, 1w formats)
    let interval = parse_interval_str(&interval_str)?;

    // --yes requires a description
    if yes && description.is_none() && !clipboard {
        return Err(kto::KtoError::ConfigError(
            "--yes requires a description argument or --clipboard".into()
        ));
    }

    // Determine if we're in interactive mode (--yes disables interactivity)
    let interactive = !yes && name_override.is_none() && atty::is(atty::Stream::Stdin);

    // Get the description/URL from user or clipboard
    let input = if clipboard {
        // Try to read from clipboard
        match get_clipboard_content() {
            Some(content) => {
                println!("  Read from clipboard: {}", truncate_str(&content, 60));
                content
            }
            None => {
                return Err(kto::KtoError::ConfigError(
                    "Could not read from clipboard. Make sure you have content copied.".into()
                ));
            }
        }
    } else {
        match description {
            Some(d) => d,
            None if interactive => {
                Text::new("What do you want to watch?")
                    .with_help_message("Enter a URL and optionally describe what to watch for")
                    .prompt()
                    .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?
            }
            None => {
                return Err(kto::KtoError::ConfigError(
                    "URL required. Usage: kto new <URL> --name <NAME>".into()
                ));
            }
        }
    };

    // Handle shell command case - input is the command, not a URL
    if use_shell {
        let command = input.trim().to_string();
        let name = name_override.unwrap_or_else(|| {
            // Generate name from command (first word or truncated)
            let first_word = command.split_whitespace().next().unwrap_or("shell");
            format!("shell:{}", first_word)
        });

        // Execute command to get initial content
        println!("\n  Executing: {}", command);
        let content = fetch::fetch("", Engine::Shell { command: command.clone() }, &std::collections::HashMap::new())?;
        let extracted = content.text.clone().unwrap_or_default();

        if extracted.is_empty() {
            println!("  Warning: Command produced no output.");
        } else {
            println!("  Got {} bytes of output.", extracted.len());
        }

        // Create watch with shell engine
        let mut watch = Watch::new(name.clone(), format!("shell://{}", command));
        watch.interval_secs = interval.max(10);
        watch.engine = Engine::Shell { command };
        watch.extraction = Extraction::Full;
        watch.tags = tags;

        // Configure agent if requested
        if use_agent {
            watch.agent_config = Some(AgentConfig {
                enabled: true,
                prompt_template: None,
                instructions: agent_instructions,
            });
        }

        let db = Database::open()?;
        db.insert_watch(&watch)?;

        // Create initial snapshot
        let normalized = normalize(&extracted, &watch.normalization);
        let hash = hash_content(&normalized);

        let snapshot = Snapshot {
            id: Uuid::new_v4(),
            watch_id: watch.id,
            fetched_at: Utc::now(),
            raw_html: None, // No HTML for shell commands
            extracted: normalized,
            content_hash: hash.clone(),
        };
        db.insert_snapshot(&snapshot)?;

        println!("\n  Created shell watch \"{}\"", name);
        println!("  Initial hash: {}", &hash[..8]);
        if watch.agent_config.is_some() {
            println!("  AI Agent: enabled");
        }
        if !watch.tags.is_empty() {
            println!("  Tags: {}", watch.tags.join(", "));
        }
        println!("  Checking every {}", format_interval(watch.interval_secs));
        if !is_daemon_running() {
            println!("\n  Run `kto daemon` to start monitoring.");
        }

        return Ok(());
    }

    // Try to extract URL from input
    let mut url = extract_url(&input).ok_or_else(|| {
        kto::KtoError::ConfigError(format!(
            "No URL found in: '{}'\n  Tip: Paste the full URL (e.g., https://example.com/page)",
            truncate_str(&input, 50)
        ))
    })?;

    // Try URL transform detection first (for known sites like GitHub, GitLab, etc.)
    let detected_intent = Intent::detect(&input);
    let transform_match = if detected_intent != Intent::Generic {
        if let Ok(parsed_url) = url::Url::parse(&url) {
            transforms::match_transform(&parsed_url, detected_intent)
        } else {
            None
        }
    } else {
        None
    };

    // If we have a high-confidence transform match, create watch automatically
    // This is the "zero-prompt happy path" for known platforms
    if let Some(ref transform) = transform_match {
        if transform.confidence >= 0.8 {
            // Auto-create for high confidence matches
            return create_watch_from_transform_magical(
                &db,
                &url,
                transform,
                name_override,
                interval,
                tags,
                use_profile,
                interactive,
                yes,
            );
        } else if transform.confidence >= 0.5 && interactive && !yes {
            // Medium confidence - show preview and ask for confirmation
            let accepted = display_transform_suggestion(
                &url,
                transform,
                &name_override,
                interval,
                &tags,
                use_profile,
                yes,
                interactive,
            )?;

            if let Some((name, final_url, final_engine, final_extraction, final_interval)) = accepted {
                return create_watch_from_transform(
                    &db,
                    name,
                    final_url,
                    final_engine,
                    final_extraction,
                    final_interval,
                    tags,
                    use_profile,
                    interactive,
                    yes,
                );
            }
            // User declined - fall through to normal flow
        }
    }

    // Detect if user expressed intent (what to watch for)
    let has_intent = input.contains(" for ") || input.contains(" when ") || input.contains(" if ")
        || input.contains("watch for") || input.contains("notify me") || input.contains("alert")
        || input.contains("price") || input.contains("stock") || input.contains("available")
        || input.contains("back in") || input.contains("drop");

    // Check if Claude CLI is available for enhanced wizard
    let claude_available = agent::claude_version().is_some();

    // Use enhanced wizard flow when intent detected and Claude available
    // Works in both interactive and --yes mode (auto-accepts in --yes mode)
    let use_enhanced_wizard = has_intent && claude_available && !use_agent && !use_rss && !use_shell;

    // Check if we should use deep research mode
    let should_research = research;

    // Deep research flow - more thorough analysis with web search
    if should_research && claude_available {
        return run_deep_research_flow(
            &input,
            &url,
            name_override,
            interval,
            tags,
            use_profile,
            yes,
            interactive,
        );
    }

    // Enhanced wizard flow with dual fetch and smart analysis
    let (engine, content, extracted, title, enhanced_suggestion) = if use_enhanced_wizard {
        println!("\n  Analyzing {}...", url);

        // Perform dual fetch: HTTP and Playwright in parallel
        let (http_content, js_content) = dual_fetch(&url)?;

        // Run platform detection with KB
        let platform_analysis = platform_detect::analyze_url_with_platform_kb(
            &url,
            detected_intent,
            http_content.as_ref(),
            js_content.as_ref(),
        ).ok();

        // Show platform detection results (if detected)
        if let Some(ref analysis) = platform_analysis {
            if analysis.has_platform() {
                if let Some(ref pm) = analysis.platform_match {
                    println!("  Platform: {} ({:.0}% confidence)", pm.platform_name.cyan(), pm.score * 100.0);
                }
            }
        }

        // Extract content from both fetches
        let http_extracted = http_content.as_ref()
            .and_then(|c| extract::extract(c, &Extraction::Auto).ok());
        let js_extracted = js_content.as_ref()
            .and_then(|c| extract::extract(c, &Extraction::Auto).ok());

        // Get title from whichever fetch succeeded
        let title = js_content.as_ref()
            .and_then(|c| extract::extract_title(&c.html))
            .or_else(|| http_content.as_ref().and_then(|c| extract::extract_title(&c.html)))
            .unwrap_or_else(|| "Untitled".to_string());

        // Call enhanced AI analysis with both content versions
        // Include KB context if platform was detected
        println!("  Analyzing with AI (dual fetch)...");
        let suggestion = match agent::analyze_for_setup_v2(
            &input,
            http_extracted.as_deref(),
            js_extracted.as_deref(),
        ) {
            Ok(mut s) => {
                // Apply KB recommendations if AI confidence is lower than KB
                if let Some(ref analysis) = platform_analysis {
                    if let Some(ref best) = analysis.best_strategy {
                        // If platform detection suggests JS and AI didn't, prefer KB
                        if matches!(best.engine, Engine::Playwright) && !s.needs_js {
                            if analysis.confidence > s.confidence {
                                s.needs_js = true;
                                s.js_reason = Some(format!(
                                    "KB recommends for {}: {}",
                                    analysis.platform_match.as_ref().map(|p| p.platform_name.as_str()).unwrap_or("platform"),
                                    best.reason
                                ));
                            }
                        }
                    }
                }
                s
            }
            Err(e) => {
                eprintln!("  AI analysis failed: {} (using fallback)", e);
                // Use KB recommendations as fallback
                if let Some(ref analysis) = platform_analysis {
                    if let Some(ref best) = analysis.best_strategy {
                        let mut fallback = EnhancedSetupSuggestion::fallback(&url, &input);
                        fallback.needs_js = matches!(best.engine, Engine::Playwright);
                        fallback.js_reason = Some(format!("KB: {}", best.reason));
                        fallback.confidence = analysis.confidence;
                        fallback
                    } else {
                        EnhancedSetupSuggestion::fallback(&url, &input)
                    }
                } else {
                    EnhancedSetupSuggestion::fallback(&url, &input)
                }
            }
        };

        // Determine which content/engine to use based on AI recommendation (augmented by KB)
        let (final_engine, final_content) = if suggestion.needs_js && js_content.is_some() {
            (Engine::Playwright, js_content.unwrap())
        } else if http_content.is_some() {
            (Engine::Http, http_content.unwrap())
        } else if js_content.is_some() {
            (Engine::Playwright, js_content.unwrap())
        } else {
            return Err(kto::KtoError::ConfigError("Both HTTP and JS fetches failed".into()));
        };

        let final_extracted = if suggestion.needs_js && js_extracted.is_some() {
            js_extracted.unwrap()
        } else {
            http_extracted.or(js_extracted).unwrap_or_default()
        };

        (final_engine, final_content, final_extracted, title, Some(suggestion))
    } else {
        // Traditional flow: determine engine first, then fetch

        // Determine engine to use - with smart probing in interactive mode
        let engine = if use_rss {
            // Validate RSS flag - warn if URL doesn't look like RSS
            if !fetch::detect_rss_url(&url) {
                eprintln!("  Note: URL doesn't look like an RSS feed, but --rss was specified.");
                eprintln!("  Will attempt to parse as RSS anyway.");
            }
            Engine::Rss
        } else if use_js {
            // Check if Playwright is available
            match check_playwright() {
                PlaywrightStatus::Ready => Engine::Playwright,
                status => {
                    eprintln!("  Warning: Playwright not ready. {}", status.install_instructions());
                    eprintln!("  Falling back to HTTP fetch.");
                    Engine::Http
                }
            }
        } else if interactive {
            // In interactive mode, probe the URL to suggest the best engine
            println!("\n  Analyzing {}...", url);
            match fetch::probe_url(&url) {
                Ok(probe) => {
                    // Show what we found
                    if let Some(ref msg) = probe.message {
                        println!("  {}", msg);
                    }

                    // If RSS detected in content or URL, offer to use it
                    if probe.suggested_engine == Engine::Rss {
                        println!("  Using RSS engine.");
                        Engine::Rss
                    }
                    // If RSS link found in page, offer to use it instead
                    else if let Some(ref rss_link) = probe.rss_url {
                        let use_rss = Confirm::new(&format!("RSS feed found at {}. Use that instead?", rss_link))
                            .with_default(true)
                            .prompt()
                            .unwrap_or(false);
                        if use_rss {
                            println!("  Switching to RSS feed.");
                            url = rss_link.clone();
                            Engine::Rss
                        } else {
                            probe.suggested_engine
                        }
                    }
                    // If Playwright suggested
                    else if probe.suggested_engine == Engine::Playwright {
                        // Check if available
                        match check_playwright() {
                            PlaywrightStatus::Ready => {
                                let use_js = Confirm::new("Enable JavaScript rendering?")
                                    .with_default(true)
                                    .prompt()
                                    .unwrap_or(false);
                                if use_js { Engine::Playwright } else { Engine::Http }
                            }
                            status => {
                                println!("  JavaScript rendering recommended but not available.");
                                println!("  {}", status.install_instructions());
                                Engine::Http
                            }
                        }
                    } else {
                        probe.suggested_engine
                    }
                }
                Err(e) => {
                    // Probe failed, fall back to simple URL pattern detection
                    eprintln!("  Could not analyze page: {}", e);
                    if fetch::detect_rss_url(&url) {
                        println!("  URL looks like RSS feed, using RSS engine.");
                        Engine::Rss
                    } else {
                        Engine::Http
                    }
                }
            }
        } else if fetch::detect_rss_url(&url) {
            // Non-interactive: auto-detect RSS from URL pattern
            println!("\n  Detected RSS feed URL, using RSS engine.");
            Engine::Rss
        } else {
            Engine::Http
        };

        let engine_label = match &engine {
            Engine::Playwright => " (with JS)".to_string(),
            Engine::Rss => " (as RSS feed)".to_string(),
            Engine::Http => "".to_string(),
            Engine::Shell { .. } => " (shell command)".to_string(),
        };
        println!("  Fetching {}{}...", url, engine_label);

        // Fetch the page with friendly error handling
        let content = match fetch::fetch(&url, engine.clone(), &std::collections::HashMap::new()) {
            Ok(c) => c,
            Err(e) => {
                let msg = platform_detect::friendly_error_message(&e.to_string(), &url);
                return Err(kto::KtoError::ConfigError(msg));
            }
        };

        // Determine extraction strategy
        let extraction = match (&selector, &engine) {
            (Some(ref sel), _) => Extraction::Selector { selector: sel.clone() },
            (None, Engine::Rss) => Extraction::Rss,
            (None, _) => Extraction::Auto,
        };

        // Extract content
        let mut extracted = extract::extract(&content, &extraction)?;
        let title = extract::extract_title(&content.html)
            .unwrap_or_else(|| "Untitled".to_string());

        // Smart fallback: if HTTP content is thin, auto-retry with Playwright
        let (final_engine, final_content) = if extracted.len() < 200 && !use_js && engine == Engine::Http {
            // Check if Playwright is available
            if check_playwright().is_ready() {
                println!("  Site needs visual rendering. Switching to browser mode...");
                match fetch::fetch(&url, Engine::Playwright, &std::collections::HashMap::new()) {
                    Ok(js_content) => {
                        let js_extracted = extract::extract(&js_content, &extraction)
                            .unwrap_or_else(|_| extracted.clone());
                        if js_extracted.len() > extracted.len() {
                            extracted = js_extracted;
                            (Engine::Playwright, js_content)
                        } else {
                            (engine, content)
                        }
                    }
                    Err(_) => (engine, content),
                }
            } else {
                println!("\n  Note: Page may need JavaScript. Run `kto init` to enable browser mode.");
                (engine, content)
            }
        } else {
            (engine, content)
        };

        (final_engine, final_content, extracted, title, None)
    };

    // Determine extraction strategy based on selector or engine
    let extraction = match (&selector, &engine) {
        (Some(ref sel), _) => Extraction::Selector { selector: sel.clone() },
        (None, Engine::Rss) => Extraction::Rss,
        (None, _) => Extraction::Auto,
    };

    // Apply enhanced AI suggestions or use traditional flow
    let (name, final_url, final_interval, final_agent_enabled, final_agent_instructions, final_extraction, final_engine) =
        if let Some(ref suggestion) = enhanced_suggestion {
            // Enhanced wizard flow with variant display
            match display_enhanced_confirmation(
                &url,
                suggestion,
                &extraction,
                engine.clone(),
                &name_override,
                interval,
                yes,
            ) {
                Ok(result) => result,
                Err(kto::KtoError::RetryWithDeepResearch) => {
                    // User requested deep research - run that flow instead
                    return run_deep_research_flow(
                        &input,
                        &url,
                        name_override,
                        interval,
                        tags,
                        use_profile,
                        yes,
                        interactive,
                    );
                }
                Err(e) => return Err(e),
            }
        } else {
            // Traditional flow - No enhanced AI suggestion
            if !yes {
                let preview: String = extracted.chars().take(200).collect();
                println!("\n  Title: {}", title);
                println!("  Content preview: {}...\n", preview.trim());
            }

            let name = match name_override {
                Some(n) => n,
                None if interactive => {
                    Text::new("Name for this watch?")
                        .with_default(&title)
                        .prompt()
                        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?
                }
                None => title.clone(),
            };

            // Intent-first flow: ask what changes matter BEFORE asking about AI
            let (agent_enabled, final_instructions) = if use_agent {
                // Explicit --agent flag always enables, use provided instructions
                (true, agent_instructions.clone())
            } else if interactive {
                // Interactive mode: use selection for common intents
                println!();
                let intent_options = vec![
                    "Price changes (sales, drops, increases)",
                    "Back in stock / availability",
                    "New content or updates",
                    "Any changes (notify on all)",
                    "Custom (I'll describe it)",
                ];

                let choice = Select::new("What do you want to watch for?", intent_options)
                    .prompt()
                    .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

                let (agent_needed, instructions) = match choice {
                    "Price changes (sales, drops, increases)" => {
                        (true, Some("Alert when price changes. Include old and new price.".to_string()))
                    }
                    "Back in stock / availability" => {
                        (true, Some("Alert when item becomes available or goes out of stock.".to_string()))
                    }
                    "New content or updates" => {
                        (true, Some("Alert when new content is added. Summarize what's new.".to_string()))
                    }
                    "Any changes (notify on all)" => {
                        (false, None)
                    }
                    "Custom (I'll describe it)" => {
                        let custom_intent = Text::new("Describe what changes matter:")
                            .with_help_message("e.g., 'price drops below $50', 'new job postings'")
                            .prompt()
                            .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

                        if custom_intent.trim().is_empty() {
                            (false, None)
                        } else {
                            (true, Some(custom_intent.trim().to_string()))
                        }
                    }
                    _ => (false, None),
                };

                if agent_needed && !claude_available {
                    println!("  Note: Smart filtering requires Claude CLI.");
                    println!("  Install: curl -fsSL https://claude.ai/install.sh | bash");
                    println!("  Will notify on all changes for now.");
                    (false, None)
                } else {
                    (agent_needed, instructions)
                }
            } else {
                // Non-interactive mode: require explicit --agent flag
                (false, agent_instructions.clone())
            };

            (name, url.clone(), interval, agent_enabled, final_instructions, extraction.clone(), engine)
        };

    // Shell safety: warn if instructions contain $ which may have been mangled by bash
    if let Some(ref instructions) = final_agent_instructions {
        if instructions.contains('$') {
            println!("  Note: Instructions contain '$' - if using prices, this looks correct.");
        } else if instructions.chars().any(|c| c.is_ascii_digit()) {
            // Check if there's a number that might have lost its $ prefix
            let has_bare_number = instructions.split_whitespace().any(|word| {
                word.chars().all(|c| c.is_ascii_digit() || c == '.')
                    && word.parse::<f64>().is_ok()
            });
            if has_bare_number && !instructions.contains('$') {
                println!("  Warning: Instructions contain numbers without '$' symbol.");
                println!("  If you meant a price (e.g., $170), the '$' may have been");
                println!("  eaten by bash. Use single quotes: --agent-instructions 'price < $170'");
            }
        }
    }

    // Create watch with final options (enforce minimum interval)
    let mut watch = Watch::new(name.clone(), final_url.clone());
    watch.interval_secs = final_interval.max(10);
    watch.engine = final_engine;
    watch.extraction = final_extraction;
    watch.tags = tags;
    watch.use_profile = use_profile;

    // Configure agent
    if final_agent_enabled {
        watch.agent_config = Some(AgentConfig {
            enabled: true,
            prompt_template: None,
            instructions: final_agent_instructions,
        });
    }

    db.insert_watch(&watch)?;

    // Create initial snapshot
    let normalized = normalize(&extracted, &watch.normalization);
    let hash = hash_content(&normalized);

    let snapshot = Snapshot {
        id: Uuid::new_v4(),
        watch_id: watch.id,
        fetched_at: Utc::now(),
        raw_html: Some(zstd::encode_all(content.html.as_bytes(), 3)?),
        extracted: normalized,
        content_hash: hash.clone(),
    };
    db.insert_snapshot(&snapshot)?;

    // User-friendly success output (no jargon)
    let has_agent = watch.agent_config.is_some();
    let agent_instructions = watch.agent_config.as_ref().and_then(|c| c.instructions.as_deref());
    let intent_description = platform_detect::describe_watch_intent(
        &watch.engine,
        has_agent,
        agent_instructions,
    );

    let success_msg = platform_detect::format_watch_created(
        &name,
        &intent_description,
        watch.interval_secs,
        has_agent,
    );
    println!("{}", success_msg);

    // Show tags if present
    if !watch.tags.is_empty() {
        println!("   Tags: {}", watch.tags.join(", "));
    }

    // Prompt for notification setup if not configured and interactive (skip with --yes)
    let mut config = Config::load()?;
    if config.default_notify.is_none() && interactive && !yes {
        println!();
        if let Some(target) = prompt_notification_setup()? {
            config.default_notify = Some(target);
            config.save()?;
            println!("  Notification settings saved.");
        }
    }

    if !is_daemon_running() {
        println!("\n  Run `kto daemon` to start monitoring.");
    }

    Ok(())
}

/// List all watches
pub fn cmd_list(verbose: bool, tag_filter: Option<String>, json: bool) -> Result<()> {
    let db = Database::open()?;
    let mut watches = db.list_watches()?;

    // Filter by tag if specified
    if let Some(ref tag) = tag_filter {
        watches.retain(|w| w.tags.iter().any(|t| t.eq_ignore_ascii_case(tag)));
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&watches)?);
        return Ok(());
    }

    if watches.is_empty() {
        if tag_filter.is_some() {
            println!("No watches found with tag '{}'.", tag_filter.unwrap());
        } else {
            println!("No watches configured. Run `kto new` to create one.");
        }
        return Ok(());
    }

    // Check if terminal supports colors
    let use_color = atty::is(atty::Stream::Stdout);

    println!("\nWatches:\n");

    if verbose {
        for watch in watches {
            let status = if watch.enabled {
                if use_color { "active".green().to_string() } else { "active".to_string() }
            } else {
                if use_color { "paused".yellow().to_string() } else { "paused".to_string() }
            };

            println!("  {} ({})", watch.name.bold(), &watch.id.to_string()[..8]);
            println!("    URL:      {}", watch.url);
            println!("    Status:   {}, every {}", status, format_interval(watch.interval_secs));
            println!("    Engine:   {:?}", watch.engine);
            if watch.agent_config.is_some() {
                println!("    AI Agent: enabled");
            }
            if !watch.tags.is_empty() {
                println!("    Tags:     {}", watch.tags.join(", "));
            }
            println!();
        }
    } else {
        // Calculate max widths for alignment
        let max_name_len = watches.iter().map(|w| w.name.len()).max().unwrap_or(20).min(30);

        for watch in watches {
            // Status indicator with color
            let status_indicator = if watch.enabled {
                if use_color { "".green().to_string() } else { "[active]".to_string() }
            } else {
                if use_color { "".yellow().to_string() } else { "[paused]".to_string() }
            };

            // Engine badge (RSS)
            let engine_badge = if watch.engine == Engine::Rss {
                if use_color { " RSS".magenta().to_string() } else { " [RSS]".to_string() }
            } else {
                "".to_string()
            };

            // AI badge
            let ai_badge = if watch.agent_config.is_some() {
                if use_color { " AI".cyan().to_string() } else { " [AI]".to_string() }
            } else {
                "".to_string()
            };

            // Truncate name if too long
            let name = truncate_str(&watch.name, max_name_len);
            let padded_name = format!("{:width$}", name, width = max_name_len);

            // Truncate URL if too long
            let url = truncate_str(&watch.url, 50);

            let interval = format_interval(watch.interval_secs);

            println!("  {} {}{}{} {} ({})",
                     status_indicator,
                     if use_color { padded_name.bold().to_string() } else { padded_name },
                     engine_badge,
                     ai_badge,
                     url.dimmed(),
                     interval);
        }
    }

    println!();
    Ok(())
}

/// Show details of a specific watch
pub fn cmd_show(id_or_name: &str, json: bool) -> Result<()> {
    let db = Database::open()?;
    let watch = db.get_watch(id_or_name)?
        .ok_or_else(|| kto::KtoError::WatchNotFound(id_or_name.to_string()))?;

    // Show recent changes
    let changes = db.get_recent_changes(&watch.id, 5)?;

    if json {
        let output = serde_json::json!({
            "watch": watch,
            "recent_changes": changes
        });
        println!("{}", serde_json::to_string_pretty(&output)?);
        return Ok(());
    }

    println!("\nWatch: {}\n", watch.name);
    println!("  ID:        {}", watch.id);
    println!("  URL:       {}", watch.url);
    println!("  Status:    {}", if watch.enabled { "active" } else { "paused" });
    println!("  Interval:  {}", format_interval(watch.interval_secs));
    println!("  Engine:    {:?}", watch.engine);
    if let Some(ref agent_config) = watch.agent_config {
        println!("  AI Agent:  {}", if agent_config.enabled { "enabled" } else { "disabled" });
        if let Some(ref instructions) = agent_config.instructions {
            println!("  Instructions: {}", instructions);
        }
    }
    if watch.use_profile {
        println!("  Profile:   enabled");
    }
    println!("  Created:   {}", watch.created_at.format("%Y-%m-%d %H:%M"));

    if !changes.is_empty() {
        println!("\n  Recent changes:");
        for change in changes {
            let notified = if change.notified { "notified" } else { "not notified" };
            println!("    {} - {}", change.detected_at.format("%Y-%m-%d %H:%M"), notified);
        }
    }

    Ok(())
}

/// Edit a watch
pub fn cmd_edit(
    id_or_name: &str,
    new_name: Option<String>,
    new_interval: Option<String>,
    new_enabled: Option<bool>,
    new_agent: Option<bool>,
    new_agent_instructions: Option<String>,
    new_selector: Option<String>,
    new_notify: Option<String>,
    new_use_profile: Option<bool>,
) -> Result<()> {
    use inquire::Select;

    let db = Database::open()?;
    let mut watch = db.get_watch(id_or_name)?
        .ok_or_else(|| kto::KtoError::WatchNotFound(id_or_name.to_string()))?;

    let has_flags = new_name.is_some() || new_interval.is_some() || new_enabled.is_some()
        || new_agent.is_some() || new_agent_instructions.is_some() || new_selector.is_some()
        || new_notify.is_some() || new_use_profile.is_some();

    if has_flags {
        // Flag-based editing (non-interactive)
        let mut changes = Vec::new();

        if let Some(name) = new_name {
            watch.name = name.clone();
            changes.push(format!("name -> {}", name));
        }

        if let Some(ref interval_str) = new_interval {
            let interval = parse_interval_str(interval_str)?;
            watch.interval_secs = interval;
            changes.push(format!("interval -> {}", format_interval(interval)));
        }

        if let Some(enabled) = new_enabled {
            watch.enabled = enabled;
            changes.push(format!("enabled -> {}", enabled));
        }

        if let Some(agent) = new_agent {
            if agent {
                if watch.agent_config.is_none() {
                    watch.agent_config = Some(AgentConfig {
                        enabled: true,
                        prompt_template: None,
                        instructions: None,
                    });
                } else if let Some(ref mut config) = watch.agent_config {
                    config.enabled = true;
                }
                changes.push("agent -> enabled".to_string());
            } else {
                if let Some(ref mut config) = watch.agent_config {
                    config.enabled = false;
                }
                changes.push("agent -> disabled".to_string());
            }
        }

        if let Some(instructions) = new_agent_instructions {
            if watch.agent_config.is_none() {
                watch.agent_config = Some(AgentConfig {
                    enabled: true,
                    prompt_template: None,
                    instructions: Some(instructions.clone()),
                });
            } else if let Some(ref mut config) = watch.agent_config {
                config.instructions = Some(instructions.clone());
            }
            changes.push(format!("agent_instructions -> {}", instructions));
        }

        if let Some(selector) = new_selector {
            watch.extraction = Extraction::Selector { selector: selector.clone() };
            changes.push(format!("selector -> {}", selector));
        }

        if let Some(notify_str) = new_notify {
            if notify_str.to_lowercase() == "none" || notify_str.to_lowercase() == "clear" {
                watch.notify_target = None;
                changes.push("notify -> cleared (will use global default)".to_string());
            } else {
                // Parse the notify string (format: "type:value" or "type:value:value2")
                let target = super::parse_notify_string(&notify_str)?;
                let description = super::describe_notify_target(&target);
                watch.notify_target = Some(target);
                changes.push(format!("notify -> {}", description));
            }
        }

        if let Some(profile) = new_use_profile {
            watch.use_profile = profile;
            changes.push(format!("use_profile -> {}", profile));
        }

        db.update_watch(&watch)?;

        println!("\nUpdated watch '{}':", watch.name);
        for change in changes {
            println!("  {}", change);
        }
    } else if atty::is(atty::Stream::Stdin) {
        // Interactive editing
        println!("\nEditing watch: {}\n", watch.name);
        println!("  Current settings:");
        println!("    Name:     {}", watch.name);
        println!("    URL:      {}", watch.url);
        println!("    Interval: {}", format_interval(watch.interval_secs));
        println!("    Status:   {}", if watch.enabled { "active" } else { "paused" });
        println!("    Engine:   {:?}", watch.engine);
        if let Some(ref config) = watch.agent_config {
            println!("    AI Agent: {}", if config.enabled { "enabled" } else { "disabled" });
            if let Some(ref inst) = config.instructions {
                println!("    Instructions: {}", inst);
            }
        } else {
            println!("    AI Agent: not configured");
        }
        println!();

        loop {
            let options = vec![
                "Change name",
                "Change interval",
                "Toggle pause/resume",
                "Toggle AI agent",
                "Set agent instructions",
                "Done",
            ];

            let choice = Select::new("What would you like to change?", options)
                .prompt()
                .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

            match choice {
                "Change name" => {
                    let new = Text::new("New name:")
                        .with_default(&watch.name)
                        .prompt()
                        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;
                    watch.name = new;
                    println!("  Name updated.");
                }
                "Change interval" => {
                    let current = format_interval(watch.interval_secs);
                    let new = Text::new("New interval (e.g., 5m, 1h, 30s):")
                        .with_default(&current)
                        .prompt()
                        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

                    if let Ok(secs) = parse_interval_str(&new) {
                        watch.interval_secs = secs;
                        println!("  Interval updated to {}.", format_interval(secs));
                    } else {
                        println!("  Invalid interval format. Use 30s, 5m, 1h, etc.");
                    }
                }
                "Toggle pause/resume" => {
                    watch.enabled = !watch.enabled;
                    println!("  Watch {}.", if watch.enabled { "resumed" } else { "paused" });
                }
                "Toggle AI agent" => {
                    if let Some(ref mut config) = watch.agent_config {
                        config.enabled = !config.enabled;
                        println!("  AI agent {}.", if config.enabled { "enabled" } else { "disabled" });
                    } else {
                        watch.agent_config = Some(AgentConfig {
                            enabled: true,
                            prompt_template: None,
                            instructions: None,
                        });
                        println!("  AI agent enabled.");
                    }
                }
                "Set agent instructions" => {
                    let current = watch.agent_config.as_ref()
                        .and_then(|c| c.instructions.as_deref())
                        .unwrap_or("");
                    let new = Text::new("Agent instructions:")
                        .with_default(current)
                        .with_help_message("What should the AI focus on when analyzing changes?")
                        .prompt()
                        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

                    if watch.agent_config.is_none() {
                        watch.agent_config = Some(AgentConfig {
                            enabled: true,
                            prompt_template: None,
                            instructions: if new.is_empty() { None } else { Some(new) },
                        });
                    } else if let Some(ref mut config) = watch.agent_config {
                        config.instructions = if new.is_empty() { None } else { Some(new) };
                    }
                    println!("  Instructions updated.");
                }
                "Done" => break,
                _ => {}
            }
        }

        db.update_watch(&watch)?;
        println!("\nWatch '{}' updated.", watch.name);
    } else {
        println!("No flags provided and not running interactively.");
        println!("Use flags like --interval 300 or run in a terminal for interactive mode.");
    }

    Ok(())
}

/// Pause a watch
pub fn cmd_pause(id_or_name: &str) -> Result<()> {
    let db = Database::open()?;
    let mut watch = db.get_watch(id_or_name)?
        .ok_or_else(|| kto::KtoError::WatchNotFound(id_or_name.to_string()))?;

    watch.enabled = false;
    db.update_watch(&watch)?;

    println!("Paused watch: {}", watch.name);
    Ok(())
}

/// Resume a paused watch
pub fn cmd_resume(id_or_name: &str) -> Result<()> {
    let db = Database::open()?;
    let mut watch = db.get_watch(id_or_name)?
        .ok_or_else(|| kto::KtoError::WatchNotFound(id_or_name.to_string()))?;

    watch.enabled = true;
    db.update_watch(&watch)?;

    println!("Resumed watch: {}", watch.name);
    Ok(())
}

/// Delete a watch
pub fn cmd_delete(id_or_name: &str, skip_confirm: bool) -> Result<()> {
    let db = Database::open()?;
    let watch = db.get_watch(id_or_name)?
        .ok_or_else(|| kto::KtoError::WatchNotFound(id_or_name.to_string()))?;

    if !skip_confirm {
        let confirm = Confirm::new(&format!("Delete watch '{}'?", watch.name))
            .with_default(false)
            .prompt()
            .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

        if !confirm {
            println!("Cancelled.");
            return Ok(());
        }
    }

    db.delete_watch(&watch.id)?;
    println!("Deleted watch: {}", watch.name);
    Ok(())
}

// ============================================================================
// Enhanced Wizard Helper Functions
// ============================================================================

/// Perform parallel HTTP and Playwright fetches for dual content analysis
/// If `skip_http` is true, only perform Playwright fetch (for known JS-heavy sites)
fn dual_fetch(url: &str) -> Result<(Option<PageContent>, Option<PageContent>)> {
    dual_fetch_with_hint(url, false)
}

/// Perform HTTP and/or Playwright fetches based on hints
/// If `skip_http` is true, only perform Playwright fetch (for known JS-heavy sites like npm)
fn dual_fetch_with_hint(url: &str, skip_http: bool) -> Result<(Option<PageContent>, Option<PageContent>)> {
    let url_owned = url.to_string();

    // Start HTTP fetch in a thread (unless skipped for known JS-heavy sites)
    let http_handle = if !skip_http {
        let url_http = url_owned.clone();
        Some(thread::spawn(move || {
            fetch::fetch(&url_http, Engine::Http, &std::collections::HashMap::new())
        }))
    } else {
        None
    };

    // Start Playwright fetch if available
    let playwright_available = check_playwright().is_ready();
    let js_handle = if playwright_available {
        let url_js = url_owned.clone();
        Some(thread::spawn(move || {
            fetch::fetch(&url_js, Engine::Playwright, &std::collections::HashMap::new())
        }))
    } else {
        None
    };

    // Wait for HTTP result
    let http_content = if let Some(handle) = http_handle {
        handle
            .join()
            .map_err(|_| kto::KtoError::ConfigError("HTTP fetch thread panicked".into()))?
            .ok()
    } else {
        None
    };

    // Wait for Playwright result if started
    let js_content = if let Some(handle) = js_handle {
        handle
            .join()
            .map_err(|_| kto::KtoError::ConfigError("Playwright fetch thread panicked".into()))?
            .ok()
    } else {
        None
    };

    // Report what we got
    let http_status = if skip_http {
        "" // Skipped
    } else if http_content.is_some() {
        ""
    } else {
        ""
    };
    let js_status = if js_content.is_some() {
        ""
    } else if playwright_available {
        ""
    } else {
        ""
    };
    println!("  Fetched: HTTP {} | JS {}", http_status, js_status);

    Ok((http_content, js_content))
}

/// Display enhanced confirmation UI with variants and current status
fn display_enhanced_confirmation(
    url: &str,
    suggestion: &EnhancedSetupSuggestion,
    default_extraction: &Extraction,
    default_engine: Engine,
    name_override: &Option<String>,
    _default_interval: u64,
    yes: bool,
) -> Result<(String, String, u64, bool, Option<String>, Extraction, Engine)> {
    // Check if we need to show low-confidence UI
    let low_confidence = suggestion.confidence < CONFIDENCE_THRESHOLD;

    if !yes {
        // Display analysis results
        println!();
        println!("  {}", "Analysis Results".bold().underline());
        println!();

        // Current status
        if let Some(ref status) = suggestion.current_status {
            println!("  Status:  {}", status.cyan());
        }

        // Engine recommendation
        let engine_text = if suggestion.needs_js {
            let reason = suggestion.js_reason.as_ref().map(|r| format!(" ({})", r)).unwrap_or_default();
            format!("{}{}", "JavaScript required".yellow(), reason)
        } else {
            "HTTP".to_string()
        };
        println!("  Engine:  {}", engine_text);

        // Detected variants (limit to 5 for display)
        if !suggestion.variants.is_empty() {
            println!();
            let more = if suggestion.variants.len() > 5 {
                format!(" (+{} more)", suggestion.variants.len() - 5)
            } else {
                String::new()
            };
            println!("  Variants:{}", more);
            for (i, variant) in suggestion.variants.iter().take(5).enumerate() {
                let status_str = variant.status.as_deref().unwrap_or("?");
                let is_match = suggestion.intent_match.as_ref().map(|m| m.variant_index == i).unwrap_or(false);
                let marker = if is_match { " ← intent".yellow().to_string() } else { "".to_string() };
                println!("    {}. {} - {}{}", i + 1, variant.name, status_str, marker);
            }
        }

        // Recommended setup
        println!();
        println!("  Suggested:");
        println!("    Name:     {}", suggestion.name);
        println!("    Interval: {}", format_interval(suggestion.interval_secs));
        if let Some(ref instructions) = suggestion.agent_instructions {
            let display_instructions = truncate_str(instructions, 60);
            println!("    AI:       \"{}\"", display_instructions);
        }

        // Show uncertainty reasons if low confidence
        if low_confidence && !suggestion.uncertainty_reasons.is_empty() {
            println!();
            println!("  {} Low confidence ({:.0}%):", "".yellow(), suggestion.confidence * 100.0);
            for reason in &suggestion.uncertainty_reasons {
                println!("{}", reason);
            }
        }
        println!();
    }

    // Check if Claude is available for deep research option
    let claude_available = agent::claude_version().is_some();

    // Determine final URL (with variant if matched)
    let final_url = if let Some(ref intent_match) = suggestion.intent_match {
        if let Some(variant) = suggestion.variants.get(intent_match.variant_index) {
            if let Some(ref url_hint) = variant.url_hint {
                construct_variant_url(url, url_hint)
            } else {
                url.to_string()
            }
        } else {
            url.to_string()
        }
    } else {
        url.to_string()
    };

    // Show variant URL if different
    if final_url != url && !yes {
        println!("  Using variant URL: {}", final_url.cyan());
        println!();
    }

    // User confirmation or customization
    if yes {
        // Auto-accept with --yes
        let name = name_override.clone().unwrap_or_else(|| suggestion.name.clone());
        let engine = if suggestion.needs_js { Engine::Playwright } else { default_engine };
        let extraction = suggestion.selector_hint.as_ref()
            .map(|sel| Extraction::Selector { selector: sel.clone() })
            .unwrap_or_else(|| default_extraction.clone());

        return Ok((
            name,
            final_url,
            suggestion.interval_secs,
            suggestion.agent_enabled,
            suggestion.agent_instructions.clone(),
            extraction,
            engine,
        ));
    }

    // Offer choices: Create, Customize, Cancel (+ Deep Research if low confidence)
    let mut choices = vec!["Create Watch"];

    // Add Deep Research option at the top if low confidence and Claude available
    if low_confidence && claude_available {
        choices.insert(0, "Run Deep Research");
    }

    if !suggestion.variants.is_empty() && suggestion.variants.len() > 1 {
        choices.push("Select Different Variant");
    }
    choices.push("Customize");
    choices.push("Cancel");

    let choice = Select::new("What would you like to do?", choices)
        .prompt()
        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

    match choice {
        "Run Deep Research" => {
            // Signal to caller to retry with deep research mode
            return Err(kto::KtoError::RetryWithDeepResearch);
        }
        "Create Watch" => {
            let name = name_override.clone().unwrap_or_else(|| suggestion.name.clone());
            let engine = if suggestion.needs_js { Engine::Playwright } else { default_engine };
            let extraction = suggestion.selector_hint.as_ref()
                .map(|sel| Extraction::Selector { selector: sel.clone() })
                .unwrap_or_else(|| default_extraction.clone());

            Ok((
                name,
                final_url,
                suggestion.interval_secs,
                suggestion.agent_enabled,
                suggestion.agent_instructions.clone(),
                extraction,
                engine,
            ))
        }
        "Select Different Variant" => {
            // Let user select which variant to monitor
            let variant_names: Vec<String> = suggestion.variants.iter()
                .enumerate()
                .map(|(i, v)| {
                    let status = v.status.as_deref().unwrap_or("unknown");
                    format!("{}. {} - {}", i + 1, v.name, status)
                })
                .collect();

            let selected = Select::new("Which variant do you want to monitor?", variant_names)
                .prompt()
                .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

            // Parse the selection to get index
            let selected_idx = selected.split('.').next()
                .and_then(|s| s.trim().parse::<usize>().ok())
                .map(|n| n - 1)
                .unwrap_or(0);

            let selected_variant = &suggestion.variants[selected_idx];

            // Construct URL with variant
            let variant_url = if let Some(ref hint) = selected_variant.url_hint {
                construct_variant_url(url, hint)
            } else {
                url.to_string()
            };

            // Update name to include variant
            let name = name_override.clone().unwrap_or_else(|| {
                format!("{} {}", suggestion.name, selected_variant.name)
            });

            // Update instructions to be variant-specific
            let instructions = Some(format!(
                "Monitor {} variant. Alert when status changes from '{}'",
                selected_variant.name,
                selected_variant.status.as_deref().unwrap_or("current")
            ));

            let engine = if suggestion.needs_js { Engine::Playwright } else { default_engine };
            let extraction = suggestion.selector_hint.as_ref()
                .map(|sel| Extraction::Selector { selector: sel.clone() })
                .unwrap_or_else(|| default_extraction.clone());

            println!("  Selected variant: {}", selected_variant.name);
            if variant_url != url {
                println!("  Using URL: {}", variant_url.cyan());
            }

            Ok((
                name,
                variant_url,
                suggestion.interval_secs,
                true,
                instructions,
                extraction,
                engine,
            ))
        }
        "Customize" => {
            // Manual customization flow
            let name = Text::new("Name for this watch?")
                .with_default(&name_override.clone().unwrap_or_else(|| suggestion.name.clone()))
                .prompt()
                .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

            let interval_str = Text::new("Check interval (e.g., 5m, 1h)?")
                .with_default(&format_interval(suggestion.interval_secs))
                .prompt()
                .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

            let custom_interval = crate::utils::parse_interval_str(&interval_str)
                .unwrap_or(suggestion.interval_secs);

            let use_ai = Confirm::new("Enable AI analysis?")
                .with_default(suggestion.agent_enabled)
                .prompt()
                .unwrap_or(suggestion.agent_enabled);

            let instructions = if use_ai {
                let inst = Text::new("What should AI watch for?")
                    .with_default(suggestion.agent_instructions.as_deref().unwrap_or(""))
                    .prompt()
                    .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;
                if inst.is_empty() { None } else { Some(inst) }
            } else {
                None
            };

            let use_js = if suggestion.needs_js {
                Confirm::new("Use JavaScript rendering (recommended)?")
                    .with_default(true)
                    .prompt()
                    .unwrap_or(true)
            } else {
                Confirm::new("Use JavaScript rendering?")
                    .with_default(false)
                    .prompt()
                    .unwrap_or(false)
            };

            let engine = if use_js { Engine::Playwright } else { Engine::Http };
            let extraction = suggestion.selector_hint.as_ref()
                .map(|sel| Extraction::Selector { selector: sel.clone() })
                .unwrap_or_else(|| default_extraction.clone());

            Ok((
                name,
                final_url,
                custom_interval,
                use_ai,
                instructions,
                extraction,
                engine,
            ))
        }
        "Cancel" | _ => {
            Err(kto::KtoError::ConfigError("Watch creation cancelled".into()))
        }
    }
}

/// Construct a URL with variant parameters
fn construct_variant_url(base_url: &str, url_hint: &str) -> String {
    // Parse the base URL
    if let Ok(mut parsed) = url::Url::parse(base_url) {
        // Check if url_hint is a full query param (contains =)
        if url_hint.contains('=') {
            // Split the hint into key=value pairs
            for param in url_hint.split('&') {
                if let Some((key, value)) = param.split_once('=') {
                    // Remove existing param with same key, add new one
                    let pairs: Vec<(String, String)> = parsed.query_pairs()
                        .filter(|(k, _)| k != key)
                        .map(|(k, v)| (k.to_string(), v.to_string()))
                        .collect();

                    parsed.set_query(None);
                    for (k, v) in pairs {
                        parsed.query_pairs_mut().append_pair(&k, &v);
                    }
                    parsed.query_pairs_mut().append_pair(key, value);
                }
            }
        } else {
            // Just append as-is (might be a path segment or raw param)
            let query = parsed.query().map(|q| format!("{}&{}", q, url_hint))
                .unwrap_or_else(|| url_hint.to_string());
            parsed.set_query(Some(&query));
        }
        parsed.to_string()
    } else {
        // Fallback: just append
        if base_url.contains('?') {
            format!("{}&{}", base_url, url_hint)
        } else {
            format!("{}?{}", base_url, url_hint)
        }
    }
}

// ============================================================================
// URL Transform Helper Functions
// ============================================================================

/// Display a transform suggestion and let user accept/decline
/// Returns Some((name, url, engine, extraction, interval)) if accepted, None if declined
fn display_transform_suggestion(
    original_url: &str,
    transform: &TransformMatch,
    name_override: &Option<String>,
    default_interval: u64,
    _tags: &[String],
    _use_profile: bool,
    yes: bool,
    interactive: bool,
) -> Result<Option<(String, String, Engine, Extraction, u64)>> {
    let transformed_url = transform.url.as_str();

    // Generate a default name from the URL
    let default_name = generate_name_from_url(&transform.url);

    if yes {
        // Auto-accept with --yes flag
        let name = name_override.clone().unwrap_or(default_name);
        let extraction = if transform.engine == Engine::Rss {
            Extraction::Rss
        } else {
            Extraction::Auto
        };

        // Show user-friendly output (no jargon)
        println!("\n  Found: {}", transform.description);

        return Ok(Some((
            name,
            transformed_url.to_string(),
            transform.engine.clone(),
            extraction,
            default_interval,
        )));
    }

    if !interactive {
        // Non-interactive without --yes, just show info
        return Ok(None);
    }

    // Interactive mode - show user-friendly suggestion
    println!();
    let platform_name = detect_platform_name(transform.url.host_str());
    println!("{} detected", platform_name.cyan());
    println!();
    println!("  Found: {}", transform.description.green());
    println!();

    // User-friendly description instead of technical jargon
    if transform.engine == Engine::Rss {
        println!("  Will notify you when new items are published.");
    } else {
        println!("  Will monitor the page for changes.");
    }
    println!();

    let choices = vec!["Accept (recommended)", "Use original URL instead", "Cancel"];
    let choice = Select::new("How would you like to proceed?", choices)
        .prompt()
        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

    match choice {
        "Accept (recommended)" => {
            let name = match name_override {
                Some(n) => n.clone(),
                None => {
                    Text::new("Name for this watch?")
                        .with_default(&default_name)
                        .prompt()
                        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?
                }
            };

            let extraction = if transform.engine == Engine::Rss {
                Extraction::Rss
            } else {
                Extraction::Auto
            };

            Ok(Some((
                name,
                transformed_url.to_string(),
                transform.engine.clone(),
                extraction,
                default_interval,
            )))
        }
        "Use original URL instead" => {
            // User declined - return None to fall through to normal flow
            println!("  Using original URL: {}", original_url);
            Ok(None)
        }
        "Cancel" | _ => {
            Err(kto::KtoError::ConfigError("Watch creation cancelled".into()))
        }
    }
}

/// Create a watch directly from transform match (bypassing AI analysis)
fn create_watch_from_transform(
    db: &Database,
    name: String,
    url: String,
    engine: Engine,
    extraction: Extraction,
    interval: u64,
    tags: Vec<String>,
    use_profile: bool,
    interactive: bool,
    yes: bool,
) -> Result<()> {
    println!("\n  Fetching {}...", url);

    // Fetch the page to create initial snapshot
    let content = fetch::fetch(&url, engine.clone(), &std::collections::HashMap::new())?;

    // Extract content
    let extracted = extract::extract(&content, &extraction)?;

    // Create watch
    let mut watch = Watch::new(name.clone(), url);
    watch.interval_secs = interval.max(10);
    watch.engine = engine;
    watch.extraction = extraction;
    watch.tags = tags;
    watch.use_profile = use_profile;

    // No agent config for transform-based watches by default
    // (RSS feeds don't need AI analysis in most cases)

    db.insert_watch(&watch)?;

    // Create initial snapshot
    let normalized = normalize(&extracted, &watch.normalization);
    let hash = hash_content(&normalized);

    let snapshot = Snapshot {
        id: Uuid::new_v4(),
        watch_id: watch.id,
        fetched_at: Utc::now(),
        raw_html: Some(zstd::encode_all(content.html.as_bytes(), 3)?),
        extracted: normalized,
        content_hash: hash.clone(),
    };
    db.insert_snapshot(&snapshot)?;

    // User-friendly success output
    let intent_description = platform_detect::describe_watch_intent(&watch.engine, false, None);
    let success_msg = platform_detect::format_watch_created(
        &name,
        &intent_description,
        watch.interval_secs,
        false,
    );
    println!("{}", success_msg);

    if !watch.tags.is_empty() {
        println!("   Tags: {}", watch.tags.join(", "));
    }

    // Prompt for notification setup if not configured and interactive
    let mut config = Config::load()?;
    if config.default_notify.is_none() && interactive && !yes {
        println!();
        if let Some(target) = super::prompt_notification_setup()? {
            config.default_notify = Some(target);
            config.save()?;
            println!("  Notification settings saved.");
        }
    }

    if !is_daemon_running() {
        println!("\n  Run `kto daemon` to start monitoring.");
    }

    Ok(())
}

/// Create a watch from a high-confidence transform match - zero prompts!
/// This is the "magical" happy path for known platforms like GitHub, Reddit, etc.
fn create_watch_from_transform_magical(
    db: &Database,
    original_url: &str,
    transform: &TransformMatch,
    name_override: Option<String>,
    default_interval: u64,
    tags: Vec<String>,
    use_profile: bool,
    interactive: bool,
    yes: bool,
) -> Result<()> {
    let transformed_url = transform.url.as_str();
    let engine = transform.engine.clone();

    // Step 1: Show we're analyzing
    println!("\n  Analyzing {}...", original_url.split('/').take(3).collect::<Vec<_>>().join("/"));

    // Step 2: Fetch to get content and validate
    let content = match fetch::fetch(transformed_url, engine.clone(), &std::collections::HashMap::new()) {
        Ok(c) => c,
        Err(e) => {
            // User-friendly error
            let msg = platform_detect::friendly_error_message(&e.to_string(), original_url);
            return Err(kto::KtoError::ConfigError(msg));
        }
    };

    // Step 3: Extract content
    let extraction = if engine == Engine::Rss {
        Extraction::Rss
    } else {
        Extraction::Auto
    };
    let extracted = extract::extract(&content, &extraction)?;

    // Step 4: Get name (from page title, URL, or override)
    let default_name = generate_name_from_url(&transform.url);
    let name = name_override.unwrap_or(default_name);

    // Step 5: Get a preview of what we're watching
    let latest_item = if engine == Engine::Rss {
        // For RSS, get the first item title
        extract_first_rss_item(&extracted)
    } else {
        None
    };

    // Step 6: Show the user-friendly preview
    println!();
    let preview = platform_detect::format_known_platform_preview(
        original_url,
        &detect_platform_name(transform.url.host_str()),
        transform.description,
        latest_item.as_deref(),
    );
    println!("{}", preview);

    // Step 7: Create watch
    let mut watch = Watch::new(name.clone(), transformed_url.to_string());
    watch.interval_secs = default_interval.max(10);
    watch.engine = engine.clone();
    watch.extraction = extraction;
    watch.tags = tags;
    watch.use_profile = use_profile;

    db.insert_watch(&watch)?;

    // Step 8: Create initial snapshot
    let normalized = normalize(&extracted, &watch.normalization);
    let hash = hash_content(&normalized);

    let snapshot = Snapshot {
        id: Uuid::new_v4(),
        watch_id: watch.id,
        fetched_at: Utc::now(),
        raw_html: Some(zstd::encode_all(content.html.as_bytes(), 3)?),
        extracted: normalized,
        content_hash: hash,
    };
    db.insert_snapshot(&snapshot)?;

    // Step 9: Show success message (no jargon!)
    let intent_description = platform_detect::describe_watch_intent(&watch.engine, false, None);
    let success_msg = platform_detect::format_watch_created(
        &name,
        &intent_description,
        watch.interval_secs,
        false,
    );
    println!("{}", success_msg);

    // Step 10: Prompt for notification setup if needed
    let mut config = Config::load()?;
    if config.default_notify.is_none() && interactive && !yes {
        println!();
        if let Some(target) = super::prompt_notification_setup()? {
            config.default_notify = Some(target);
            config.save()?;
            println!("  Notification settings saved.");
        }
    }

    if !is_daemon_running() {
        println!("\n  Run `kto daemon` to start monitoring.");
    }

    Ok(())
}

/// Extract the first item title from RSS feed content
fn extract_first_rss_item(rss_content: &str) -> Option<String> {
    // RSS content is already formatted by fetch, look for first item
    for line in rss_content.lines() {
        let trimmed = line.trim();
        if !trimmed.is_empty() && !trimmed.starts_with('-') && !trimmed.starts_with('[') {
            // Skip header lines, return first actual content
            if trimmed.len() > 5 && trimmed.len() < 100 {
                return Some(trimmed.to_string());
            }
        }
    }
    None
}

/// Get a human-readable platform name from host
fn detect_platform_name(host: Option<&str>) -> String {
    match host {
        Some("github.com") => "GitHub Repository".to_string(),
        Some("gitlab.com") => "GitLab Project".to_string(),
        Some("codeberg.org") => "Codeberg Repository".to_string(),
        Some("news.ycombinator.com") => "Hacker News".to_string(),
        Some(h) if h.contains("reddit.com") => "Reddit".to_string(),
        Some("pypi.org") => "PyPI Package".to_string(),
        Some("crates.io") => "Crates.io Package".to_string(),
        Some("hub.docker.com") => "Docker Hub".to_string(),
        Some("www.npmjs.com") => "npm Package".to_string(),
        Some(h) => h.to_string(),
        None => "Site".to_string(),
    }
}

/// Generate a human-readable name from a URL
fn generate_name_from_url(url: &url::Url) -> String {
    // Try to extract meaningful name from path
    let path = url.path().trim_matches('/');
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    // For GitHub/GitLab repos: "owner/repo" -> "owner/repo releases"
    if let Some(host) = url.host_str() {
        if (host == "github.com" || host == "gitlab.com" || host == "codeberg.org")
            && segments.len() >= 2
        {
            let owner = segments[0];
            let repo = segments[1];
            return format!("{}/{}", owner, repo);
        }

        // For Reddit: "r/subreddit" -> "r/subreddit"
        if host.contains("reddit.com") && segments.len() >= 2 && segments[0] == "r" {
            return format!("r/{}", segments[1]);
        }

        // For HN
        if host == "news.ycombinator.com" {
            return "Hacker News".to_string();
        }

        // For PyPI
        if host == "pypi.org" && segments.len() >= 2 && segments[0] == "project" {
            return format!("PyPI: {}", segments[1]);
        }
    }

    // Fallback: use host
    url.host_str()
        .unwrap_or("Watch")
        .to_string()
}

// ============================================================================
// Deep Research Mode
// ============================================================================

/// Run the deep research flow for watch creation
fn run_deep_research_flow(
    input: &str,
    url: &str,
    name_override: Option<String>,
    default_interval: u64,
    tags: Vec<String>,
    use_profile: bool,
    yes: bool,
    interactive: bool,
) -> Result<()> {
    let db = Database::open()?;

    println!("\n  {} Deep Research Mode", "🔬".bold());
    println!("  Analyzing {}...", url);

    // Check if there's a transform rule that specifies Playwright
    // If so, skip HTTP fetch to avoid timeout on JS-heavy sites (e.g., npm)
    let parsed_url = url::Url::parse(url).ok();
    let detected_intent = Intent::detect(input);
    let transform_match = parsed_url
        .as_ref()
        .and_then(|u| transforms::match_transform(u, detected_intent));

    let skip_http = transform_match
        .as_ref()
        .map(|m| m.engine == Engine::Playwright)
        .unwrap_or(false);

    if skip_http {
        println!("  Note: Transform rule specifies Playwright - skipping HTTP fetch");
    }

    // Step 1: Dual fetch (HTTP and Playwright)
    let (http_content, js_content) = dual_fetch_with_hint(url, skip_http)?;

    // Step 2: Extract content from both
    let http_html = http_content.as_ref().map(|c| c.html.as_str());
    let http_extracted = http_content.as_ref()
        .and_then(|c| extract::extract(c, &Extraction::Auto).ok());
    let js_extracted = js_content.as_ref()
        .and_then(|c| extract::extract(c, &Extraction::Auto).ok());

    // Step 3: Detect site type
    let site_type = http_html.and_then(|html| fetch::detect_site_type(url, html));
    if let Some(ref st) = site_type {
        println!("  Detected: {}", st.cyan());
    }

    // Step 4: Discover feeds from HTML
    let discovered_feeds = if let Some(html) = http_html {
        println!("  Discovering feeds...");
        let feeds = fetch::discover_feeds(url, html);
        if !feeds.is_empty() {
            println!("  Found {} feed(s)", feeds.len());
        }
        feeds
    } else {
        vec![]
    };

    // Step 5: Extract JSON-LD
    let jsonld_data = http_html.and_then(|html| extract::extract_raw_jsonld(html));
    if jsonld_data.is_some() {
        println!("  Found JSON-LD structured data");
    }

    // Step 6: Run deep research analysis
    println!("  Analyzing with AI (this may take a moment)...");
    let research_result = match agent::deep_research_analysis(
        url,
        input,
        http_extracted.as_deref(),
        js_extracted.as_deref(),
        &discovered_feeds,
        jsonld_data.as_deref(),
        site_type.as_deref(),
    ) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("  Research failed: {} (using fallback)", e);
            DeepResearchResult::fallback(url, input)
        }
    };

    // Step 7: Display results
    display_research_results(&research_result);

    // Step 7.5: Apply URL modifications (variant params, etc.)
    let modified_url = apply_url_modifications(url, &research_result);
    if modified_url != url {
        println!("  URL modified: {}", modified_url.cyan());
    }

    // Step 8: User confirmation or auto-accept
    let (name, final_url, final_engine, final_extraction, final_interval, agent_enabled, agent_instructions) =
        if yes {
            // Auto-accept
            let name = name_override.unwrap_or_else(|| {
                if let Ok(parsed) = url::Url::parse(&modified_url) {
                    generate_name_from_url(&parsed)
                } else {
                    "Watch".to_string()
                }
            });
            let engine = research_result.engine.to_engine();
            let extraction = match research_result.extraction.strategy.as_str() {
                "selector" => {
                    if let Some(ref sel) = research_result.extraction.selector {
                        Extraction::Selector { selector: sel.clone() }
                    } else {
                        Extraction::Auto
                    }
                }
                "rss" => Extraction::Rss,
                "json_ld" => Extraction::JsonLd { types: None },
                _ => Extraction::Auto,
            };

            (
                name,
                modified_url.clone(),
                engine,
                extraction,
                research_result.interval_secs,
                research_result.agent_instructions.is_some(),
                research_result.agent_instructions.clone(),
            )
        } else if interactive {
            // Interactive confirmation
            confirm_research_results(
                &modified_url,
                &research_result,
                &name_override,
                default_interval,
            )?
        } else {
            return Err(kto::KtoError::ConfigError(
                "Deep research requires interactive mode or --yes flag".into()
            ));
        };

    // Step 9: Fetch with final engine
    println!("\n  Fetching with {:?} engine...", final_engine);
    let content = fetch::fetch(&final_url, final_engine.clone(), &std::collections::HashMap::new())?;
    let extracted = extract::extract(&content, &final_extraction)?;

    // Step 10: Create watch
    let mut watch = Watch::new(name.clone(), final_url);
    watch.interval_secs = final_interval.max(10);
    watch.engine = final_engine;
    watch.extraction = final_extraction;
    watch.tags = tags;
    watch.use_profile = use_profile;

    if agent_enabled {
        watch.agent_config = Some(AgentConfig {
            enabled: true,
            prompt_template: None,
            instructions: agent_instructions,
        });
    }

    db.insert_watch(&watch)?;

    // Create initial snapshot
    let normalized = normalize(&extracted, &watch.normalization);
    let hash = hash_content(&normalized);

    let snapshot = Snapshot {
        id: Uuid::new_v4(),
        watch_id: watch.id,
        fetched_at: Utc::now(),
        raw_html: Some(zstd::encode_all(content.html.as_bytes(), 3)?),
        extracted: normalized,
        content_hash: hash.clone(),
    };
    db.insert_snapshot(&snapshot)?;

    println!("\n  Created watch \"{}\"", name);
    println!("  Initial hash: {}", &hash[..8]);
    println!("  Engine: {:?}", watch.engine);
    if watch.agent_config.is_some() {
        println!("  AI Agent: enabled");
    }
    if watch.use_profile {
        println!("  Profile: enabled");
    }
    if !watch.tags.is_empty() {
        println!("  Tags: {}", watch.tags.join(", "));
    }
    println!("  Checking every {}", format_interval(watch.interval_secs));

    // Prompt for notification setup if not configured
    let mut config = Config::load()?;
    if config.default_notify.is_none() && interactive && !yes {
        println!();
        if let Some(target) = super::prompt_notification_setup()? {
            config.default_notify = Some(target);
            config.save()?;
            println!("  Notification settings saved.");
        }
    }

    if !is_daemon_running() {
        println!("\n  Run `kto daemon` to start monitoring.");
    }

    Ok(())
}

/// Apply URL modifications from research results (variant params, etc.)
fn apply_url_modifications(url: &str, result: &DeepResearchResult) -> String {
    if let Some(ref mods) = result.url_modifications {
        if let Some(ref variant) = mods.variant_param {
            if !variant.is_empty() {
                if url.contains('?') {
                    return format!("{}&variant={}", url, variant);
                } else {
                    return format!("{}?variant={}", url, variant);
                }
            }
        }
    }
    url.to_string()
}

/// Display deep research results
fn display_research_results(result: &DeepResearchResult) {
    println!();
    println!("  {}", "Deep Research Results".bold().underline());
    println!();
    println!("  {}", result.summary);

    // Web research findings (if available)
    if let Some(ref web) = result.web_research {
        println!();
        println!("  {}:", "Web Research".bold());
        if !web.queries_made.is_empty() {
            println!("    Searched: {}", web.queries_made.join(", "));
        }
        for finding in &web.relevant_findings {
            println!("{}", finding);
        }
        if !web.api_endpoints.is_empty() {
            println!();
            println!("  Discovered APIs:");
            for api in &web.api_endpoints {
                let auth = if api.requires_auth { " (auth required)" } else { "" };
                println!("    {} - {}{}", api.url_pattern, api.description, auth);
            }
        }
        if !web.community_tips.is_empty() {
            println!();
            println!("  Community Tips:");
            for tip in &web.community_tips {
                println!("{}", tip);
            }
        }
    }

    // Discovered feeds
    if !result.discovered_feeds.is_empty() {
        println!();
        println!("  {}:", "Discovered Feeds".bold());
        for feed in &result.discovered_feeds {
            let intent_marker = if feed.matches_intent {
                " ← matches intent".green().to_string()
            } else {
                "".to_string()
            };
            println!("    {} ({}, via {}){}", feed.url, feed.feed_type, feed.discovery_method, intent_marker);
        }
    }

    // Recommended approach
    println!();
    println!("  {}:", "Recommended Approach".bold());
    println!("    Engine: {}", result.engine.engine_type.cyan());
    println!("      {}", result.engine.reason.dimmed());
    println!("    Extraction: {}", result.extraction.strategy.cyan());
    if let Some(ref sel) = result.extraction.selector {
        println!("      Selector: {}", sel);
    }
    println!("      {}", result.extraction.reason.dimmed());

    // URL modifications
    if let Some(ref mods) = result.url_modifications {
        if mods.variant_param.is_some() {
            println!("    URL Mod: variant={}", mods.variant_param.as_ref().unwrap().cyan());
            println!("      {}", mods.reason.dimmed());
        }
    }

    // Recommended selectors
    if !result.selectors.is_empty() {
        println!();
        println!("  Stable Selectors:");
        for sel in &result.selectors {
            let stability = format!("{:.0}%", sel.stability_score * 100.0);
            println!("    {} ({})", sel.selector, stability.dimmed());
            println!("      {}", sel.description.dimmed());
        }
    }

    // Key insights
    if !result.insights.is_empty() {
        println!();
        println!("  {}:", "Key Insights".bold());
        for insight in &result.insights {
            println!("{}", insight);
        }
    }

    // Agent instructions
    if let Some(ref instructions) = result.agent_instructions {
        println!();
        println!("  AI Instructions: \"{}\"", truncate_str(instructions, 60));
    }

    // Confidence
    println!();
    let confidence_color = if result.confidence >= 0.8 {
        format!("{:.0}%", result.confidence * 100.0).green()
    } else if result.confidence >= 0.5 {
        format!("{:.0}%", result.confidence * 100.0).yellow()
    } else {
        format!("{:.0}%", result.confidence * 100.0).red()
    };
    println!("  Confidence: {}", confidence_color);
    println!();
}

/// Interactive confirmation of research results
fn confirm_research_results(
    url: &str,
    result: &DeepResearchResult,
    name_override: &Option<String>,
    _default_interval: u64,
) -> Result<(String, String, Engine, Extraction, u64, bool, Option<String>)> {
    // Check if there's a feed that matches intent
    let matching_feed = result.discovered_feeds.iter().find(|f| f.matches_intent);

    // Build choices
    let mut choices = vec!["Accept recommendations", "Customize"];

    // Add option to use matching feed if available
    if matching_feed.is_some() {
        choices.insert(1, "Use discovered feed");
    }

    choices.push("Cancel");

    let choice = Select::new("What would you like to do?", choices)
        .prompt()
        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

    match choice {
        "Accept recommendations" => {
            let name = match name_override {
                Some(n) => n.clone(),
                None => {
                    let default_name = if let Ok(parsed) = url::Url::parse(url) {
                        generate_name_from_url(&parsed)
                    } else {
                        "Watch".to_string()
                    };
                    Text::new("Name for this watch?")
                        .with_default(&default_name)
                        .prompt()
                        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?
                }
            };

            let engine = result.engine.to_engine();
            let extraction = match result.extraction.strategy.as_str() {
                "selector" => {
                    if let Some(ref sel) = result.extraction.selector {
                        Extraction::Selector { selector: sel.clone() }
                    } else {
                        Extraction::Auto
                    }
                }
                "rss" => Extraction::Rss,
                "json_ld" => Extraction::JsonLd { types: None },
                _ => Extraction::Auto,
            };

            Ok((
                name,
                url.to_string(),
                engine,
                extraction,
                result.interval_secs,
                result.agent_instructions.is_some(),
                result.agent_instructions.clone(),
            ))
        }
        "Use discovered feed" => {
            let feed = matching_feed.expect("Feed should exist");
            let name = match name_override {
                Some(n) => n.clone(),
                None => {
                    let default_name = feed.title.clone().unwrap_or_else(|| {
                        if let Ok(parsed) = url::Url::parse(&feed.url) {
                            generate_name_from_url(&parsed)
                        } else {
                            "Watch".to_string()
                        }
                    });
                    Text::new("Name for this watch?")
                        .with_default(&default_name)
                        .prompt()
                        .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?
                }
            };

            println!("  Using feed: {}", feed.url.cyan());

            Ok((
                name,
                feed.url.clone(),
                Engine::Rss,
                Extraction::Rss,
                result.interval_secs,
                false, // RSS feeds usually don't need AI
                None,
            ))
        }
        "Customize" => {
            // Full customization
            let name = Text::new("Name for this watch?")
                .with_default(&name_override.clone().unwrap_or_else(|| {
                    if let Ok(parsed) = url::Url::parse(url) {
                        generate_name_from_url(&parsed)
                    } else {
                        "Watch".to_string()
                    }
                }))
                .prompt()
                .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

            // Engine selection
            let engine_choices = vec!["HTTP", "JavaScript (Playwright)", "RSS"];
            let default_engine_idx = match result.engine.engine_type.as_str() {
                "playwright" | "js" => 1,
                "rss" => 2,
                _ => 0,
            };
            let engine_choice = Select::new("Engine:", engine_choices)
                .with_starting_cursor(default_engine_idx)
                .prompt()
                .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

            let engine = match engine_choice {
                "JavaScript (Playwright)" => Engine::Playwright,
                "RSS" => Engine::Rss,
                _ => Engine::Http,
            };

            // Extraction strategy
            let extraction = if engine == Engine::Rss {
                Extraction::Rss
            } else {
                let extraction_choices = vec!["Auto", "CSS Selector", "JSON-LD"];
                let extraction_choice = Select::new("Extraction:", extraction_choices)
                    .prompt()
                    .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

                match extraction_choice {
                    "CSS Selector" => {
                        let default_sel = result.extraction.selector.as_deref()
                            .or_else(|| result.selectors.first().map(|s| s.selector.as_str()))
                            .unwrap_or("");
                        let sel = Text::new("CSS Selector:")
                            .with_default(default_sel)
                            .prompt()
                            .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;
                        Extraction::Selector { selector: sel }
                    }
                    "JSON-LD" => Extraction::JsonLd { types: None },
                    _ => Extraction::Auto,
                }
            };

            // Interval
            let interval_str = Text::new("Check interval (e.g., 5m, 1h)?")
                .with_default(&format_interval(result.interval_secs))
                .prompt()
                .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;

            let interval = crate::utils::parse_interval_str(&interval_str)
                .unwrap_or(result.interval_secs);

            // AI agent
            let use_ai = Confirm::new("Enable AI analysis?")
                .with_default(result.agent_instructions.is_some())
                .prompt()
                .unwrap_or(false);

            let instructions = if use_ai {
                let inst = Text::new("AI instructions:")
                    .with_default(result.agent_instructions.as_deref().unwrap_or(""))
                    .prompt()
                    .map_err(|e| kto::KtoError::ConfigError(e.to_string()))?;
                if inst.is_empty() { None } else { Some(inst) }
            } else {
                None
            };

            Ok((name, url.to_string(), engine, extraction, interval, use_ai, instructions))
        }
        "Cancel" | _ => {
            Err(kto::KtoError::ConfigError("Watch creation cancelled".into()))
        }
    }
}