bkmr 6.6.0

A Unified CLI Tool for Bookmark, Snippet, and Knowledge Management
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
// src/cli/bookmark_commands.rs
use crate::application::actions::MarkdownAction;
use crate::config::Settings;
// Service container dependency injection implemented via SearchCommandHandler
use crate::application::services::action_service::ActionService;
use crate::application::services::bookmark_service::BookmarkService;
use crate::application::services::tag_service::TagService;
use crate::application::services::template_service::TemplateService;
use crate::application::templates::bookmark_template::BookmarkTemplate;
use crate::cli::args::{Cli, Commands};
use crate::cli::error::{CliError, CliResult};
use crate::cli::process::{edit_bookmarks, execute_bookmark_default_action};
use crate::config::{get_config_file_path, ConfigSource};
use crate::domain::bookmark::Bookmark;
use crate::domain::error_context::CliErrorContext;
use crate::domain::repositories::repository::BookmarkRepository;
use crate::domain::search::SemanticSearch;
use crate::domain::system_tag::SystemTag;
use crate::domain::tag::Tag;
use crate::infrastructure::di::ServiceContainer;
use crate::infrastructure::embeddings::DummyEmbedding;
use crate::infrastructure::json::{write_bookmarks_as_json, JsonBookmarkView};
use crate::infrastructure::repositories::sqlite::migration;
use crate::infrastructure::repositories::sqlite::repository::{
    print_db_schema, SqliteBookmarkRepository,
};
use crate::util::argument_processor::ArgumentProcessor;
use crate::util::helper::{confirm, ensure_int_vector, is_stdout_piped};
use crate::util::helper::{format_file_path, format_mtime};
use chrono;
use crossterm::style::Stylize;
use std::collections::HashSet;
use std::io::Write;
use std::path::Path;
use std::sync::Arc;
use std::{fs, io};
use termcolor::StandardStream;
use tracing::{instrument, warn};

// Helper function to get and validate IDs
fn get_ids(ids: String) -> CliResult<Vec<i32>> {
    // ensure_int_vector(&ids.split(',').map(String::from).collect())
    //     .ok_or_else(|| CliError::InvalidIdFormat(format!("Invalid ID format: {}", ids)))
    let string_vec: Vec<String> = ids.split(',').map(|s| s.trim().to_string()).collect();
    ensure_int_vector(&string_vec)
        .ok_or_else(|| CliError::InvalidIdFormat(format!("Invalid ID format: {}", ids)))
}

/// Format action description, incorporating custom opener if present
pub fn format_action_description(base_description: &str, opener: Option<&String>) -> String {
    match opener {
        Some(o) => format!("Open with {}", o),
        None => base_description.to_string(),
    }
}

#[instrument(skip(stderr, cli, services))]
pub fn semantic_search(
    mut stderr: StandardStream,
    cli: Cli,
    services: &ServiceContainer,
) -> CliResult<()> {
    if let Commands::SemSearch {
        query,
        limit,
        non_interactive,
    } = cli.command.unwrap()
    {
        // Check if embedder is DummyEmbedding and provide helpful error message
        if services.embedder.as_any().type_id() == std::any::TypeId::of::<DummyEmbedding>() {
            writeln!(
                stderr,
                "{}",
                "Error: Semantic search requires embeddings. Use --openai flag.".red()
            )
            .cli_context("writing DummyEmbedding error message to stderr")?;
            return Err(CliError::CommandFailed(
                "No embeddings available - use --openai flag".to_string(),
            ));
        }

        // Create the semantic search domain object
        let search = SemanticSearch::new(query, limit.map(|l| l as usize));

        // Perform semantic search
        let results = services
            .bookmark_service
            .semantic_search(&search)
            .cli_context("performing semantic search on bookmarks")?;

        if results.is_empty() {
            writeln!(stderr, "{}", "No bookmarks found".yellow())
                .cli_context("writing empty search result to stderr")?;
            return Ok(());
        }

        let is_piped = is_stdout_piped();

        if is_piped {
            // Generate plain-text output for piping
            for result in &results {
                println!(
                    "{}\t{}\t{}\t{}",
                    result.bookmark.id.unwrap_or(0),
                    result.bookmark.title,
                    result.bookmark.url,
                    result.similarity_percentage()
                );
            }
        } else {
            // Format and display results with similarity scores for interactive use
            for result in &results {
                writeln!(
                    stderr,
                    "{} {} [{}] ({})",
                    result
                        .bookmark
                        .id
                        .map_or("?".to_string(), |id| id.to_string())
                        .blue(),
                    result.bookmark.title.clone().green(),
                    result.bookmark.formatted_tags().yellow(),
                    result.similarity_percentage().cyan()
                )?;
                writeln!(stderr, "  {}", result.bookmark.url)?;
                if !result.bookmark.description.is_empty() {
                    writeln!(stderr, "  {}", result.bookmark.description)?;
                }
                writeln!(stderr)?;
            }
        }

        writeln!(stderr, "{} bookmarks found", results.len())?;

        // In interactive mode, prompt for actions
        if !non_interactive && !is_piped && !results.is_empty() && confirm("Open bookmark(s)?") {
            // Prompt for which bookmark to open
            print!("Enter ID(s) to open (comma-separated): ");
            io::stdout()
                .flush()
                .cli_context("flushing stdout after prompt")?;

            let mut input = String::new();
            io::stdin()
                .read_line(&mut input)
                .cli_context("reading user input for bookmark IDs")?;

            let ids = get_ids(input.trim().to_string())
                .cli_context("parsing bookmark IDs from user input")?;
            for id in ids {
                if let Some(result) = results.iter().find(|r| r.bookmark.id == Some(id)) {
                    execute_bookmark_default_action(
                        &result.bookmark,
                        services.action_service.clone(),
                    )
                    .cli_context("executing default action for selected bookmark")?;
                } else {
                    writeln!(stderr, "Bookmark with ID {} not found in results", id)?;
                }
            }
        }
    }
    Ok(())
}

