midas_fetcher 0.1.2

High-performance concurrent downloader for UK Met Office MIDAS Open weather data with intelligent caching and resumable downloads
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
//! Command handlers for MIDAS Fetcher CLI
//!
//! This module implements the main command handlers that coordinate between
//! CLI arguments and the core application functionality.

use std::collections::HashMap;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use tracing::{debug, error, info, warn};

use crate::app::{
    collect_datasets_and_years, fill_queue_from_manifest, filter_manifest_files, CacheConfig,
    CacheManager, CedaClient, Coordinator, CoordinatorConfig, ManifestStreamer, Md5Hash, WorkQueue,
};
use crate::auth::{setup_credentials, show_auth_status, verify_credentials};
use crate::cli::{
    interactive_selection, validate_startup, AuthAction, AuthArgs, CacheAction, CacheArgs,
    DownloadArgs, ManifestAction, ManifestArgs, ProgressConfig, ProgressDisplay,
};
use crate::errors::{AppError, Result};

/// Handle the download command
///
/// Orchestrates the complete download process including startup validation,
/// dataset selection, file filtering, and coordinated downloading.
pub async fn handle_download(args: DownloadArgs) -> Result<()> {
    use std::time::Instant;

    let start_time = Instant::now();
    info!("Starting download command with {} workers", args.workers);

    // Validate download arguments
    args.validate().map_err(AppError::generic)?;

    // Perform startup validation
    let validation_start = Instant::now();
    let startup_status = validate_startup(true, true).await?;
    if !startup_status.is_ready() {
        error!("Startup validation failed: {}", startup_status.summary());
        return Err(AppError::generic("System not ready for downloads"));
    }
    info!(
        "Startup validation completed in {:?}",
        validation_start.elapsed()
    );

    // Check authentication status early
    let auth_check_start = Instant::now();
    info!("Checking authentication status...");
    let auth_status = crate::auth::get_auth_status();
    info!("Auth status: {}", auth_status.status_message());
    if !auth_status.has_credentials() {
        warn!("No credentials found - downloads may fail. Run 'midas_fetcher auth setup' first.");
        println!("⚠️  Warning: No CEDA credentials found. Downloads may fail.");
        println!("   Run 'midas_fetcher auth setup' to configure credentials.");
        println!();
    } else {
        info!("Credentials are available for authentication");
    }
    info!(
        "Authentication check completed in {:?}",
        auth_check_start.elapsed()
    );

    // Determine manifest file to use
    let manifest_start = Instant::now();
    let manifest_path = find_manifest_file().await?;
    info!(
        "Using manifest file: {} (found in {:?})",
        manifest_path.display(),
        manifest_start.elapsed()
    );

    // Get quality control version
    let quality_version = args.quality_version();
    info!("Using quality control version: {}", quality_version);

    // Interactive dataset selection with file count
    let selection_start = Instant::now();
    let (selected_dataset, expected_files) = interactive_selection(
        &manifest_path,
        args.dataset.as_deref(),
        args.county.as_deref(),
        &quality_version,
    )
    .await?;
    info!(
        "Dataset selection completed in {:?} - expecting {} files",
        selection_start.elapsed(),
        expected_files
    );

    // Filter files based on criteria with progress feedback
    let filtering_start = Instant::now();
    info!("Filtering files based on selection criteria...");

    // Create progress spinner for filtering
    use indicatif::{ProgressBar, ProgressStyle};
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.green} {msg}")
            .unwrap()
            .tick_strings(&["", "", "", ""]),
    );

    let filter_message = format!("Filtering files for dataset '{}'...", selected_dataset);
    spinner.set_message(filter_message);
    spinner.enable_steady_tick(std::time::Duration::from_millis(120));

    // For dry-run mode, we still need to collect files to show what would be downloaded
    if args.dry_run {
        let files_to_download = filter_manifest_files(
            &manifest_path,
            Some(&selected_dataset),
            args.county.as_deref(),
            &quality_version,
        )
        .await
        .map_err(AppError::Manifest)?;

        let filtering_duration = filtering_start.elapsed();
        spinner.finish_and_clear();
        info!(
            "File filtering completed: {} files in {:?}",
            files_to_download.len(),
            filtering_duration
        );

        if files_to_download.is_empty() {
            warn!("No files match the specified criteria");
            println!("No files found matching your criteria:");
            println!("  Dataset: {}", selected_dataset);
            if let Some(county) = &args.county {
                println!("  County: {}", county);
            }
            println!("  Quality: {}", quality_version);
            return Ok(());
        }

        // Apply limit for dry-run display
        let display_files = if let Some(limit) = args.limit {
            if files_to_download.len() > limit {
                info!(
                    "Would limit download to {} files (from {} total)",
                    limit,
                    files_to_download.len()
                );
                files_to_download.into_iter().take(limit).collect()
            } else {
                files_to_download
            }
        } else {
            files_to_download
        };

        println!("Dry run - would download {} files:", display_files.len());
        for (i, file) in display_files.iter().take(10).enumerate() {
            println!("  {}. {} ({})", i + 1, file.file_name, file.hash);
        }
        if display_files.len() > 10 {
            println!("  ... and {} more files", display_files.len() - 10);
        }
        return Ok(());
    }

    // For actual downloads, use streaming approach
    let filtering_duration = filtering_start.elapsed();
    spinner.finish_and_clear();
    info!(
        "Starting streaming manifest processing in {:?}",
        filtering_duration
    );

    // Setup shared components
    let setup_start = Instant::now();
    info!("Setting up cache, client, and work queue...");

    // Setup early signal handling for long-running queue operations
    let _signal_handle = tokio::spawn(async move {
        if let Err(e) = tokio::signal::ctrl_c().await {
            eprintln!("Failed to setup Ctrl-C handler: {}", e);
            return;
        }
        eprintln!("\n🛑 Ctrl-C received during setup - forcing exit");
        std::process::exit(1);
    });

    let cache_config = CacheConfig {
        cache_root: args.cache_dir(),
        ..Default::default()
    };
    let cache = Arc::new(CacheManager::new(cache_config).await?);

    // The authentication step can take 90+ seconds - this is the bottleneck
    print!("🔐 Authenticating with CEDA...");
    io::stdout().flush().unwrap();
    let client = Arc::new(CedaClient::new().await?);
    println!("");
    let queue = Arc::new(WorkQueue::new());

    // Check for existing queue state
    let initial_stats = queue.stats().await;
    if initial_stats.total_added > 0 || initial_stats.completed_count > 0 {
        println!(
            "📋 Found existing queue state: {} completed, {} in progress",
            initial_stats.completed_count, initial_stats.in_progress_count
        );
        if args.force {
            println!("🔄 Force flag set - clearing previous download state");
            // TODO: Add queue reset method
        }
    }

    // Use pull-based streaming to fill queue directly from manifest
    let queue_fill_start = Instant::now();

    // Start filling queue in background while setting up other components
    let queue_clone = queue.clone();
    let manifest_path_clone = manifest_path.clone();
    let selected_dataset_clone = selected_dataset.clone();
    let county_clone = args.county.clone();
    let quality_version_clone = quality_version.clone();
    let limit_clone = args.limit;

    let queue_fill_task = tokio::spawn(async move {
        fill_queue_from_manifest(
            manifest_path_clone,
            &queue_clone,
            Some(&selected_dataset_clone),
            county_clone.as_deref(),
            &quality_version_clone,
            limit_clone,
        )
        .await
        .map_err(AppError::Manifest)
    });

    let queue_fill_duration = queue_fill_start.elapsed();
    info!("Started queue filling task in {:?}", queue_fill_duration);

    let setup_duration = setup_start.elapsed();
    info!("Component setup completed in {:?}", setup_duration);

    // Apply limit to expected files if specified
    let final_expected_files = if let Some(limit) = args.limit {
        expected_files.min(limit)
    } else {
        expected_files
    };

    // Setup coordinator
    let coordinator_start = Instant::now();
    info!("Setting up coordinator with {} workers...", args.workers);

    let coordinator_config = CoordinatorConfig {
        worker_count: args.workers,
        enable_progress_bar: !args.quiet(),
        verbose_logging: args.verbose(),
        ..Default::default()
    };

    let coordinator = Coordinator::new_with_expected_files(
        coordinator_config,
        queue.clone(),
        cache,
        client,
        final_expected_files,
    );
    info!(
        "Coordinator setup completed in {:?}",
        coordinator_start.elapsed()
    );

    // Setup progress display for streaming (we don't know total count upfront)
    let progress_config = ProgressConfig {
        enable_progress_bars: !args.quiet(),
        show_worker_details: args.verbose(),
        ..Default::default()
    };
    let mut progress_display = ProgressDisplay::new(progress_config);

    // Run downloads with progress display
    let download_start = Instant::now();
    info!(
        "Starting coordinated download process with {} workers...",
        args.workers
    );
    println!("🚀 Starting downloads with {} workers...", args.workers);

    // Add spinner to explain initial delay while system starts up
    let startup_spinner = ProgressBar::new_spinner();
    startup_spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.cyan} {msg}")
            .unwrap()
            .tick_strings(&["", "", "", "", "", "", "", "", "", ""]),
    );
    startup_spinner.set_message("Initializing workers and starting downloads...");
    startup_spinner.enable_steady_tick(std::time::Duration::from_millis(80));

    // Run downloads with real progress updates
    let session_result = {
        // Start the downloads in the background
        let coordinator_task = {
            let coord = coordinator;
            tokio::spawn(async move {
                let mut coord = coord;
                coord.run_downloads().await
            })
        };

        // Start progress display after coordinator is launched to avoid flashing
        progress_display
            .start(final_expected_files, args.workers)
            .await
            .map_err(AppError::Download)?;

        // Clear startup spinner after progress display is ready
        startup_spinner.finish_and_clear();

        // Monitor progress and update display in real-time
        let mut last_completed = 0usize;
        let mut last_failed = 0usize;
        let mut queue_fill_task = Some(queue_fill_task);
        let mut queue_fill_completed = false;
        let mut total_files_added = 0usize;

        // Run monitoring loop directly without timeout wrapper for now
        loop {
            // Check if queue filling is complete
            if !queue_fill_completed {
                if let Some(task) = &queue_fill_task {
                    if task.is_finished() {
                        let task = queue_fill_task.take().unwrap();
                        match task.await {
                            Ok(Ok(added_count)) => {
                                total_files_added = added_count;
                                queue_fill_completed = true;
                                info!("Queue filling completed: {} files added", added_count);

                                if added_count == 0 {
                                    println!("ℹ️  No new files to download - all files already completed or in progress");
                                    break Ok(crate::app::SessionResult {
                                        stats: crate::app::DownloadStats::default(),
                                        success: true,
                                        shutdown_errors: vec![],
                                        total_duration: download_start.elapsed(),
                                    });
                                }
                            }
                            Ok(Err(e)) => {
                                error!("Queue filling failed: {}", e);
                                break Err(e);
                            }
                            Err(e) => {
                                error!("Queue filling task panicked: {}", e);
                                break Err(AppError::generic(format!(
                                    "Queue filling task panicked: {}",
                                    e
                                )));
                            }
                        }
                    }
                }
            }

            // Get current queue statistics
            let queue_stats = queue.stats().await;
            let current_completed = queue_stats.completed_count as usize;
            let current_failed = queue_stats.failed_count as usize;

            // Update progress display if there's been progress
            if current_completed > last_completed || current_failed > last_failed {
                if args.verbose() {
                    if queue_fill_completed {
                        eprintln!(
                            "🔄 Progress update: {}/{} completed, {} failed",
                            current_completed, total_files_added, current_failed
                        );
                    } else {
                        eprintln!(
                            "🔄 Progress update: {} completed, {} failed (queue still filling)",
                            current_completed, current_failed
                        );
                    }
                }
                progress_display
                    .update_with_stats(current_completed, current_failed)
                    .await
                    .map_err(AppError::Download)?;
                last_completed = current_completed;
                last_failed = current_failed;
            }

            // Check if coordinator is done
            if coordinator_task.is_finished() {
                let result = coordinator_task
                    .await
                    .map_err(|e| AppError::generic(format!("Coordinator task panicked: {}", e)))?;

                // If coordinator is done, abort the queue fill task if it's still running
                if let Some(task) = queue_fill_task.take() {
                    task.abort();
                }

                break Ok(result.map_err(AppError::Download)?);
            }

            // Check if work is complete (queue filling done AND no work remaining)
            if queue_fill_completed
                && queue_stats.pending_count == 0
                && queue_stats.in_progress_count == 0
            {
                // Wait a bit and check again
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                continue;
            }

            // Small sleep to avoid excessive polling
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    };
    let download_duration = download_start.elapsed();

    // Finish progress display
    progress_display
        .finish()
        .await
        .map_err(AppError::Download)?;

    // Report results
    let total_duration = start_time.elapsed();
    let session_result = session_result?;
    let stats = &session_result.stats;

    info!(
        "Download session completed in {:?} (total elapsed: {:?})",
        download_duration, total_duration
    );

    println!("\n📊 Verification Summary:");
    println!("  Total files: {}", stats.total_files);

    // Calculate files that were actually downloaded this session vs already complete
    let files_downloaded = if stats.files_completed > 0 && stats.files_failed == 0 {
        // If we have completed files but no failures, we need to determine actual downloads
        // For now, we'll show the completed count as "already complete" since most are cache hits
        0
    } else {
        stats.files_completed
    };
    let files_already_complete = stats.files_completed - files_downloaded;

    if files_already_complete > 0 {
        let percentage = (files_already_complete as f64 / stats.total_files as f64) * 100.0;
        println!(
            "  ✅ Already complete: {} ({:.1}%)",
            files_already_complete, percentage
        );
    }

    if files_downloaded > 0 {
        println!("  📥 Downloaded: {}", files_downloaded);
    }

    if stats.files_failed > 0 {
        println!("  ❌ Failed: {}", stats.files_failed);
    }

    println!("  Time: {:.3}s", total_duration.as_secs_f64());

    if !session_result.success {
        warn!("Download session completed with errors");
        if !session_result.shutdown_errors.is_empty() {
            println!("\nShutdown errors:");
            for error in &session_result.shutdown_errors {
                println!("{}", error);
            }
        }
    }

    Ok(())
}

