kibana-object-manager 0.3.2

A Git-inspired CLI tool for managing Kibana saved objects in version control
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
//! Manifest migration utilities
//!
//! Provides utilities for migrating from the legacy Bash-based structure
//! to the new Rust-based directory structure.
//!
//! Legacy structure (Bash version):
//! ```text
//! project/
//!   ├── manifest.json                          (saved objects manifest)
//!   └── objects/                               (flat saved object files)
//!       ├── allocation-overview.dashboard.json (format: name.type.json)
//!       ├── data-summary.dashboard.json
//!       └── test-viz.visualization.json
//! ```
//!
//! New structure (Rust v0.1.0+):
//! ```text
//! project/
//!   ├── manifest/
//!   │   └── saved_objects.json  (saved objects manifest)
//!   └── objects/                (hierarchical saved object files)
//!       ├── dashboard/
//!       │   ├── allocation-overview.json
//!       │   └── data-summary.json
//!       └── visualization/
//!           └── test-viz.json
//! ```

use eyre::{Context, Result};
use std::path::{Path, PathBuf};

use crate::client::{Auth, KibanaClient};
use crate::kibana::saved_objects::SavedObjectsManifest;
use crate::kibana::spaces::{SpacesExtractor, SpacesManifest};
use crate::storage::{sanitize_filename, transform_env_file};
use url::Url;

/// Migrate a legacy manifest.json file to the new manifest/ directory structure
///
/// This function:
/// 1. Reads the legacy `manifest.json` file
/// 2. Creates a `manifest/` directory if it doesn't exist
/// 3. Writes the manifest to `manifest/saved_objects.json`
/// 4. Migrates flat object files (`objects/type-id.json`) to hierarchical (`objects/type/id.json`)
/// 5. Optionally backs up or removes the old `manifest.json` file
///
/// # Example
/// ```no_run
/// use kibana_object_manager::migration::migrate_manifest;
///
/// # fn example() -> eyre::Result<()> {
/// // Migrate manifest.json in the current directory
/// migrate_manifest(".", true)?;
/// # Ok(())
/// # }
/// ```
pub fn migrate_manifest(
    project_dir: impl AsRef<Path>,
    backup_old: bool,
) -> Result<MigrationResult> {
    let project_dir = project_dir.as_ref();
    let old_manifest_path = project_dir.join("manifest.json");
    let new_manifest_dir = project_dir.join("manifest");
    let new_manifest_path = new_manifest_dir.join("saved_objects.json");

    // Check if old manifest exists
    if !old_manifest_path.exists() {
        return Ok(MigrationResult::NoLegacyManifest);
    }

    // Check if new manifest already exists
    if new_manifest_path.exists() {
        return Ok(MigrationResult::AlreadyMigrated);
    }

    log::info!(
        "Migrating manifest from {} to {}",
        old_manifest_path.display(),
        new_manifest_path.display()
    );

    // Read the old manifest
    let manifest = SavedObjectsManifest::read(&old_manifest_path).with_context(|| {
        format!(
            "Failed to read legacy manifest: {}",
            old_manifest_path.display()
        )
    })?;

    log::info!("Read legacy manifest with {} objects", manifest.count());

    // Create the manifest directory
    std::fs::create_dir_all(&new_manifest_dir).with_context(|| {
        format!(
            "Failed to create manifest directory: {}",
            new_manifest_dir.display()
        )
    })?;

    // Write the new manifest
    manifest.write(&new_manifest_path).with_context(|| {
        format!(
            "Failed to write new manifest: {}",
            new_manifest_path.display()
        )
    })?;

    log::info!("Wrote new manifest to {}", new_manifest_path.display());

    // Migrate object files from flat to hierarchical structure
    migrate_object_files(project_dir)?;

    // Handle the old manifest file
    if backup_old {
        let backup_path = project_dir.join("manifest.json.backup");
        std::fs::rename(&old_manifest_path, &backup_path).with_context(|| {
            format!("Failed to backup old manifest to {}", backup_path.display())
        })?;
        log::info!("Backed up old manifest to {}", backup_path.display());
        Ok(MigrationResult::MigratedWithBackup(backup_path))
    } else {
        std::fs::remove_file(&old_manifest_path).with_context(|| {
            format!(
                "Failed to remove old manifest: {}",
                old_manifest_path.display()
            )
        })?;
        log::info!("Removed old manifest");
        Ok(MigrationResult::MigratedWithoutBackup)
    }
}