#[instrument(skip(cli, bookmark_service, action_service, interpolation_service))]
pub fn open(
    cli: Cli,
    bookmark_service: Arc<dyn BookmarkService>,
    action_service: Arc<dyn ActionService>,
    interpolation_service: Arc<
        dyn crate::application::services::interpolation_service::InterpolationService,
    >,
) -> CliResult<()> {
    if let Commands::Open {
        ids,
        no_edit,
        file,
        script_args,
        stdout,
    } = cli.command.unwrap()
    {
        if file {
            // Handle direct file viewing
            handle_file_viewing(&ids).cli_context("handling direct file viewing")?;
        } else {
            // Handle bookmark opening (existing logic)

            for id in get_ids(ids).cli_context("parsing bookmark IDs for opening")? {
                if let Some(bookmark) = bookmark_service
                    .get_bookmark(id)
                    .cli_context("retrieving bookmark for opening")?
                {
                    if stdout {
                        // Output interpolated content to stdout instead of executing
                        let content = interpolation_service
                            .render_bookmark_url(&bookmark)
                            .map_err(|e| {
                                CliError::CommandFailed(format!("Failed to render content: {}", e))
                            })?;
                        println!("{}", content);
                    } else {
                        // Use action service to execute default action
                        let base_description = action_service.get_default_action_description(&bookmark);
                        let action_type = format_action_description(base_description, bookmark.opener.as_ref());
                        eprintln!("Performing '{}' for: {}", action_type, bookmark.title);

                        // Execute default action with access recording handled by action service
                        action_service.execute_default_action_with_options(
                            &bookmark,
                            no_edit,
                            &script_args,
                        )?;
                    }
                } else {
                    eprintln!("Bookmark with ID {} not found", id);
                }
            }
        }
    }
    Ok(())
}

/// Handle direct file viewing by creating a temporary bookmark and using existing markdown functionality
fn handle_file_viewing(file_path: &str) -> CliResult<()> {
    use crate::domain::action::BookmarkAction;
    use std::collections::HashSet;

    // Check if file exists first
    if !Path::new(file_path).exists() {
        return Err(CliError::Other(format!(
            "File not found: {}. Please check the path and try again.",
            file_path
        )));
    }

    // Extract filename for display
    let path = Path::new(file_path);
    let filename = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(file_path);

    eprintln!("Rendering file: {}", filename);

    // Create markdown action with dummy embedder (reuses existing file reading logic)
    let embedder = Arc::new(DummyEmbedding);
    let markdown_action = MarkdownAction::new(embedder);

    // Create a minimal bookmark structure - the MarkdownAction already handles file paths in url field
    let mut tags = HashSet::new();
    tags.insert(Tag::new("_md_").map_err(|e| CliError::Other(e.to_string()))?);

    let temp_bookmark = Bookmark {
        id: None,
        url: file_path.to_string(), // File path - MarkdownAction will detect this and read the file
        title: filename.to_string(),
        description: format!("Direct file view: {}", file_path),
        tags,
        access_count: 0,
        created_at: Some(chrono::Utc::now()),
        updated_at: chrono::Utc::now(),
        embedding: None,
        content_hash: None,
        embeddable: false,
        file_path: None,
        file_mtime: None,
        file_hash: None,
        opener: None,
        accessed_at: None,
    };

    // Execute the markdown action - it will handle file reading and rendering
    markdown_action
        .execute(&temp_bookmark)
        .cli_context("Failed to render file")?;

    Ok(())
}

/// Helper function to process content based on bookmark type
fn process_content_for_type(content: &str, system_tag: SystemTag) -> String {
    if matches!(
        system_tag,
        SystemTag::Markdown
            | SystemTag::Snippet
            | SystemTag::Text
            | SystemTag::Shell
            | SystemTag::Env
    ) {
        content.replace("\\n", "\n")
    } else {
        content.to_string()
    }
}

#[instrument(skip(cli, bookmark_service, template_service))]
pub fn add(
    cli: Cli,
    bookmark_service: Arc<dyn BookmarkService>,
    template_service: Arc<dyn TemplateService>,
) -> CliResult<()> {
    if let Commands::Add {
        url,
        tags,
        title,
        desc,
        no_web,
        edit,
        bookmark_type,
        clone_id,
        stdin,
        open_with,
    } = cli.command.unwrap()
    {
        // Convert bookmark_type string to SystemTag
        let system_tag = match bookmark_type.to_lowercase().as_str() {
            "snip" => SystemTag::Snippet,
            "text" => SystemTag::Text,
            "shell" => SystemTag::Shell,
            "md" | "markdown" => SystemTag::Markdown,
            "env" => SystemTag::Env,
            _ => SystemTag::Uri, // Default to Uri for anything else
        };

        // Parse tags using centralized argument processor
        let mut tag_set = ArgumentProcessor::parse_tags_with_error_handling(&tags)?;
        // Add the system tag if it's not Uri (which has an empty string as_str)
        if system_tag != SystemTag::Uri {
            if let Ok(system_tag_value) = Tag::new(system_tag.as_str()) {
                tag_set.insert(system_tag_value);
            }
        }

        // Handle stdin input - read content from stdin if requested
        let final_url = if stdin {
            use std::io::{self, Read};
            let mut content = String::new();
            io::stdin()
                .read_to_string(&mut content)
                .cli_context("Failed to read from stdin")?;

            // Trim trailing newline for cleaner content
            Some(content.trim_end().to_string())
        } else {
            url
        };

        // Prepare the template - either from clone or new
        let mut template = if let Some(id) = clone_id {
            // Get the bookmark to clone
            let bookmark = bookmark_service.get_bookmark(id)?.ok_or_else(|| {
                CliError::InvalidInput(format!("No bookmark found with ID {}", id))
            })?;

            // Create a template with the bookmark data but without ID
            let mut template = BookmarkTemplate::from_bookmark(&bookmark);
            template.id = None; // Clear ID to ensure a new bookmark will be created
            template
        } else {
            // Create a new template for the specific bookmark type
            BookmarkTemplate::for_type(system_tag)
        };

        // Override with provided values if they exist
        if let Some(url_value) = &final_url {
            template.url = process_content_for_type(url_value, system_tag);
        }

        if let Some(title_value) = &title {
            template.title = title_value.clone();
        }
        if let Some(desc_value) = &desc {
            template.comments = desc_value.clone();
        }

        // Add user-provided tags (keep existing tags for cloned bookmarks)
        for tag in &tag_set {
            template.tags.insert(tag.clone());
        }

        // If URL is provided, edit flag is not set, and we're not cloning,
        // use the simple add path without opening editor
        if final_url.is_some() && !edit && clone_id.is_none() {
            let url_value = final_url.unwrap();
            let processed_content = process_content_for_type(&url_value, system_tag);

            let mut bookmark = bookmark_service.add_bookmark(
                &processed_content,
                title.as_deref(),
                desc.as_deref(),
                Some(&tag_set),
                !no_web,
            )?;

            // Set custom opener if provided
            if let Some(opener) = open_with {
                bookmark.opener = if opener.is_empty() {
                    None
                } else {
                    Some(opener)
                };
                bookmark_service.update_bookmark(bookmark.clone(), false)?;
            }

            eprintln!(
                "Added bookmark: {} (ID: {})",
                bookmark.title,
                bookmark.id.unwrap_or(0)
            );
            return Ok(());
        }

        // Otherwise, open in editor
        // Convert template to a temporary bookmark for editing
        let temp_bookmark = template
            .to_bookmark(None)
            .map_err(|e| CliError::Other(format!("Failed to create temporary bookmark: {}", e)))?;

        // Open the editor with our prepared template
        match template_service.edit_bookmark_with_template(Some(temp_bookmark)) {
            Ok((edited_bookmark, was_modified)) => {
                if !was_modified {
                    eprintln!("No changes made in editor. Bookmark not added.");
                    return Ok(());
                }

                // Add the edited bookmark
                match bookmark_service.add_bookmark(
                    &edited_bookmark.url,
                    Some(&edited_bookmark.title),
                    Some(&edited_bookmark.description),
                    Some(&edited_bookmark.tags),
                    false, // Don't fetch metadata since we've already edited it
                ) {
                    Ok(mut bookmark) => {
                        // Set custom opener if provided via CLI flag
                        // Note: opener can also be set via the edit template
                        if let Some(opener) = &open_with {
                            bookmark.opener = if opener.is_empty() {
                                None
                            } else {
                                Some(opener.clone())
                            };
                            bookmark_service.update_bookmark(bookmark.clone(), false)?;
                        }

                        eprintln!(
                            "Added bookmark: {} (ID: {})",
                            bookmark.title,
                            bookmark.id.unwrap_or(0)
                        );
                    }
                    Err(e) => {
                        return Err(CliError::CommandFailed(format!(
                            "Failed to add bookmark: {}",
                            e
                        )));
                    }
                }
            }
            Err(e) => {
                return Err(CliError::CommandFailed(format!(
                    "Failed to edit bookmark: {}",
                    e
                )));
            }
        }
    }
    Ok(())
}