/// Handle manifest-related commands
pub async fn handle_manifest(args: ManifestArgs) -> Result<()> {
    match args.action {
        ManifestAction::Update { force, verify } => handle_manifest_update(force, verify).await,
        ManifestAction::Info { file } => handle_manifest_info(file).await,
        ManifestAction::List {
            datasets_only,
            dataset,
        } => handle_manifest_list(datasets_only, dataset).await,
        ManifestAction::Check { detailed } => handle_manifest_check(detailed).await,
    }
}

/// Handle manifest update command
async fn handle_manifest_update(force: bool, verify: bool) -> Result<()> {
    use crate::cli::startup::{check_manifest_update_needed, download_manifest_files};

    info!(
        "Updating manifest files (force: {}, verify: {})",
        force, verify
    );

    println!("📋 Manifest Update");
    println!("=================");
    println!();

    // Check if update is needed (unless forced)
    if !force {
        match check_manifest_update_needed().await {
            Ok(status) => {
                println!("Checking for updates...");

                if let Some(version) = status.local_version {
                    println!(
                        "Local version:  v{} ({})",
                        version,
                        status.age_description()
                    );
                }
                println!("Remote version: v{}", status.remote_version);
                println!("Status: {}", status.status_message());
                println!();

                if !status.needs_update {
                    println!("✅ Manifest is already up to date!");
                    return Ok(());
                }
            }
            Err(e) => {
                warn!("Could not check for updates: {}", e);
                println!("⚠️  Could not check current status, proceeding with download...");
            }
        }
    }

    // Create progress spinner for manifest download
    use indicatif::{ProgressBar, ProgressStyle};
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.green} {msg}")
            .unwrap()
            .tick_strings(&["", "", "", ""]),
    );

    let download_message = if force {
        "Force downloading latest manifest..."
    } else {
        "Downloading latest manifest..."
    };
    spinner.set_message(download_message);
    spinner.enable_steady_tick(std::time::Duration::from_millis(120));

    // Download the manifest and generate metadata
    match download_manifest_files().await {
        Ok(()) => {
            spinner.finish_and_clear();
            println!("✅ Manifest updated successfully!");

            if verify {
                println!();
                println!("🔍 Verifying manifest integrity...");
                // TODO: Add verification logic here
                println!("✅ Manifest verification complete");
            }
        }
        Err(e) => {
            spinner.finish_and_clear();
            println!("❌ Failed to download manifest");
            return Err(AppError::generic(format!(
                "Failed to update manifest: {}",
                e
            )));
        }
    }

    Ok(())
}