/// Migrate object files from flat structure to hierarchical structure
///
/// Converts:
///   objects/object_name.type.json → objects/type/object_name.json
///   objects/my-dashboard.dashboard.json → objects/dashboard/my-dashboard.json
fn migrate_object_files(project_dir: &Path) -> Result<()> {
    let objects_dir = project_dir.join("objects");

    // If objects directory doesn't exist, nothing to migrate
    if !objects_dir.exists() {
        log::debug!("No objects directory found, skipping object file migration");
        return Ok(());
    }

    let mut migrated_count = 0;
    let mut already_hierarchical = 0;

    // Read all entries in objects directory
    for entry in std::fs::read_dir(&objects_dir).with_context(|| {
        format!(
            "Failed to read objects directory: {}",
            objects_dir.display()
        )
    })? {
        let entry = entry?;
        let path = entry.path();

        // Skip subdirectories (already hierarchical)
        if path.is_dir() {
            already_hierarchical += 1;
            continue;
        }

        // Only process .json files
        if path.extension().and_then(|s| s.to_str()) != Some("json") {
            continue;
        }

        // Extract filename without extension
        let filename = match path.file_stem().and_then(|s| s.to_str()) {
            Some(name) => name,
            None => continue,
        };

        // Parse flat filename: "object_name.type" format
        // Look for the LAST dot to split name and type
        if let Some(dot_pos) = filename.rfind('.') {
            let obj_name = &filename[..dot_pos];
            let obj_type = &filename[dot_pos + 1..];

            // Sanitize object name to ensure no shell-reserved characters (like '*')
            let sanitized_name = sanitize_filename(obj_name);

            // Create hierarchical path: type/object_name.json
            let type_dir = objects_dir.join(obj_type);
            let new_path = type_dir.join(format!("{}.json", sanitized_name));

            // Create type directory if it doesn't exist
            std::fs::create_dir_all(&type_dir)
                .with_context(|| format!("Failed to create directory: {}", type_dir.display()))?;

            // Move file to new location
            std::fs::rename(&path, &new_path).with_context(|| {
                format!(
                    "Failed to move {} to {}",
                    path.display(),
                    new_path.display()
                )
            })?;

            log::debug!(
                "Migrated object file: {} → {}",
                path.display(),
                new_path.display()
            );
            migrated_count += 1;
        } else {
            log::warn!(
                "Skipping file with unexpected name format (expected 'object_name.type.json'): {}",
                path.display()
            );
        }
    }

    if migrated_count > 0 {
        log::info!(
            "Migrated {} object file(s) from flat to hierarchical structure",
            migrated_count
        );
    } else if already_hierarchical > 0 {
        log::info!(
            "Object files already in hierarchical structure ({} subdirectories found)",
            already_hierarchical
        );
    } else {
        log::info!("No object files to migrate");
    }

    Ok(())
}

/// Check if a project directory needs migration
pub fn needs_migration(project_dir: impl AsRef<Path>) -> bool {
    let project_dir = project_dir.as_ref();
    let old_manifest = project_dir.join("manifest.json");
    let new_manifest = project_dir.join("manifest/saved_objects.json");

    old_manifest.exists() && !new_manifest.exists()
}

/// Attempt to load a SavedObjectsManifest from either the new or legacy location
///
/// This function provides backward compatibility by checking:
/// 1. First tries `manifest/saved_objects.json` (new location)
/// 2. Falls back to `manifest.json` (legacy location)
///
/// # Example
/// ```no_run
/// use kibana_object_manager::migration::load_saved_objects_manifest;
///
/// # fn example() -> eyre::Result<()> {
/// let manifest = load_saved_objects_manifest(".")?;
/// println!("Loaded {} objects", manifest.count());
/// # Ok(())
/// # }
/// ```
pub fn load_saved_objects_manifest(project_dir: impl AsRef<Path>) -> Result<SavedObjectsManifest> {
    let project_dir = project_dir.as_ref();
    let new_path = project_dir.join("manifest/saved_objects.json");
    let old_path = project_dir.join("manifest.json");

    if new_path.exists() {
        log::debug!("Loading manifest from new location: {}", new_path.display());
        Ok(SavedObjectsManifest::read(&new_path)?)
    } else if old_path.exists() {
        log::warn!(
            "Loading manifest from legacy location: {}. Consider running 'kibob migrate' to update.",
            old_path.display()
        );
        Ok(SavedObjectsManifest::read(&old_path)?)
    } else {
        eyre::bail!(
            "No saved objects manifest found at {} or {}",
            new_path.display(),
            old_path.display()
        )
    }
}

/// Result of a migration operation
#[derive(Debug, Clone, PartialEq)]
pub enum MigrationResult {
    /// Migration completed successfully with backup of old file
    MigratedWithBackup(PathBuf),
    /// Migration completed successfully without backup
    MigratedWithoutBackup,
    /// No legacy manifest.json file found (nothing to migrate)
    NoLegacyManifest,
    /// Already migrated (manifest/saved_objects.json already exists)
    AlreadyMigrated,
}