#[instrument(skip(cli, bookmark_service))]
pub fn delete(cli: Cli, bookmark_service: Arc<dyn BookmarkService>) -> CliResult<()> {
    if let Commands::Delete { ids } = cli.command.unwrap() {
        let id_list = get_ids(ids)?;

        for id in id_list {
            if let Some(bookmark) = bookmark_service.get_bookmark(id)? {
                eprintln!("Deleting: {} ({})", bookmark.title, bookmark.url);

                if confirm("Confirm delete?") {
                    match bookmark_service.delete_bookmark(id) {
                        Ok(true) => eprintln!("Deleted bookmark with ID {}", id),
                        Ok(false) => eprintln!("Bookmark with ID {} not found", id),
                        Err(e) => eprintln!("Error deleting bookmark with ID {}: {}", id, e),
                    }
                } else {
                    eprintln!("Deletion cancelled");
                }
            } else {
                eprintln!("Bookmark with ID {} not found", id);
            }
        }
    }
    Ok(())
}

#[instrument(skip(cli, bookmark_service, tag_service))]
pub fn update(
    cli: Cli,
    bookmark_service: Arc<dyn BookmarkService>,
    tag_service: Arc<dyn TagService>,
) -> CliResult<()> {
    if let Commands::Update {
        ids,
        tags,
        tags_not,
        force,
        open_with,
    } = cli.command.unwrap()
    {
        let id_list = get_ids(ids)?;

        for id in id_list {
            if let Some(bookmark) = bookmark_service.get_bookmark(id)? {
                eprintln!("Updating: {} ({})", bookmark.title, bookmark.url);

                if force && tags.is_some() {
                    // Replace all tags
                    let tag_str = tags.as_ref().unwrap();
                    let parsed_tags = tag_service.parse_tag_string(tag_str)?;
                    let tag_set = parsed_tags.into_iter().collect::<HashSet<_>>();

                    let updated = bookmark_service.replace_bookmark_tags(id, &tag_set)?;
                    eprintln!("Tags replaced: {}", updated.formatted_tags());
                } else {
                    // Add tags if provided
                    if let Some(tag_str) = &tags {
                        let parsed_tags = tag_service.parse_tag_string(tag_str)?;
                        let tag_set = parsed_tags.into_iter().collect::<HashSet<_>>();

                        let updated = bookmark_service.add_tags_to_bookmark(id, &tag_set)?;
                        eprintln!("Tags added: {}", updated.formatted_tags());
                    }

                    // Remove tags if provided
                    if let Some(tag_str) = &tags_not {
                        let parsed_tags = tag_service.parse_tag_string(tag_str)?;
                        let tag_set = parsed_tags.into_iter().collect::<HashSet<_>>();

                        let updated = bookmark_service.remove_tags_from_bookmark(id, &tag_set)?;
                        eprintln!("Tags removed: {}", updated.formatted_tags());
                    }
                }

                // Update custom opener if provided
                if let Some(opener) = &open_with {
                    // Fetch latest version to avoid stale data
                    if let Some(mut latest_bookmark) = bookmark_service.get_bookmark(id)? {
                        latest_bookmark.opener = if opener.is_empty() {
                            None
                        } else {
                            Some(opener.clone())
                        };
                        bookmark_service.update_bookmark(latest_bookmark, false)?;
                        if opener.is_empty() {
                            eprintln!("Custom opener cleared");
                        } else {
                            eprintln!("Custom opener set to: {}", opener);
                        }
                    }
                }
            } else {
                eprintln!("Bookmark with ID {} not found", id);
            }
        }
    }
    Ok(())
}