/// Handle manifest check command
async fn handle_manifest_check(detailed: bool) -> Result<()> {
    use crate::cli::startup::check_manifest_update_needed;

    info!("Checking manifest update status (detailed: {})", detailed);

    println!("📋 Manifest Update Check");
    println!("========================");
    println!();

    match check_manifest_update_needed().await {
        Ok(status) => {
            // Basic information
            match status.local_version {
                Some(version) => {
                    println!(
                        "Local version:  v{} ({})",
                        version,
                        status.age_description()
                    );
                    if detailed {
                        if let Some(filename) = &status.local_filename {
                            println!("Local file:     {}", filename);
                        }
                    }
                }
                None => {
                    println!("Local version:  Not found");
                }
            }

            println!("Remote version: v{}", status.remote_version);
            if detailed {
                println!("Remote file:    {}", status.remote_filename);
            }

            println!();
            println!("Status: {}", status.status_message());

            // Recommendations
            if status.needs_update {
                println!();
                println!("📥 To update: midas_fetcher manifest update");
            } else if let Some(age) = status.local_age_days {
                if age > 7 {
                    println!();
                    println!(
                        "💡 Your manifest is {} days old. Consider updating occasionally to get",
                        age
                    );
                    println!("   the latest datasets and file checksums.");
                }
            }

            // Detailed information
            if detailed {
                println!();
                println!("Detailed Information:");
                println!("--------------------");
                if let Some(age) = status.local_age_days {
                    println!("Local manifest age: {} days", age);
                }
                println!("Update needed: {}", status.needs_update);

                if status.needs_update {
                    let version_diff = status.remote_version - status.local_version.unwrap_or(0);
                    println!("Version difference: {} releases", version_diff);
                }
            }
        }
        Err(e) => {
            return Err(AppError::generic(format!(
                "Failed to check manifest status: {}",
                e
            )));
        }
    }

    Ok(())
}