impl std::fmt::Display for MigrationResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MigrationResult::MigratedWithBackup(path) => {
                write!(
                    f,
                    "Migration completed. Old manifest backed up to: {}",
                    path.display()
                )
            }
            MigrationResult::MigratedWithoutBackup => {
                write!(f, "Migration completed. Old manifest removed.")
            }
            MigrationResult::NoLegacyManifest => {
                write!(f, "No legacy manifest.json found. Nothing to migrate.")
            }
            MigrationResult::AlreadyMigrated => {
                write!(f, "Already migrated. manifest/saved_objects.json exists.")
            }
        }
    }
}

//
// Unified migration function
//

/// Check if project needs any migration
///
/// Returns true if:
/// - Legacy structure exists: `manifest.json` in root
/// - Old single-space structure exists: `manifest/saved_objects.json` in root manifest/
/// - New multi-space structure doesn't exist: `{space}/manifest/` directory doesn't exist
pub fn needs_migration_unified(project_dir: impl AsRef<Path>) -> bool {
    let project_dir = project_dir.as_ref();
    let legacy_manifest = project_dir.join("manifest.json");
    let old_manifest = project_dir.join("manifest/saved_objects.json");

    // Detect target space from environment (prefer lowercase kibana_space)
    let target_space = std::env::var("kibana_space")
        .or_else(|_| std::env::var("KIBANA_SPACE"))
        .unwrap_or_else(|_| "default".to_string());
    let new_default_manifest_dir = project_dir.join(&target_space).join("manifest");

    // If new structure exists, already migrated
    if new_default_manifest_dir.exists() {
        return false;
    }

    // If legacy or old single-space structure exists, needs migration
    legacy_manifest.exists() || old_manifest.exists()
}