#[instrument(skip(cli, bookmark_service, template_service, settings))]
pub fn edit(
    cli: Cli,
    bookmark_service: Arc<dyn BookmarkService>,
    template_service: Arc<dyn TemplateService>,
    settings: &crate::config::Settings,
) -> CliResult<()> {
    if let Commands::Edit { ids, force_db } = cli.command.unwrap() {
        let id_list = get_ids(ids)?;

        // Get all bookmarks to edit first
        let mut bookmarks_to_edit = Vec::new();
        for id in &id_list {
            if let Some(bookmark) = bookmark_service.get_bookmark(*id)? {
                bookmarks_to_edit.push(bookmark);
            } else {
                eprintln!("Bookmark with ID {} not found", id);
            }
        }

        if bookmarks_to_edit.is_empty() {
            eprintln!("No bookmarks found to edit");
            return Ok(());
        }

        edit_bookmarks(
            id_list,
            force_db,
            bookmark_service,
            template_service,
            settings,
        )?;
    }
    Ok(())
}

#[instrument(skip(cli))]
pub fn show(cli: Cli, services: &ServiceContainer) -> CliResult<()> {
    if let Commands::Show { ids, is_json } = cli.command.unwrap() {
        let bookmark_service = services.bookmark_service.clone();

        let id_list = get_ids(ids)?;
        let mut bookmarks = Vec::new();

        for id in id_list {
            if let Some(_bookmark) = bookmark_service.get_bookmark(id)? {
                let updated_bookmark = bookmark_service.record_bookmark_access(id)?;
                bookmarks.push(updated_bookmark);
            } else {
                eprintln!("Bookmark with ID {} not found", id);
            }
        }

        if is_json {
            // Output bookmarks as JSON
            let json_views = JsonBookmarkView::from_domain_collection(&bookmarks);
            write_bookmarks_as_json(&json_views)?;
        } else {
            // Output bookmarks in detailed format (existing behavior)
            for bookmark in &bookmarks {
                print!("{}", show_bookmark_details(bookmark, services));
            }
        }
    }
    Ok(())
}

/// Shows detailed information about a bookmark, can be used by both show command and FZF CTRL-P
#[instrument(level = "debug")]
pub fn show_bookmark_details(bookmark: &Bookmark, services: &ServiceContainer) -> String {
    // Get the action service
    let action_service = services.action_service.clone();

    // Get the action description, incorporating custom opener if present
    let base_description = action_service.get_default_action_description(bookmark);
    let action_description = format_action_description(base_description, bookmark.opener.as_ref());

    // Format all the bookmark details
    let mut details = format!(
        "{} {} [{}] ({})\n  URL/Content: {}\n  Description: {}\n  Access count: {}\n  Created: {}\n  Updated: {}\n  Has embedding: {}\n  Default Action: {}",
        bookmark
            .id
            .map_or("?".to_string(), |id| id.to_string())
            .blue(),
        bookmark.title.clone().green(),
        bookmark.formatted_tags().yellow(),
        action_description.as_str().cyan(),
        bookmark.url,
        bookmark.description,
        bookmark.access_count,
        bookmark.created_at.map_or("N/A".to_string(), |dt| dt.to_string()),
        bookmark.updated_at,
        bookmark.embedding.is_some(),
        action_description
    );

    // Add file info if present
    if let (Some(file_path), Some(file_mtime)) = (&bookmark.file_path, bookmark.file_mtime) {
        let formatted_path = format_file_path(file_path, 120);
        let formatted_time = format_mtime(file_mtime);
        details.push_str(&format!(
            "\n  Source File: {} (modified: {})",
            formatted_path, formatted_time
        ));
    }

    details.push('\n');
    details
}

#[instrument(skip(cli))]
pub fn surprise(cli: Cli, services: &ServiceContainer) -> CliResult<()> {
    if let Commands::Surprise { n } = cli.command.unwrap() {
        let bookmark_service = services.bookmark_service.clone();
        let action_service = services.action_service.clone();

        // Get random bookmarks
        let count = if n < 1 { 1 } else { n as usize };
        let bookmarks = bookmark_service.get_random_bookmarks(count)?;

        if bookmarks.is_empty() {
            eprintln!("No bookmarks found");
            return Ok(());
        }

        eprintln!("Processing {} random bookmarks:", bookmarks.len());

        for bookmark in &bookmarks {
            // Get the action description, incorporating custom opener if present
            let base_description = action_service.get_default_action_description(bookmark);
            let action_description = format_action_description(base_description, bookmark.opener.as_ref());

            // Show what we're doing
            eprintln!(
                "Performing '{}' for: {} ({})",
                action_description, bookmark.title, bookmark.url
            );

            // Execute the default action
            action_service.execute_default_action(bookmark)?;
        }
    }
    Ok(())
}

#[instrument(skip(cli))]
pub fn create_db(cli: Cli, services: &ServiceContainer, settings: &Settings) -> CliResult<()> {
    if let Commands::CreateDb { path, pre_fill } = cli.command.unwrap() {
        // Get the database path from either the command-line argument or the config system
        let db_path = match path {
            Some(p) => p,
            None => {
                // Get from config system via settings parameter
                let configured_path = &settings.db_url;

                // Check if we're using default configuration
                if settings.config_source == ConfigSource::Default {
                    eprintln!(
                        "{}",
                        "Warning: Using default database path. No configuration found.".yellow()
                    );
                    eprintln!("Default path: {}", configured_path);
                    eprintln!(
                        "Consider creating a configuration file at ~/.config/bkmr/config.toml"
                    );
                    eprintln!("or setting the BKMR_DB_URL environment variable.");

                    // Ask for confirmation when using default configuration
                    if !confirm("Continue with default database location?") {
                        eprintln!("Database creation cancelled.");
                        return Ok(());
                    }
                }

                configured_path.clone()
            }
        };

        // Check if the database file already exists
        if Path::new(&db_path).exists() {
            return Err(CliError::InvalidInput(format!(
                "Database already exists at: {}. Please choose a different path or delete the existing file.",
                db_path
            )));
        }

        // Create parent directories if they don't exist
        if let Some(parent) = Path::new(&db_path).parent() {
            if !parent.exists() {
                fs::create_dir_all(parent).map_err(|e| {
                    CliError::Io(io::Error::new(
                        io::ErrorKind::Other,
                        format!("Failed to create parent directories: {}", e),
                    ))
                })?;
            }
        }

        eprintln!("Creating new database at: {}", db_path);

        // Create the repository with the new path
        let repository = SqliteBookmarkRepository::from_url(&db_path)?;

        // Get a connection
        let mut conn = repository.get_connection()?;

        // Run migrations to set up the schema
        migration::init_db(&mut conn)?;

        // Clean the bookmark table to ensure we start with an empty database
        repository.empty_bookmark_table()?;

        eprintln!("Database created successfully at: {}", db_path);

        // Pre-fill the database with demo entries if requested
        if pre_fill {
            eprintln!("Pre-filling database with demo entries...");
            let embedder = DummyEmbedding;
            pre_fill_database(&repository, &embedder)?;
            eprintln!("Demo entries added successfully!");
        }
    }
    Ok(())
}