/// Handle manifest info command
async fn handle_manifest_info(file: Option<PathBuf>) -> Result<()> {
    let manifest_path = if let Some(path) = file {
        path
    } else {
        find_manifest_file().await?
    };

    println!("📋 Manifest Information");
    println!("=======================");

    info!("Analyzing manifest file: {}", manifest_path.display());

    // Add spinner for manifest loading
    use indicatif::{ProgressBar, ProgressStyle};
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.green} {msg}")
            .unwrap()
            .tick_strings(&["", "", "", ""]),
    );
    spinner.set_message("Loading manifest...");
    spinner.enable_steady_tick(std::time::Duration::from_millis(120));

    let load_start = Instant::now();
    let datasets_map = collect_datasets_and_years(&manifest_path)
        .await
        .map_err(AppError::Manifest)?;

    spinner.finish_and_clear();
    println!(
        "Loading manifest... ✅ Analyzed {} entries ({}s)",
        datasets_map.values().map(|d| d.file_count).sum::<usize>(),
        load_start.elapsed().as_secs()
    );
    println!();

    // Display results as a clean table
    display_manifest_table(&datasets_map);

    Ok(())
}

/// Display manifest information as a clean table
fn display_manifest_table(datasets_map: &HashMap<String, crate::app::DatasetSummary>) {
    if datasets_map.is_empty() {
        println!("No datasets found in manifest.");
        return;
    }

    // Calculate column widths
    let name_width = datasets_map
        .keys()
        .map(|name| name.len())
        .max()
        .unwrap_or(12)
        .max(12); // Minimum width for "Dataset Name"

    let counties_width = 9; // Width for "Counties"
    let year_range_width = 10; // Width for "Year Range"
    let files_width = 7; // Width for "Files"

    // Print header
    println!(
        "{:<width$} {:>counties_width$} {:>year_range_width$} {:>files_width$}",
        "Dataset Name",
        "Counties",
        "Year Range",
        "Files",
        width = name_width,
        counties_width = counties_width,
        year_range_width = year_range_width,
        files_width = files_width
    );

    // Print separator line
    println!(
        "{}",
        "".repeat(name_width + counties_width + year_range_width + files_width + 6)
    );

    // Sort datasets by name for consistent output
    let mut sorted_datasets: Vec<_> = datasets_map.iter().collect();
    sorted_datasets.sort_by_key(|(name, _)| *name);

    // Print data rows
    for (name, summary) in sorted_datasets {
        println!(
            "{:<width$} {:>counties_width$} {:>year_range_width$} {:>files_width$}",
            name,
            summary.counties.len(),
            summary.year_range(),
            summary.file_count,
            width = name_width,
            counties_width = counties_width,
            year_range_width = year_range_width,
            files_width = files_width
        );
    }
}