/// Unified migration: Migrate directly from legacy structure to multi-space structure
///
/// This performs a single-step migration from either:
/// - Legacy Bash structure (manifest.json) → Multi-space structure
/// - Old v0.1.0 single-space (manifest/saved_objects.json) → Multi-space structure
///
/// The migration uses the `kibana_space` environment variable (if set) to determine
/// the target space directory. If not set, it defaults to `KIBANA_SPACE` or "default".
/// It also updates the .env file if provided.
pub async fn migrate_to_multispace_unified(
    project_dir: impl AsRef<Path>,
    backup_old: bool,
    env_path: Option<impl AsRef<Path>>,
) -> Result<MigrationResult> {
    let project_dir = project_dir.as_ref();

    if !needs_migration_unified(project_dir) {
        return Ok(MigrationResult::AlreadyMigrated);
    }

    // Detect target space from environment (prefer lowercase kibana_space)
    let target_space = std::env::var("kibana_space")
        .or_else(|_| std::env::var("KIBANA_SPACE"))
        .unwrap_or_else(|_| "default".to_string());

    if target_space != "default" {
        log::info!("Using space '{}' for migration target", target_space);
    }

    log::info!("Migrating project to multi-space structure...");
    log::info!("Target space: '{}'", target_space);

    let legacy_manifest_path = project_dir.join("manifest.json");
    let old_manifest_path = project_dir.join("manifest/saved_objects.json");
    let target_space_dir = project_dir.join(&target_space);
    let new_manifest_dir = target_space_dir.join("manifest");
    let new_manifest_path = new_manifest_dir.join("saved_objects.json");

    // Create target directories
    std::fs::create_dir_all(&new_manifest_dir)?;
    std::fs::create_dir_all(&target_space_dir)?;

    // Update .env file if provided
    if let Some(env_path) = env_path {
        transform_env_file(env_path)?;
    }

    // Attempt to fetch space definition and update root spaces.yml
    let kibana_url = match std::env::var("KIBANA_URL") {
        Ok(url) => Url::parse(&url)?,
        Err(_) => return Err(eyre::eyre!("KIBANA_URL environment variable not set")),
    };

    let auth = if let Ok(api_key) = std::env::var("KIBANA_APIKEY") {
        Auth::Apikey(api_key)
    } else if let (Ok(u), Ok(p)) = (
        std::env::var("KIBANA_USERNAME"),
        std::env::var("KIBANA_PASSWORD"),
    ) {
        Auth::Basic(u, p)
    } else {
        Auth::None
    };

    if let Ok(client) = KibanaClient::builder(kibana_url)
        .auth(auth)
        .max_concurrency(8)
        .build()
    {
        let extractor = SpacesExtractor::all(client);
        if let Ok(space_def) = extractor.fetch_space(&target_space).await {
            let space_file = target_space_dir.join("space.json");
            let json = serde_json::to_string_pretty(&space_def)?;
            std::fs::write(&space_file, json)?;
            log::info!(
                "Fetched and wrote space definition to {}",
                space_file.display()
            );

            // Update root spaces.yml
            let spaces_manifest_path = project_dir.join("spaces.yml");
            let mut spaces_manifest = if spaces_manifest_path.exists() {
                SpacesManifest::read(&spaces_manifest_path)?
            } else {
                SpacesManifest::new()
            };

            let space_name = space_def
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or(&target_space);

            if spaces_manifest.add_space(target_space.clone(), space_name.to_string()) {
                spaces_manifest.write(&spaces_manifest_path)?;
                log::info!("Added space '{}' to root spaces.yml", target_space);
            }
        }
    }

    // Determine source manifest and migrate saved_objects.json
    let backup_path = if legacy_manifest_path.exists() {
        log::info!("Migrating from legacy manifest.json...");

        // Read legacy manifest
        let manifest = SavedObjectsManifest::read(&legacy_manifest_path)?;
        log::info!("Read legacy manifest with {} objects", manifest.count());

        // Write to new location
        manifest.write(&new_manifest_path)?;
        log::info!("Wrote new manifest to {}", new_manifest_path.display());

        // Migrate object files from flat to hierarchical (if needed)
        migrate_legacy_object_files(project_dir)?;

        // Move objects directory to {space}/objects
        let old_objects_dir = project_dir.join("objects");
        let new_objects_dir = target_space_dir.join("objects");
        if old_objects_dir.exists() && !new_objects_dir.exists() {
            std::fs::rename(&old_objects_dir, &new_objects_dir)?;
            log::info!("Moved objects/ → {}/objects/", target_space);
        }

        // Handle old manifest file
        if backup_old {
            let backup = project_dir.join("manifest.json.backup");
            std::fs::rename(&legacy_manifest_path, &backup)?;
            log::info!("Backed up old manifest to {}", backup.display());
            Some(backup)
        } else {
            std::fs::remove_file(&legacy_manifest_path)?;
            log::info!("Removed old manifest");
            None
        }
    } else if old_manifest_path.exists() {
        log::info!("Migrating from v0.1.0 single-space structure...");

        // Move manifest files to {space}/manifest/ subdirectory
        migrate_file_simple(&old_manifest_path, &new_manifest_path)?;

        // Move other manifest files
        let old_manifest_dir = project_dir.join("manifest");
        for file_name in &["workflows.yml", "agents.yml", "tools.yml"] {
            let old_file = old_manifest_dir.join(file_name);
            let new_file = new_manifest_dir.join(file_name);
            if old_file.exists() {
                migrate_file_simple(&old_file, &new_file)?;
            }
        }

        // Move content directories to {space}/
        for dir_name in &["objects", "workflows", "agents", "tools"] {
            let old_dir = project_dir.join(dir_name);
            let new_dir = target_space_dir.join(dir_name);
            if old_dir.exists() && !new_dir.exists() {
                std::fs::rename(&old_dir, &new_dir)?;
                log::info!("Moved {}/ → {}/{}/", dir_name, target_space, dir_name);
            }
        }

        // Clean up old manifest directory if it's empty
        let old_manifest_dir = project_dir.join("manifest");
        if old_manifest_dir.exists()
            && let Ok(entries) = std::fs::read_dir(&old_manifest_dir)
            && entries.count() == 0
        {
            std::fs::remove_dir(&old_manifest_dir)?;
            log::info!("Removed empty manifest/ directory");
        }

        None
    } else {
        return Ok(MigrationResult::NoLegacyManifest);
    };

    log::info!("✓ Migration to multi-space structure complete!");
    log::info!("  New structure: {}/manifest/", target_space);

    if target_space != "default" {
        log::info!(
            "Note: KIBANA_SPACE='{}' is deprecated. You can now safely unset it.",
            target_space
        );
    }

    if let Some(backup) = backup_path {
        Ok(MigrationResult::MigratedWithBackup(backup))
    } else {
        Ok(MigrationResult::MigratedWithoutBackup)
    }
}

/// Helper to migrate legacy flat object files to hierarchical structure
fn migrate_legacy_object_files(project_dir: &Path) -> Result<()> {
    let objects_dir = project_dir.join("objects");

    if !objects_dir.exists() {
        return Ok(());
    }

    let mut migrated_count = 0;

    for entry in std::fs::read_dir(&objects_dir)? {
        let entry = entry?;
        let path = entry.path();

        // Skip subdirectories (already hierarchical)
        if path.is_dir() {
            continue;
        }

        // Only process .json files
        if path.extension().and_then(|s| s.to_str()) != Some("json") {
            continue;
        }

        // Extract filename without extension
        let filename = match path.file_stem().and_then(|s| s.to_str()) {
            Some(name) => name,
            None => continue,
        };

        // Parse flat filename: "object_name.type" format
        if let Some(dot_pos) = filename.rfind('.') {
            let obj_name = &filename[..dot_pos];
            let obj_type = &filename[dot_pos + 1..];

            // Sanitize object name to ensure no shell-reserved characters (like '*')
            let sanitized_name = sanitize_filename(obj_name);

            // Create hierarchical path: type/object_name.json
            let type_dir = objects_dir.join(obj_type);
            let new_path = type_dir.join(format!("{}.json", sanitized_name));

            std::fs::create_dir_all(&type_dir)?;
            std::fs::rename(&path, &new_path)?;

            log::debug!("Migrated: {} → {}", path.display(), new_path.display());
            migrated_count += 1;
        }
    }

    if migrated_count > 0 {
        log::info!(
            "Migrated {} object file(s) to hierarchical structure",
            migrated_count
        );
    }

    Ok(())
}