#[instrument(skip(cli))]
pub fn set_embeddable(cli: Cli, services: &ServiceContainer) -> CliResult<()> {
    if let Commands::SetEmbeddable {
        id,
        enable,
        disable,
    } = cli.command.unwrap()
    {
        let bookmark_service = services.bookmark_service.clone();

        // Ensure that exactly one flag is provided
        if enable == disable {
            return Err(CliError::InvalidInput(
                "Exactly one of --enable or --disable must be specified".to_string(),
            ));
        }

        // Set the embeddable flag
        let embeddable = enable;
        match bookmark_service.set_bookmark_embeddable(id, embeddable) {
            Ok(bookmark) => {
                eprintln!(
                    "Bookmark '{}' (ID: {}) is now {} for embedding",
                    bookmark.title,
                    bookmark.id.unwrap_or(0),
                    if embeddable { "enabled" } else { "disabled" }
                );
                Ok(())
            }
            Err(e) => Err(CliError::from(e)),
        }
    } else {
        Err(CliError::Other("Invalid command".to_string()))
    }
}

#[instrument(skip(cli), level = "debug")]
pub fn backfill(cli: Cli, services: &ServiceContainer) -> CliResult<()> {
    if let Commands::Backfill { dry_run, force } = cli.command.unwrap() {
        // Check embedder type using services instead of global state
        if services.embedder.as_any().type_id() == std::any::TypeId::of::<DummyEmbedding>() {
            eprintln!("{}", "Error: Cannot backfill embeddings with DummyEmbedding active. Please use --openai flag.".red());
            return Err(CliError::CommandFailed(
                "DummyEmbedding active - embeddings not available".to_string(),
            ));
        }
        let bookmark_service = services.bookmark_service.clone();

        // Get bookmarks to process based on force flag
        let bookmarks = if force {
            bookmark_service.get_bookmarks_for_forced_backfill()?
        } else {
            bookmark_service.get_bookmarks_without_embeddings()?
        };

        if bookmarks.is_empty() {
            eprintln!("No embeddable bookmarks found that need embeddings (excluding bookmarks with '_imported_' tag)");
            return Ok(());
        }

        eprintln!(
            "Found {} bookmarks to process{}",
            bookmarks.len(),
            if force { " (force mode)" } else { "" }
        );

        if dry_run {
            // Just show the bookmarks that would be processed
            for bookmark in &bookmarks {
                eprintln!(
                    "Would update: {} (ID: {})",
                    bookmark.title,
                    bookmark.id.unwrap_or(0)
                );
            }
        } else {
            // Process each bookmark
            for bookmark in &bookmarks {
                if let Some(id) = bookmark.id {
                    eprintln!("Updating embedding for: {} (ID: {})", bookmark.title, id);
                    match bookmark_service.update_bookmark(bookmark.clone(), force) {
                        Ok(_) => eprintln!("  Successfully updated embedding"),
                        Err(e) => eprintln!("  Failed to update embedding: {}", e),
                    }
                }
            }
            eprintln!(
                "Completed embedding backfill for {} bookmarks",
                bookmarks.len()
            );
        }
    }
    Ok(())
}

#[instrument(skip(cli))]
pub fn load_json(cli: Cli, services: &ServiceContainer) -> CliResult<()> {
    if let Commands::LoadJson { path, dry_run } = cli.command.unwrap() {
        eprintln!("Loading bookmarks from JSON array: {}", path);

        let bookmark_service = services.bookmark_service.clone();

        if dry_run {
            let count = bookmark_service.load_json_bookmarks(&path, true)?;
            eprintln!(
                "Dry run completed - would process {} bookmark entries",
                count
            );
            return Ok(());
        }

        // Process the bookmarks
        let processed_count = bookmark_service.load_json_bookmarks(&path, false)?;
        eprintln!(
            "Successfully processed {} bookmark entries",
            processed_count
        );
    }
    Ok(())
}

#[instrument(skip(cli), level = "debug")]
pub fn load_texts(cli: Cli, services: &ServiceContainer) -> CliResult<()> {
    if let Commands::LoadTexts {
        dry_run,
        force,
        path,
    } = cli.command.unwrap()
    {
        // Check embedder type using services instead of global state
        if services.embedder.as_any().type_id() == std::any::TypeId::of::<DummyEmbedding>() {
            eprintln!(
                "{}",
                "Error: Cannot load texts with DummyEmbedding active. Please use --openai flag."
                    .red()
            );
            return Err(CliError::CommandFailed(
                "DummyEmbedding active - embeddings not available".to_string(),
            ));
        }

        eprintln!("Loading text documents from NDJSON file: {}", path);
        eprintln!("(Expecting one JSON document per line)");

        let bookmark_service = services.bookmark_service.clone();

        if dry_run {
            let count = bookmark_service.load_texts(&path, true, force)?;
            eprintln!("Dry run completed - would process {} text entries", count);
            return Ok(());
        }

        // Process the texts
        let processed_count = bookmark_service.load_texts(&path, false, force)?;
        eprintln!("Successfully processed {} text entries", processed_count);
    }
    Ok(())
}