/// Display simple manifest table with dataset name and file count only
fn display_simple_manifest_table(datasets_map: &HashMap<String, crate::app::DatasetSummary>) {
    if datasets_map.is_empty() {
        println!("No datasets found in manifest.");
        return;
    }

    // Calculate column widths
    let name_width = datasets_map
        .keys()
        .map(|name| name.len())
        .max()
        .unwrap_or(12)
        .max(12); // Minimum width for "Dataset Name"

    let files_width = datasets_map
        .values()
        .map(|summary| summary.file_count.to_string().len())
        .max()
        .unwrap_or(5)
        .max(5); // Minimum width for "Files"

    // Print header
    println!(
        "{:<width$} {:>files_width$}",
        "Dataset Name",
        "Files",
        width = name_width,
        files_width = files_width
    );

    // Print separator line
    println!("{}", "".repeat(name_width + files_width + 1));

    // Sort datasets by name for consistent output
    let mut sorted_datasets: Vec<_> = datasets_map.iter().collect();
    sorted_datasets.sort_by_key(|(name, _)| *name);

    // Print data rows
    for (name, summary) in sorted_datasets {
        println!(
            "{:<width$} {:>files_width$}",
            name,
            summary.file_count,
            width = name_width,
            files_width = files_width
        );
    }
}

/// Handle manifest list command
async fn handle_manifest_list(datasets_only: bool, dataset: Option<String>) -> Result<()> {
    let manifest_path = find_manifest_file().await?;

    // Add spinner for manifest loading
    use indicatif::{ProgressBar, ProgressStyle};
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.green} {msg}")
            .unwrap()
            .tick_strings(&["", "", "", ""]),
    );
    spinner.set_message("Preparing list...");
    spinner.enable_steady_tick(std::time::Duration::from_millis(120));

    let datasets_map = collect_datasets_and_years(&manifest_path)
        .await
        .map_err(AppError::Manifest)?;

    spinner.finish_and_clear();

    if datasets_only {
        println!("Available Datasets:");
        for name in datasets_map.keys() {
            println!("  {}", name);
        }
        return Ok(());
    }

    if let Some(dataset_filter) = dataset {
        if let Some(summary) = datasets_map.get(&dataset_filter) {
            println!("📊 Dataset: {}", dataset_filter);
            println!("Available versions:");
            for version in &summary.versions {
                println!("  {}", version);
            }
            if let Some(latest) = summary.latest_version() {
                println!("Latest: {}", latest);
            }
        } else {
            return Err(AppError::generic(format!(
                "Dataset '{}' not found. Available: {}",
                dataset_filter,
                datasets_map.keys().cloned().collect::<Vec<_>>().join(", ")
            )));
        }
        return Ok(());
    }

    // Show simple table with dataset name and file count only
    display_simple_manifest_table(&datasets_map);

    Ok(())
}

/// Handle authentication commands
pub async fn handle_auth(args: AuthArgs) -> Result<()> {
    match args.action {
        AuthAction::Setup { force } => {
            if force || !crate::auth::check_credentials() {
                setup_credentials().await.map_err(AppError::Auth)?;
            } else {
                println!("✅ Credentials already configured. Use --force to update.");
            }
        }
        AuthAction::Verify => {
            let is_valid = verify_credentials().await.map_err(AppError::Auth)?;
            if is_valid {
                println!("✅ Credentials verified successfully");
            } else {
                println!("❌ Credential verification failed");
            }
        }
        AuthAction::Status => {
            show_auth_status().await.map_err(AppError::Auth)?;
        }
        AuthAction::Clear => {
            println!("🗑️  Clearing stored credentials...");
            // TODO: Implement credential clearing
            println!("💡 To clear credentials, delete the .env file manually.");
        }
    }

    Ok(())
}

/// Handle cache management commands
pub async fn handle_cache(args: CacheArgs) -> Result<()> {
    match args.action {
        CacheAction::Verify { dataset } => handle_cache_verify(dataset).await,
        CacheAction::Info => handle_cache_info().await,
        CacheAction::Clean { all, failed_only } => handle_cache_clean(all, failed_only).await,
    }
}