/// Simple file move helper
fn migrate_file_simple(old_path: &Path, new_path: &Path) -> Result<()> {
    if !old_path.exists() {
        return Ok(());
    }

    if new_path.exists() {
        log::warn!("Skipping {}: target already exists", old_path.display());
        return Ok(());
    }

    if let Some(parent) = new_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    std::fs::rename(old_path, new_path)?;
    log::info!("Moved {} → {}", old_path.display(), new_path.display());

    Ok(())
}

//
// Multi-space migration functions (kept for backward compatibility)
//

/// Check if project needs migration from single-space to multi-space structure
///
/// Returns true if:
/// - Old single-space structure exists: `manifest/saved_objects.json` or `manifest/workflows.yml` (etc.) in root manifest/
/// - New multi-space structure doesn't exist: `manifest/default/` directory doesn't exist
pub fn needs_multispace_migration(project_dir: impl AsRef<Path>) -> bool {
    let project_dir = project_dir.as_ref();
    let old_manifest = project_dir.join("manifest/saved_objects.json");
    let old_workflows = project_dir.join("manifest/workflows.yml");
    let old_agents = project_dir.join("manifest/agents.yml");
    let old_tools = project_dir.join("manifest/tools.yml");

    let new_default_manifest_dir = project_dir.join("manifest/default");

    // If new structure exists, already migrated
    if new_default_manifest_dir.exists() {
        return false;
    }

    // If any old single-space manifest exists, needs migration
    old_manifest.exists() || old_workflows.exists() || old_agents.exists() || old_tools.exists()
}

/// Migrate from single-space structure to multi-space structure
///
/// This migrates the old v0.1.0 single-space structure to the new multi-space structure:
///
/// Old structure:
/// ```text
/// project/
///   ├── manifest/
///   │   ├── saved_objects.json
///   │   ├── workflows.yml
///   │   ├── agents.yml
///   │   ├── tools.yml
///   │   └── spaces.yml
///   ├── objects/           # flat saved objects
///   ├── workflows/         # flat workflows
///   ├── agents/            # flat agents
///   └── tools/             # flat tools
/// ```
///
/// New structure:
/// ```text
/// project/
///   ├── manifest/
///   │   ├── default/
///   │   │   ├── saved_objects.json
///   │   │   ├── workflows.yml
///   │   │   ├── agents.yml
///   │   │   └── tools.yml
///   │   └── spaces.yml
///   ├── default/
///   │   ├── objects/       # moved from root
///   │   ├── workflows/     # moved from root
///   │   ├── agents/        # moved from root
///   │   └── tools/         # moved from root
///   └── spaces/            # space definitions
///       └── default.json
/// ```
pub fn migrate_to_multispace(
    project_dir: impl AsRef<Path>,
    backup_old: bool,
) -> Result<MultispaceMigrationResult> {
    let project_dir = project_dir.as_ref();

    if !needs_multispace_migration(project_dir) {
        return Ok(MultispaceMigrationResult::AlreadyMigrated);
    }

    log::info!("Migrating project to multi-space structure...");

    let mut migrated_items = Vec::new();

    // Create target directories
    let default_manifest_dir = project_dir.join("manifest/default");
    let default_space_dir = project_dir.join("default");

    std::fs::create_dir_all(&default_manifest_dir)?;
    std::fs::create_dir_all(&default_space_dir)?;

    // Migrate saved_objects.json
    migrate_file_to_space(
        project_dir,
        "manifest/saved_objects.json",
        "manifest/default/saved_objects.json",
        backup_old,
        &mut migrated_items,
    )?;

    // Migrate workflows.yml
    migrate_file_to_space(
        project_dir,
        "manifest/workflows.yml",
        "manifest/default/workflows.yml",
        backup_old,
        &mut migrated_items,
    )?;

    // Migrate agents.yml
    migrate_file_to_space(
        project_dir,
        "manifest/agents.yml",
        "manifest/default/agents.yml",
        backup_old,
        &mut migrated_items,
    )?;

    // Migrate tools.yml
    migrate_file_to_space(
        project_dir,
        "manifest/tools.yml",
        "manifest/default/tools.yml",
        backup_old,
        &mut migrated_items,
    )?;

    // Migrate content directories
    migrate_directory_to_space(
        project_dir,
        "objects",
        "default/objects",
        backup_old,
        &mut migrated_items,
    )?;

    migrate_directory_to_space(
        project_dir,
        "workflows",
        "default/workflows",
        backup_old,
        &mut migrated_items,
    )?;

    migrate_directory_to_space(
        project_dir,
        "agents",
        "default/agents",
        backup_old,
        &mut migrated_items,
    )?;

    migrate_directory_to_space(
        project_dir,
        "tools",
        "default/tools",
        backup_old,
        &mut migrated_items,
    )?;

    log::info!(
        "✓ Multi-space migration complete: {} items migrated",
        migrated_items.len()
    );

    Ok(MultispaceMigrationResult::Migrated {
        items: migrated_items,
        backup_created: backup_old,
    })
}