#[instrument(skip(cli))]
pub fn info(cli: Cli, services: &ServiceContainer, settings: &Settings) -> CliResult<()> {
    if let Commands::Info { show_schema } = cli.command.unwrap() {
        // Use settings parameter and services instead of global state
        let repository = SqliteBookmarkRepository::from_url(&settings.db_url)?;

        // Program version
        println!("Program Version: {}", env!("CARGO_PKG_VERSION"));

        // Configuration section
        println!("\nConfiguration:");

        // Config file status
        if let Some(config_path) = get_config_file_path() {
            let exists = config_path.exists();
            println!(
                "  Config file: {} ({})",
                config_path.display(),
                if exists { "exists" } else { "not found" }
            );
        } else {
            println!("  Config file: (unable to determine path)");
        }

        // Config source
        println!("  Source: {:?}", settings.config_source);

        // Database URL with file size
        let db_info = if let Ok(metadata) = fs::metadata(&settings.db_url) {
            format!("{} ({})", settings.db_url, format_file_size(metadata.len()))
        } else {
            format!("{} (file not found)", settings.db_url)
        };
        println!("  Database: {}", db_info);

        // FZF options - all of them
        println!("  FZF Height: {}", settings.fzf_opts.height);
        println!("  FZF Reverse: {}", settings.fzf_opts.reverse);
        println!("  FZF Show Tags: {}", settings.fzf_opts.show_tags);
        println!("  FZF Hide URL: {}", settings.fzf_opts.no_url);
        println!("  FZF Show Action: {}", settings.fzf_opts.show_action);
        println!("  FZF Show File Info: {}", settings.fzf_opts.show_file_info);

        // Shell options
        println!("  Shell Interactive: {}", settings.shell_opts.interactive);

        // Embedder type using services
        let embedder_type =
            if services.embedder.as_any().type_id() == std::any::TypeId::of::<DummyEmbedding>() {
                "DummyEmbedding (embeddings disabled)"
            } else {
                "OpenAiEmbedding (embeddings enabled)"
            };
        println!("  Embedder: {}", embedder_type);

        // Base paths section
        println!("\n  Base Paths:");
        if settings.base_paths.is_empty() {
            println!("    (none configured)");
        } else {
            for (name, value) in &settings.base_paths {
                let expanded = shellexpand::full(value)
                    .map(|s| s.to_string())
                    .unwrap_or_else(|_| value.clone());
                if expanded != *value {
                    println!("    {}: {} -> {}", name, value, expanded);
                } else {
                    println!("    {}: {}", name, value);
                }
            }
        }

        // Environment overrides section
        println!("\n  Environment Overrides:");
        display_env_var("BKMR_DB_URL", false);
        display_env_var("BKMR_FZF_OPTS", false);
        display_env_var("BKMR_SHELL_INTERACTIVE", false);
        display_env_var("OPENAI_API_KEY", true); // Mask the actual value

        // Database statistics
        let bookmarks = repository.get_all()?;
        let bookmark_count = bookmarks.len();
        let file_imported_count = bookmarks.iter().filter(|b| b.file_path.is_some()).count();

        println!("\nDatabase Statistics:");
        println!("  Total Bookmarks: {}", bookmark_count);
        println!("  File-imported: {}", file_imported_count);

        // Get tag statistics
        let tags = repository.get_all_tags()?;
        println!("  Total Tags: {}", tags.len());
        println!("  Top 5 Tags:");
        for (tag, count) in tags.iter().take(5) {
            println!("    {} ({})", tag.value(), count);
        }

        // Add system tag statistics
        println!("\nSystem Tags:");
        display_system_tag_stats(&repository)?;

        // Show schema if requested
        if show_schema {
            println!("\nDatabase Schema:");
            print_db_schema(&repository);
        }
    }
    Ok(())
}

/// Format file size in human-readable form
fn format_file_size(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if bytes >= GB {
        format!("{:.1} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.1} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} B", bytes)
    }
}

/// Display environment variable status
fn display_env_var(name: &str, mask_value: bool) {
    match std::env::var(name) {
        Ok(value) => {
            if mask_value {
                println!("    {}: configured", name);
            } else {
                println!("    {}: {}", name, value);
            }
        }
        Err(_) => {
            println!("    {}: not set", name);
        }
    }
}

fn display_system_tag_stats(repository: &SqliteBookmarkRepository) -> CliResult<()> {
    // Define known system tags
    let system_tags = [
        (
            "_snip_",
            "Snippet",
            "Code snippets that are copied to clipboard",
        ),
        ("_imported_", "Text", "Imported text documents"),
        ("_shell_", "Shell", "Shell scripts that are executed"),
        (
            "_md_",
            "Markdown",
            "Markdown documents that are rendered as HTML",
        ),
        (
            "_env_",
            "Environment",
            "Environment variables for shell sourcing",
        ),
    ];

    // Get all bookmarks
    let bookmarks = repository.get_all()?;

    // Count usage of each system tag
    for (tag_value, tag_name, description) in &system_tags {
        let count = bookmarks
            .iter()
            .filter(|b| b.tags.iter().any(|t| t.value() == *tag_value))
            .count();

        println!(
            "  {} ({}): {} entries - {}",
            tag_name.cyan(),
            tag_value.yellow(),
            count,
            description
        );
    }

    Ok(())
}