/// Handle cache verification
async fn handle_cache_verify(dataset: Option<String>) -> Result<()> {
    info!("Verifying cache integrity (dataset: {:?})", dataset);

    println!("🔍 Cache Verification");
    println!("====================");
    println!();

    let start_time = Instant::now();

    // Phase 1: Setup cache manager
    let cache_config = CacheConfig::default();
    let cache = CacheManager::new(cache_config).await?;
    let cache_root = cache.cache_root().to_path_buf();

    // Phase 2: Scan cache directory with progress
    print!("🔍 Scanning cache directory...");
    io::stdout().flush().unwrap();

    let scan_start = Instant::now();
    let cached_files = scan_cache_files(&cache_root, dataset.as_deref()).await?;

    println!(
        " ✅ Found {} cached files ({}s)",
        cached_files.len(),
        scan_start.elapsed().as_secs()
    );

    if cached_files.is_empty() {
        println!("ℹ️  No cached files found to verify");
        return Ok(());
    }

    // Phase 3: Load manifest with progress
    use indicatif::{ProgressBar, ProgressStyle};
    let manifest_spinner = ProgressBar::new_spinner();
    manifest_spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.green} {msg}")
            .unwrap()
            .tick_strings(&["", "", "", ""]),
    );
    manifest_spinner.set_message("📋 Loading manifest file...");
    manifest_spinner.enable_steady_tick(std::time::Duration::from_millis(120));

    let manifest_start = Instant::now();
    let manifest_path = find_manifest_file().await?;
    let manifest_hashes = load_manifest_hashes(&manifest_path, dataset.as_deref()).await?;

    manifest_spinner.finish_and_clear();
    println!(
        "📋 Loading manifest file... ✅ Loaded {} manifest entries ({}s)",
        manifest_hashes.len(),
        manifest_start.elapsed().as_secs()
    );

    // Phase 4: Verify files with progress
    println!("✅ Verifying file integrity...");

    let verify_start = Instant::now();
    let results = verify_files_with_progress(&cached_files, &manifest_hashes).await?;

    let verify_duration = verify_start.elapsed();
    let total_duration = start_time.elapsed();

    // Phase 5: Display results
    println!();
    println!("📊 Verification Results");
    println!("======================");
    println!("Files verified: {}", results.total_verified);
    println!("Valid files: {}", results.valid_count);
    println!("Corrupted files: {}", results.corrupted_count);
    println!(
        "Missing from manifest: {}",
        results.missing_from_manifest_count
    );
    println!("Verification time: {}s", verify_duration.as_secs());
    println!("Total time: {}s", total_duration.as_secs());

    // Show corrupted files if any
    if !results.corrupted_files.is_empty() {
        println!();
        println!("⚠️  Corrupted Files:");
        for file_path in &results.corrupted_files {
            println!("  {}", file_path.display());
        }
        println!();
        println!(
            "💡 These files should be re-downloaded. Run the download command to replace them."
        );
    }

    // Show missing files if any
    if !results.missing_from_manifest_files.is_empty() {
        println!();
        println!("❓ Files Not in Manifest:");
        for file_path in &results.missing_from_manifest_files {
            println!("  {}", file_path.display());
        }
        println!();
        println!("💡 These files may be from an older manifest or a different dataset.");
    }

    if results.corrupted_count > 0 || results.missing_from_manifest_count > 0 {
        println!();
        if results.corrupted_count > 0 {
            println!(
                "❌ Cache verification found {} corrupted files",
                results.corrupted_count
            );
        }
        if results.missing_from_manifest_count > 0 {
            println!(
                "⚠️  Found {} files not in current manifest",
                results.missing_from_manifest_count
            );
        }
    } else {
        println!();
        println!("✅ All cached files verified successfully!");
    }

    Ok(())
}

/// Results of cache verification
#[derive(Debug)]
struct VerificationResults {
    total_verified: usize,
    valid_count: usize,
    corrupted_count: usize,
    missing_from_manifest_count: usize,
    corrupted_files: Vec<PathBuf>,
    missing_from_manifest_files: Vec<PathBuf>,
}

/// Scan cache directory for files to verify
async fn scan_cache_files(cache_root: &Path, dataset_filter: Option<&str>) -> Result<Vec<PathBuf>> {
    let mut files = Vec::new();

    // Use the same directory scanning logic as cache info
    scan_directory_recursive_for_verify(cache_root, &mut files, dataset_filter)?;

    Ok(files)
}

/// Recursively scan directory for CSV files
fn scan_directory_recursive_for_verify(
    dir: &Path,
    files: &mut Vec<PathBuf>,
    dataset_filter: Option<&str>,
) -> Result<()> {
    use std::fs;

    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(_) => return Ok(()), // Skip inaccessible directories
    };

    for entry in entries {
        let entry = entry
            .map_err(|e| AppError::generic(format!("Failed to read directory entry: {}", e)))?;
        let path = entry.path();

        if path.is_dir() {
            // Apply dataset filter if specified
            if let Some(filter) = dataset_filter {
                if let Some(dir_name) = path.file_name().and_then(|n| n.to_str()) {
                    if !dir_name.contains(filter) {
                        continue; // Skip directories not matching dataset filter
                    }
                }
            }

            // Recursively scan subdirectories
            scan_directory_recursive_for_verify(&path, files, dataset_filter)?;
        } else if path.extension().and_then(|s| s.to_str()) == Some("csv") {
            files.push(path);
        }
    }

    Ok(())
}