/// Helper function to migrate a single file
fn migrate_file_to_space(
    project_dir: &Path,
    old_path: &str,
    new_path: &str,
    backup: bool,
    migrated_items: &mut Vec<String>,
) -> Result<()> {
    let old = project_dir.join(old_path);
    let new = project_dir.join(new_path);

    if !old.exists() {
        log::debug!("Skipping {}: file doesn't exist", old_path);
        return Ok(());
    }

    if new.exists() {
        log::warn!("Skipping {}: target already exists", new_path);
        return Ok(());
    }

    // Create parent directory
    if let Some(parent) = new.parent() {
        std::fs::create_dir_all(parent)?;
    }

    if backup {
        // Copy then remove
        std::fs::copy(&old, &new)?;
        std::fs::remove_file(&old)?;
        log::info!("Migrated (with backup): {} → {}", old_path, new_path);
    } else {
        // Just move
        std::fs::rename(&old, &new)?;
        log::info!("Migrated: {} → {}", old_path, new_path);
    }

    migrated_items.push(old_path.to_string());
    Ok(())
}

/// Helper function to migrate a directory
fn migrate_directory_to_space(
    project_dir: &Path,
    old_path: &str,
    new_path: &str,
    backup: bool,
    migrated_items: &mut Vec<String>,
) -> Result<()> {
    let old = project_dir.join(old_path);
    let new = project_dir.join(new_path);

    if !old.exists() {
        log::debug!("Skipping {}: directory doesn't exist", old_path);
        return Ok(());
    }

    if new.exists() {
        log::warn!("Skipping {}: target already exists", new_path);
        return Ok(());
    }

    // Create parent directory
    if let Some(parent) = new.parent() {
        std::fs::create_dir_all(parent)?;
    }

    if backup {
        // Copy recursively then remove
        copy_dir_all(&old, &new)?;
        std::fs::remove_dir_all(&old)?;
        log::info!(
            "Migrated directory (with backup): {} → {}",
            old_path,
            new_path
        );
    } else {
        // Just move
        std::fs::rename(&old, &new)?;
        log::info!("Migrated directory: {} → {}", old_path, new_path);
    }

    migrated_items.push(format!("{}/", old_path));
    Ok(())
}

/// Helper to recursively copy a directory
fn copy_dir_all(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir_all(dst)?;

    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let ty = entry.file_type()?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());

        if ty.is_dir() {
            copy_dir_all(&src_path, &dst_path)?;
        } else {
            std::fs::copy(&src_path, &dst_path)?;
        }
    }

    Ok(())
}

/// Result of a multi-space migration operation
#[derive(Debug, Clone, PartialEq)]
pub enum MultispaceMigrationResult {
    /// Migration completed successfully
    Migrated {
        items: Vec<String>,
        backup_created: bool,
    },
    /// Already migrated (manifest/default/ already exists)
    AlreadyMigrated,
}