/// Pre-fills the database with a variety of demo entries to showcase bkmr's features
pub fn pre_fill_database(
    repository: &SqliteBookmarkRepository,
    embedder: &dyn crate::domain::embedding::Embedder,
) -> CliResult<()> {
    // Create demo entries
    let demo_entries = vec![
        // Regular URLs
        (
            "https://github.com",
            "GitHub",
            "Platform for version control and collaboration",
            vec!["git", "development", "coding"],
        ),
        (
            "https://rust-lang.org",
            "Rust Programming Language",
            "A language empowering everyone to build reliable and efficient software",
            vec!["rust", "programming", "language"],
        ),
        (
            "https://crates.io",
            "Rust Package Registry",
            "The Rust community's crate registry",
            vec!["rust", "packages", "crates"],
        ),

        // Shell command URLs
        (
            "shell::echo 'Hello, World!'",
            "Hello World Shell Command",
            "Simple shell command that prints 'Hello, World!'",
            vec!["shell", "example", "hello_world"],
        ),
        (
            "shell::ls -la | grep '.rs$'",
            "List Rust Files",
            "Shell command to list all Rust files in the current directory",
            vec!["shell", "rust", "files", "list"],
        ),

        // URL with interpolation (date)
        (
            "https://example.com/report?date={{ current_date | strftime(\"%Y-%m-%d\") }}",
            "Daily Report",
            "Dynamic URL that includes today's date",
            vec!["report", "dynamic", "interpolation", "date"],
        ),
        (
            "https://api.example.com/data?from={{ current_date | subtract_days(7) | strftime(\"%Y-%m-%d\") }}&to={{ current_date | strftime(\"%Y-%m-%d\") }}",
            "Last 7 Days Data",
            "API URL for fetching last 7 days of data",
            vec!["api", "dynamic", "date_range", "interpolation"],
        ),

        // URL with environment variable interpolation
        (
            "https://api.service.com/v1/users?token={{ env('API_TOKEN', 'demo-token') }}",
            "API with Token",
            "Service API that uses an environment variable for authentication",
            vec!["api", "token", "environment", "interpolation"],
        ),

        // Code snippet with language tag
        (
            "println!(\"Hello, {}!\", \"Rust\");\n\nfn main() {\n    println!(\"This is a Rust snippet example\");\n}",
            "Rust Hello World Snippet",
            "Simple Rust code snippet demonstrating println",
            vec!["rust", "snippet", "code", "_snip_"],
        ),
        (
            "function greet(name) {\n    console.log(`Hello, ${name}!`);\n}\n\ngreet('JavaScript');",
            "JavaScript Greeting Function",
            "Simple JavaScript function that greets a person",
            vec!["javascript", "snippet", "function", "_snip_"],
        ),

        // Shell script snippet
        (
            "#!/bin/bash\n\necho \"Current directory:\"\npwd\n\necho \"\\nFiles:\"\nls -la",
            "Directory Info Script",
            "Shell script that shows current directory and lists files",
            vec!["bash", "script", "shell", "_snip_"],
        ),

        // Snippet with interpolation
        (
            "#!/bin/bash\n\n# Today's date: {{ current_date | strftime(\"%Y-%m-%d\") }}\n\necho \"Report for {{ current_date | strftime(\"%B %d, %Y\") }}\"",
            "Date Script with Interpolation",
            "Shell script with embedded date interpolation",
            vec!["bash", "date", "interpolation", "_snip_"],
        ),

        // SQL snippet
        (
            "SELECT *\nFROM users\nWHERE registration_date > '{{ current_date | subtract_days(30) | strftime(\"%Y-%m-%d\") }}'\nORDER BY username ASC;",
            "Recent Users SQL Query",
            "SQL query to find users registered in the last 30 days",
            vec!["sql", "query", "users", "_snip_"],
        ),

        // Markdown document
        (
            "# Meeting Notes: {{ current_date | strftime(\"%B %d, %Y\") }}\n\n## Agenda\n- Review last week's progress\n- Discuss current blockers\n- Plan for next sprint\n\n## Action Items\n- [ ] Document API changes\n- [ ] Complete code review\n- [ ] Deploy to staging",
            "Meeting Notes Template",
            "Template for taking meeting notes with dynamic date",
            vec!["markdown", "meeting", "template", "_imported_"],
        ),

        // URL with shell interpolation
        (
            "https://example.com/user/{{ \"whoami\" | shell }}",
            "User-specific Link",
            "URL that includes the current username via shell command",
            vec!["dynamic", "shell", "interpolation"],
        ),

        // Shell script (with _shell_ tag)
        (
            "#!/bin/bash\n\necho \"Running shell script bookmark...\"\necho \"Current directory: $(pwd)\"\nls -la",
            "Directory Info Shell Script",
            "Shell script that shows current directory and lists files",
            vec!["bash", "script", "shell", "_shell_"],
        ),

        // Shell script with interpolation
        (
            "#!/bin/bash\n\n# Today's date: {{ current_date | strftime(\"%Y-%m-%d\") }}\n\necho \"Report for {{ current_date | strftime(\"%B %d, %Y\") }}\"\necho \"Environment variables:\"\nenv | sort",
            "Environment Report Shell Script",
            "Shell script that reports environment variables and the current date",
            vec!["bash", "environment", "report", "_shell_"],
        ),

        // Markdown document
        (
            "# Markdown Example\n\n## Features\n\n- **Bold text**\n- *Italic text*\n- Lists\n- Links: [Example](https://example.com)\n\n## Code Snippets\n\n```rust\nfn hello() {\n    println!(\"Hello from Markdown!\");\n}\n```\n\n> This is a blockquote.\n\n![Image placeholder](https://via.placeholder.com/150)",
            "Markdown Demo Document",
            "Example of a markdown document with various formatting features",
            vec!["markdown", "example", "documentation", "_md_"],
        ),

        // Markdown with interpolation
        (
            "# Daily Report: {{ current_date | strftime(\"%B %d, %Y\") }}\n\n## Overview\n\nThis is an automatically generated report for {{ current_date | strftime(\"%Y-%m-%d\") }}.\n\n## Tasks\n\n- Review yesterday's progress\n- Plan today's work\n- Schedule meetings\n\n## Notes\n\n> Add your daily notes here.\n\n## Environment\n\n```\nUser: {{ \"whoami\" | shell }}\nHostname: {{ \"hostname\" | shell }}\n```",
            "Daily Report Template",
            "Markdown template for daily reports with date interpolation",
            vec!["markdown", "template", "report", "_md_"],
        ),

        // Environment variables
        (
            "# Environment variables for a dev project\nexport PROJECT_ROOT=\"$HOME/projects/myapp\"\nexport DATABASE_URL=\"postgres://localhost/myapp_dev\"\nexport API_KEY=\"dev_key_{{ current_date | strftime(\"%Y%m%d\") }}\"\n\n# Add the project bin to PATH\nexport PATH=\"$PROJECT_ROOT/bin:$PATH\"\n\necho \"Development environment loaded for MyApp\"",
            "Dev Environment",
            "Environment variables for the development project",
            vec!["postgres", "development", "env", "_env_"],
        ),
    ];

    // Add each entry to the database
    for (url, title, description, tags) in demo_entries {
        let mut tag_set = HashSet::new();
        for tag_str in tags {
            if let Ok(tag) = Tag::new(tag_str) {
                tag_set.insert(tag);
            }
        }

        match Bookmark::new(url, title, description, tag_set, embedder) {
            Ok(mut bookmark) => {
                // Set embeddable flag for regular URLs
                if url.starts_with("http") && !url.contains("{{") {
                    bookmark.set_embeddable(true);
                }

                // Add the bookmark to the repository
                if let Err(e) = repository.add(&mut bookmark) {
                    eprintln!("Failed to add demo bookmark {}: {}", title, e);
                }
            }
            Err(e) => {
                eprintln!("Failed to create demo bookmark {}: {}", title, e);
            }
        }
    }

    Ok(())
}