/// Load manifest and build hash lookup map
async fn load_manifest_hashes(
    manifest_path: &Path,
    dataset_filter: Option<&str>,
) -> Result<HashMap<PathBuf, Md5Hash>> {
    use futures::StreamExt;

    let mut manifest_streamer = ManifestStreamer::new();
    let mut manifest_stream = manifest_streamer
        .stream(manifest_path)
        .await
        .map_err(AppError::Manifest)?;

    let mut hash_map = HashMap::new();

    while let Some(file_info_result) = manifest_stream.next().await {
        let file_info = file_info_result.map_err(AppError::Manifest)?;

        // Apply dataset filter if specified
        if let Some(filter) = dataset_filter {
            if !file_info.dataset_info.dataset_name.contains(filter) {
                continue;
            }
        }

        // Build the expected cache path for this file
        let cache_path = build_cache_path_from_file_info(&file_info);
        hash_map.insert(cache_path, file_info.hash);
    }

    Ok(hash_map)
}

/// Build expected cache path from file info
fn build_cache_path_from_file_info(file_info: &crate::app::models::FileInfo) -> PathBuf {
    // This should match the cache path construction logic in the cache manager
    // For now, use the file name as a simple approach
    PathBuf::from(&file_info.file_name)
}

/// Verify files with progress indication
async fn verify_files_with_progress(
    cached_files: &[PathBuf],
    manifest_hashes: &HashMap<PathBuf, Md5Hash>,
) -> Result<VerificationResults> {
    use indicatif::{ProgressBar, ProgressStyle};

    let total_files = cached_files.len();
    let mut results = VerificationResults {
        total_verified: 0,
        valid_count: 0,
        corrupted_count: 0,
        missing_from_manifest_count: 0,
        corrupted_files: Vec::new(),
        missing_from_manifest_files: Vec::new(),
    };

    // Create progress bar
    let progress = ProgressBar::new(total_files as u64);
    progress.set_style(
        ProgressStyle::default_bar()
            .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} (ETA: {eta}) {msg}")
            .unwrap()
            .progress_chars("##-"),
    );
    progress.enable_steady_tick(std::time::Duration::from_millis(100));

    let start_time = Instant::now();

    for (i, file_path) in cached_files.iter().enumerate() {
        // Update progress every 100 files or on last file
        if i % 100 == 0 || i == total_files - 1 {
            progress.set_position(i as u64);

            // Calculate verification rate
            let elapsed = start_time.elapsed().as_secs_f64();
            if elapsed > 0.0 {
                let rate = (i + 1) as f64 / elapsed;
                progress.set_message(format!("{:.1} files/sec", rate));
            } else {
                progress.set_message("Verifying files...");
            }
        }

        results.total_verified += 1;

        // Get the file name for manifest lookup
        let file_name = file_path
            .file_name()
            .and_then(|n| n.to_str())
            .map(PathBuf::from)
            .unwrap_or_else(|| file_path.clone());

        // Check if file exists in manifest
        let expected_hash = match manifest_hashes.get(&file_name) {
            Some(hash) => hash,
            None => {
                results.missing_from_manifest_count += 1;
                results.missing_from_manifest_files.push(file_path.clone());
                continue;
            }
        };

        // Calculate actual file hash
        match calculate_file_md5(file_path).await {
            Ok(actual_hash) => {
                if actual_hash == *expected_hash {
                    results.valid_count += 1;
                } else {
                    results.corrupted_count += 1;
                    results.corrupted_files.push(file_path.clone());
                }
            }
            Err(_) => {
                // File couldn't be read, consider it corrupted
                results.corrupted_count += 1;
                results.corrupted_files.push(file_path.clone());
            }
        }
    }

    progress.finish_with_message("Verification complete");

    Ok(results)
}

/// Calculate MD5 hash of a file
async fn calculate_file_md5(file_path: &Path) -> Result<Md5Hash> {
    use tokio::fs::File;
    use tokio::io::AsyncReadExt;

    let mut file = File::open(file_path).await.map_err(|e| {
        AppError::generic(format!(
            "Failed to open file {}: {}",
            file_path.display(),
            e
        ))
    })?;
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer).await.map_err(|e| {
        AppError::generic(format!(
            "Failed to read file {}: {}",
            file_path.display(),
            e
        ))
    })?;

    let digest = md5::compute(&buffer);
    let hash_bytes: [u8; 16] = digest.0;

    Ok(Md5Hash::from_bytes(hash_bytes))
}

/// Handle cache info display
async fn handle_cache_info() -> Result<()> {
    let cache_config = CacheConfig::default();
    let cache = CacheManager::new(cache_config).await?;

    let stats = cache.get_cache_stats().await;

    println!("💾 Cache Information");
    println!("===================");
    println!("Location: {}", cache.cache_root().display());
    println!("Cached files: {}", stats.cached_files_count);
    println!(
        "Cache size: {:.1} MB",
        stats.total_cache_size as f64 / (1024.0 * 1024.0)
    );

    Ok(())
}

/// Handle cache cleanup
async fn handle_cache_clean(all: bool, failed_only: bool) -> Result<()> {
    println!("🧹 Cache Cleanup");
    println!("===============");

    if all {
        println!("⚠️  This will remove ALL cached files!");
        // TODO: Implement full cache cleanup
    } else if failed_only {
        println!("🗑️  Removing failed/incomplete downloads...");
        // TODO: Implement failed file cleanup
    } else {
        println!("🗑️  Removing temporary and incomplete files...");
        // TODO: Implement selective cleanup
    }

    println!("💡 Cache cleanup functionality coming soon.");

    Ok(())
}