impl std::fmt::Display for MultispaceMigrationResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MultispaceMigrationResult::Migrated {
                items,
                backup_created,
            } => {
                write!(
                    f,
                    "Multi-space migration completed: {} items migrated{}",
                    items.len(),
                    if *backup_created {
                        " (with backups)"
                    } else {
                        ""
                    }
                )
            }
            MultispaceMigrationResult::AlreadyMigrated => {
                write!(f, "Already using multi-space structure")
            }
        }
    }
}

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

    #[test]
    fn test_needs_migration() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // No manifest files - doesn't need migration
        assert!(!needs_migration(project_dir));

        // Create legacy manifest
        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "test-1")]);
        manifest.write(project_dir.join("manifest.json")).unwrap();

        // Now it needs migration
        assert!(needs_migration(project_dir));

        // Create new manifest directory
        std::fs::create_dir_all(project_dir.join("manifest")).unwrap();
        manifest
            .write(project_dir.join("manifest/saved_objects.json"))
            .unwrap();

        // Already migrated - doesn't need migration
        assert!(!needs_migration(project_dir));
    }

    #[test]
    fn test_migrate_with_backup() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create legacy manifest
        let manifest = SavedObjectsManifest::with_objects(vec![
            SavedObject::new("dashboard", "test-1"),
            SavedObject::new("visualization", "test-2"),
        ]);
        manifest.write(project_dir.join("manifest.json")).unwrap();

        // Migrate with backup
        let result = migrate_manifest(project_dir, true).unwrap();
        match result {
            MigrationResult::MigratedWithBackup(backup_path) => {
                assert!(backup_path.exists());
                assert_eq!(backup_path, project_dir.join("manifest.json.backup"));
            }
            _ => panic!("Expected MigratedWithBackup result"),
        }

        // Verify new manifest exists and has correct content
        let new_manifest =
            SavedObjectsManifest::read(project_dir.join("manifest/saved_objects.json")).unwrap();
        assert_eq!(new_manifest.count(), 2);
        assert!(new_manifest.contains("dashboard", "test-1"));
        assert!(new_manifest.contains("visualization", "test-2"));

        // Verify old manifest doesn't exist
        assert!(!project_dir.join("manifest.json").exists());
    }

    #[test]
    fn test_migrate_without_backup() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create legacy manifest
        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "test-1")]);
        manifest.write(project_dir.join("manifest.json")).unwrap();

        // Migrate without backup
        let result = migrate_manifest(project_dir, false).unwrap();
        assert_eq!(result, MigrationResult::MigratedWithoutBackup);

        // Verify new manifest exists
        assert!(project_dir.join("manifest/saved_objects.json").exists());

        // Verify old manifest and backup don't exist
        assert!(!project_dir.join("manifest.json").exists());
        assert!(!project_dir.join("manifest.json.backup").exists());
    }

    #[test]
    fn test_migrate_no_legacy_manifest() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        let result = migrate_manifest(project_dir, true).unwrap();
        assert_eq!(result, MigrationResult::NoLegacyManifest);
    }

    #[test]
    fn test_migrate_already_migrated() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create both old and new manifests
        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "test-1")]);
        manifest.write(project_dir.join("manifest.json")).unwrap();
        std::fs::create_dir_all(project_dir.join("manifest")).unwrap();
        manifest
            .write(project_dir.join("manifest/saved_objects.json"))
            .unwrap();

        let result = migrate_manifest(project_dir, true).unwrap();
        assert_eq!(result, MigrationResult::AlreadyMigrated);
    }

    #[test]
    fn test_load_saved_objects_manifest_new_location() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create new manifest
        std::fs::create_dir_all(project_dir.join("manifest")).unwrap();
        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "new-1")]);
        manifest
            .write(project_dir.join("manifest/saved_objects.json"))
            .unwrap();

        let loaded = load_saved_objects_manifest(project_dir).unwrap();
        assert_eq!(loaded.count(), 1);
        assert!(loaded.contains("dashboard", "new-1"));
    }

    #[test]
    fn test_load_saved_objects_manifest_legacy_location() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create legacy manifest only
        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "legacy-1")]);
        manifest.write(project_dir.join("manifest.json")).unwrap();

        let loaded = load_saved_objects_manifest(project_dir).unwrap();
        assert_eq!(loaded.count(), 1);
        assert!(loaded.contains("dashboard", "legacy-1"));
    }

    #[test]
    fn test_load_saved_objects_manifest_prefers_new() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create both manifests with different content
        let legacy =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "legacy-1")]);
        legacy.write(project_dir.join("manifest.json")).unwrap();

        std::fs::create_dir_all(project_dir.join("manifest")).unwrap();
        let new = SavedObjectsManifest::with_objects(vec![
            SavedObject::new("dashboard", "new-1"),
            SavedObject::new("visualization", "new-2"),
        ]);
        new.write(project_dir.join("manifest/saved_objects.json"))
            .unwrap();

        // Should load from new location
        let loaded = load_saved_objects_manifest(project_dir).unwrap();
        assert_eq!(loaded.count(), 2);
        assert!(loaded.contains("dashboard", "new-1"));
        assert!(loaded.contains("visualization", "new-2"));
    }

    #[test]
    fn test_load_saved_objects_manifest_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        let result = load_saved_objects_manifest(project_dir);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("No saved objects manifest found")
        );
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_needs_migration_unified() {
        unsafe {
            std::env::set_var("KIBANA_URL", "http://localhost:5601");
        }
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // No manifest files - doesn't need migration
        assert!(!needs_migration_unified(project_dir));

        // Create legacy manifest
        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "test-1")]);
        manifest.write(project_dir.join("manifest.json")).unwrap();

        // Now it needs migration
        assert!(needs_migration_unified(project_dir));

        // Migrate to multi-space structure
        let result = migrate_to_multispace_unified(project_dir, false, None::<&Path>)
            .await
            .unwrap();
        match result {
            MigrationResult::MigratedWithoutBackup => {}
            _ => panic!("Expected MigratedWithoutBackup result"),
        }

        // After migration, shouldn't need migration anymore
        assert!(!needs_migration_unified(project_dir));

        // Verify new structure exists
        assert!(
            project_dir
                .join("default/manifest/saved_objects.json")
                .exists()
        );
        assert!(project_dir.join("default").exists());
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_migrate_unified_from_legacy() {
        unsafe {
            std::env::set_var("KIBANA_URL", "http://localhost:5601");
        }
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create legacy manifest
        let manifest = SavedObjectsManifest::with_objects(vec![
            SavedObject::new("dashboard", "test-1"),
            SavedObject::new("visualization", "test-2"),
        ]);
        manifest.write(project_dir.join("manifest.json")).unwrap();

        // Create legacy objects directory with flat files
        let objects_dir = project_dir.join("objects");
        std::fs::create_dir_all(&objects_dir).unwrap();
        std::fs::write(objects_dir.join("test-1.dashboard.json"), "{}").unwrap();

        // Migrate with backup
        let result = migrate_to_multispace_unified(project_dir, true, None::<&Path>)
            .await
            .unwrap();
        match result {
            MigrationResult::MigratedWithBackup(backup_path) => {
                assert!(backup_path.exists());
                assert_eq!(backup_path, project_dir.join("manifest.json.backup"));
            }
            _ => panic!("Expected MigratedWithBackup result"),
        }

        // Verify new structure
        let new_manifest = project_dir.join("default/manifest/saved_objects.json");
        assert!(new_manifest.exists());

        let loaded = SavedObjectsManifest::read(&new_manifest).unwrap();
        assert_eq!(loaded.count(), 2);

        // Verify objects moved to hierarchical structure
        assert!(project_dir.join("default/objects").exists());
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_migrate_unified_from_v0_1_0() {
        unsafe {
            std::env::set_var("KIBANA_URL", "http://localhost:5601");
        }
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create v0.1.0 structure
        let manifest_dir = project_dir.join("manifest");
        std::fs::create_dir_all(&manifest_dir).unwrap();

        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "test-1")]);
        manifest
            .write(manifest_dir.join("saved_objects.json"))
            .unwrap();

        // Create content directories
        let objects_dir = project_dir.join("objects");
        std::fs::create_dir_all(&objects_dir).unwrap();

        // Migrate (no backup for v0.1.0 → multi-space)
        let result = migrate_to_multispace_unified(project_dir, false, None::<&Path>)
            .await
            .unwrap();
        match result {
            MigrationResult::MigratedWithoutBackup => {}
            _ => panic!("Expected MigratedWithoutBackup result"),
        }

        // Verify new structure
        assert!(
            project_dir
                .join("default/manifest/saved_objects.json")
                .exists()
        );
        assert!(project_dir.join("default/objects").exists());

        // Old manifest should be gone
        assert!(!project_dir.join("manifest/saved_objects.json").exists());
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_migrate_unified_already_migrated() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create new multi-space structure
        let new_manifest_dir = project_dir.join("default/manifest");
        std::fs::create_dir_all(&new_manifest_dir).unwrap();

        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "test-1")]);
        manifest
            .write(new_manifest_dir.join("saved_objects.json"))
            .unwrap();

        // Try to migrate
        let result = migrate_to_multispace_unified(project_dir, false, None::<&Path>)
            .await
            .unwrap();
        match result {
            MigrationResult::AlreadyMigrated => {}
            _ => panic!("Expected AlreadyMigrated result"),
        }
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn test_migrate_space_aware() {
        unsafe {
            std::env::set_var("KIBANA_URL", "http://localhost:5601");
        }
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path();

        // Create legacy manifest
        let manifest =
            SavedObjectsManifest::with_objects(vec![SavedObject::new("dashboard", "test-1")]);
        manifest.write(project_dir.join("manifest.json")).unwrap();

        // Set lowercase env var
        unsafe {
            std::env::set_var("kibana_space", "marketing");
        }

        // Migrate
        let result = migrate_to_multispace_unified(project_dir, false, None::<&Path>)
            .await
            .unwrap();
        assert!(matches!(result, MigrationResult::MigratedWithoutBackup));

        // Verify it used "marketing" directory
        assert!(
            project_dir
                .join("marketing/manifest/saved_objects.json")
                .exists()
        );
        assert!(!project_dir.join("default").exists());

        // Clean up
        unsafe {
            std::env::remove_var("kibana_space");
        }
    }
}