pub fn import_files(cli: Cli, services: &ServiceContainer) -> CliResult<()> {
    use crate::application::error::ApplicationError;
    use crate::config::{has_base_path, load_settings};
    use crate::exitcode;

    if let Some(Commands::ImportFiles {
        paths,
        update,
        delete_missing,
        dry_run,
        verbose,
        base_path,
    }) = cli.command
    {
        // Validate base path if provided
        if let Some(ref base_path_name) = base_path {
            let settings = load_settings(cli.config.as_deref())
                .map_err(|e| CliError::Other(format!("Failed to load configuration: {}", e)))?;

            if !has_base_path(&settings, base_path_name) {
                eprintln!(
                    "{}",
                    format!(
                        "Error: Base path '{}' not found in configuration",
                        base_path_name
                    )
                    .red()
                );
                eprintln!("Add it to your config.toml under [base_paths]:");
                eprintln!("  [base_paths]");
                eprintln!("  {} = \"$HOME/your/path\"", base_path_name);
                std::process::exit(exitcode::USAGE);
            }
        }

        let service = services.bookmark_service.clone();

        if dry_run {
            println!("{}", "Dry run mode - showing what would be done:".green());
        }

        match service.import_files(
            &paths,
            update,
            delete_missing,
            dry_run,
            verbose,
            base_path.as_deref(),
        ) {
            Ok((added, updated, deleted)) => {
                if dry_run {
                    println!(
                        "Would add: {}, update: {}, delete: {}",
                        added.to_string().green(),
                        updated.to_string().yellow(),
                        deleted.to_string().red()
                    );
                } else {
                    println!(
                        "Added: {}, Updated: {}, Deleted: {}",
                        added.to_string().green(),
                        updated.to_string().yellow(),
                        deleted.to_string().red()
                    );
                }
                Ok(())
            }
            Err(ApplicationError::DuplicateName {
                name,
                existing_id,
                file_path,
            }) => {
                eprintln!(
                    "{}",
                    format!("Error: Duplicate name '{}' found in {}", name, file_path).red()
                );
                eprintln!(
                    "Existing bookmark with same name already exists (ID: {})",
                    existing_id
                );
                eprintln!("Use --update flag to overwrite existing bookmarks with changed content");
                std::process::exit(exitcode::DUP);
            }
            Err(e) => {
                eprintln!("{}", format!("Import failed: {}", e).red());
                std::process::exit(exitcode::USAGE);
            }
        }
    } else {
        Err(CliError::InvalidInput(
            "Expected ImportFiles command".to_string(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::testing::{init_test_env, setup_test_db, EnvGuard};

    #[test]
    fn given_valid_id_string_when_get_ids_then_returns_id_vector() {
        let ids = "1,2,3,4,5".to_string();
        let result = get_ids(ids);
        assert!(result.is_ok());
        let id_list = result.unwrap();
        assert_eq!(id_list, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn given_invalid_id_string_when_get_ids_then_returns_error() {
        let ids = "1,2,three,4,5".to_string();
        let result = get_ids(ids);
        assert!(result.is_err());
    }

    #[test]
    fn given_empty_database_when_pre_fill_then_creates_sample_bookmarks() {
        // Arrange
        let _ = init_test_env();
        let _guard = EnvGuard::new();
        let repository = setup_test_db();

        // Make sure we start with an empty database
        repository
            .empty_bookmark_table()
            .expect("Failed to empty bookmark table");

        // Verify database is initially empty
        let initial_bookmarks = repository.get_all().expect("Failed to get bookmarks");
        assert_eq!(
            initial_bookmarks.len(),
            0,
            "Database should be empty initially"
        );

        // Act - Use DummyEmbedding directly
        let embedder = DummyEmbedding;
        pre_fill_database(&repository, &embedder).expect("Failed to pre-fill database");

        // Assert
        let bookmarks = repository.get_all().expect("Failed to get bookmarks");

        // Verify we have added the expected number of demo entries
        assert!(
            !bookmarks.is_empty(),
            "Database should contain demo entries"
        );

        // Define expected entry types to check for
        let expected_types = vec![
            // Regular URLs
            ("https://github.com", false),
            ("https://rust-lang.org", false),
            // Shell command URLs
            ("shell::", false),
            // URL with interpolation (date)
            ("{{", false),
            // Code snippets
            ("_snip_", true),
            // Imported documents
            ("_imported_", true),
        ];

        // Check that each expected type exists in the database
        for (pattern, is_tag) in expected_types {
            let found = if is_tag {
                // Check for a tag containing the pattern
                bookmarks
                    .iter()
                    .any(|b| b.tags.iter().any(|t| t.value().contains(pattern)))
            } else {
                // Check for a URL containing the pattern
                bookmarks.iter().any(|b| b.url.contains(pattern))
            };

            assert!(
                found,
                "Database should contain an entry with {} '{}'",
                if is_tag { "tag" } else { "URL containing" },
                pattern
            );
        }

        // Check that we have entries with embeddable flag set
        let embeddable_entries = bookmarks.iter().filter(|b| b.embeddable).count();
        assert!(
            embeddable_entries > 0,
            "Database should contain entries with embeddable flag set"
        );

        // Test specific entries for correct data
        let github_entry = bookmarks.iter().find(|b| b.url == "https://github.com");
        assert!(github_entry.is_some(), "GitHub entry should exist");
        if let Some(entry) = github_entry {
            assert_eq!(entry.title, "GitHub");
            assert!(entry.tags.iter().any(|t| t.value() == "git"));
        }

        // Test that snippets are correctly marked
        let snippets = bookmarks
            .iter()
            .filter(|b| b.tags.iter().any(|t| t.value() == "_snip_"))
            .count();
        assert!(snippets > 0, "Database should contain snippet entries");
    }
}

// Temporary helper functions removed - using proper dependency injection