/// Find an available manifest file
async fn find_manifest_file() -> Result<PathBuf> {
    use crate::app::CacheManager;

    // Get cache directory
    let cache = CacheManager::new(Default::default())
        .await
        .map_err(AppError::Cache)?;
    let cache_root = cache.cache_root();

    // First check for legacy manifest file in current directory
    let legacy_path = Path::new("manifest.txt");
    if legacy_path.exists() {
        debug!("Found legacy manifest file: {}", legacy_path.display());
        return Ok(legacy_path.to_path_buf());
    }

    // Check for legacy manifest file in cache directory
    let cache_legacy_path = cache_root.join("manifest.txt");
    if cache_legacy_path.exists() {
        debug!(
            "Found legacy manifest file in cache: {}",
            cache_legacy_path.display()
        );
        return Ok(cache_legacy_path);
    }

    // Look for versioned manifest files in current directory first
    if let Ok(entries) = std::fs::read_dir(".") {
        let mut versioned_manifests: Vec<(u32, PathBuf)> = Vec::new();

        for entry in entries.flatten() {
            if let Some(filename) = entry.file_name().to_str() {
                if filename.starts_with("midas-open-v") && filename.ends_with("-md5s.txt") {
                    // Parse version from filename
                    if let Some(start) = filename.find("midas-open-v") {
                        let version_start = start + "midas-open-v".len();
                        if let Some(end) = filename[version_start..].find("-md5s.txt") {
                            let version_str = &filename[version_start..version_start + end];
                            if let Ok(version) = version_str.parse::<u32>() {
                                versioned_manifests.push((version, entry.path()));
                            }
                        }
                    }
                }
            }
        }

        if !versioned_manifests.is_empty() {
            // Sort by version and return the latest
            versioned_manifests.sort_by_key(|&(version, _)| version);
            let (_, latest_path) = versioned_manifests.into_iter().last().unwrap();
            debug!("Found latest manifest file: {}", latest_path.display());
            return Ok(latest_path);
        }
    }

    // Look for versioned manifest files in cache directory
    if let Ok(entries) = std::fs::read_dir(cache_root) {
        let mut versioned_manifests: Vec<(u32, PathBuf)> = Vec::new();

        for entry in entries.flatten() {
            if let Some(filename) = entry.file_name().to_str() {
                if filename.starts_with("midas-open-v") && filename.ends_with("-md5s.txt") {
                    // Parse version from filename
                    if let Some(start) = filename.find("midas-open-v") {
                        let version_start = start + "midas-open-v".len();
                        if let Some(end) = filename[version_start..].find("-md5s.txt") {
                            let version_str = &filename[version_start..version_start + end];
                            if let Ok(version) = version_str.parse::<u32>() {
                                versioned_manifests.push((version, entry.path()));
                            }
                        }
                    }
                }
            }
        }

        if !versioned_manifests.is_empty() {
            // Sort by version and return the latest
            versioned_manifests.sort_by_key(|&(version, _)| version);
            let (_, latest_path) = versioned_manifests.into_iter().last().unwrap();
            debug!(
                "Found latest manifest file in cache: {}",
                latest_path.display()
            );
            return Ok(latest_path);
        }
    }

    Err(AppError::generic(
        "No manifest file found. Run 'midas_fetcher manifest update' to download one.",
    ))
}

// Helper trait to add missing methods to DownloadArgs
trait DownloadArgsExt {
    fn cache_dir(&self) -> Option<PathBuf>;
    fn quiet(&self) -> bool;
    fn verbose(&self) -> bool;
}

impl DownloadArgsExt for DownloadArgs {
    fn cache_dir(&self) -> Option<PathBuf> {
        // For now, use default cache directory
        // This would normally come from global args
        None
    }

    fn quiet(&self) -> bool {
        // For now, return false
        // This would normally come from global args
        false
    }

    fn verbose(&self) -> bool {
        self.verbose
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_find_manifest_file_not_found() {
        // In an empty directory with no cache files, should return error
        let temp_dir = TempDir::new().unwrap();
        let original_dir = std::env::current_dir().unwrap();

        std::env::set_current_dir(temp_dir.path()).unwrap();

        // Set a temporary cache directory that doesn't exist
        let temp_cache_dir = temp_dir.path().join("empty_cache");
        unsafe {
            std::env::set_var("XDG_CACHE_HOME", temp_cache_dir.parent().unwrap());
        }

        let result = find_manifest_file().await;

        // Clean up environment variable
        unsafe {
            std::env::remove_var("XDG_CACHE_HOME");
        }

        // Note: This might not fail if the cache manager creates default directories
        // In a real scenario, the user would see a helpful error message
        if result.is_ok() {
            // If cache directory was created automatically, that's also valid behavior
            eprintln!("Note: Cache directory was auto-created, which is valid behavior");
        }

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();
    }

    #[tokio::test]
    async fn test_find_manifest_file_found() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("manifest.txt");

        // Create a dummy manifest file
        std::fs::write(&manifest_path, "dummy content").unwrap();

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp_dir.path()).unwrap();

        let result = find_manifest_file().await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().file_name().unwrap(), "manifest.txt");

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();
    }
}