agpm-cli 0.4.14

AGent Package Manager - A Git-based package manager for coding agents
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
//! Path computation and resolution for dependency installation.
//!
//! This module provides utilities for computing installation paths, resolving
//! pattern paths, determining flatten behavior, and handling all path-related
//! operations for resource dependencies. It supports both merge-target resources
//! (Hooks, MCP servers) and regular file-based resources (Agents, Commands,
//! Snippets, Scripts).

use crate::core::ResourceType;
use crate::manifest::{Manifest, ResourceDependency};
use crate::utils::{compute_relative_install_path, normalize_path_for_storage};
use anyhow::Result;
use std::path::{Path, PathBuf};

/// Parses a pattern string to extract the base path and pattern components.
///
/// Handles three cases:
/// 1. Patterns with path separators and absolute/relative parents
/// 2. Patterns with path separators but simple relative paths
/// 3. Simple patterns without path separators
///
/// # Arguments
///
/// * `pattern` - The glob pattern string (e.g., "agents/*.md", "../foo/*.md")
///
/// # Returns
///
/// A tuple of (base_path, pattern_str) where:
/// - `base_path` is the directory to search in
/// - `pattern_str` is the glob pattern to match files against
///
/// # Examples
///
/// ```
/// use std::path::{Path, PathBuf};
/// use agpm_cli::resolver::path_resolver::parse_pattern_base_path;
///
/// let (base, pattern) = parse_pattern_base_path("agents/*.md");
/// assert_eq!(base, PathBuf::from("."));
/// assert_eq!(pattern, "agents/*.md");
///
/// let (base, pattern) = parse_pattern_base_path("../foo/bar/*.md");
/// assert_eq!(base, PathBuf::from("../foo/bar"));
/// assert_eq!(pattern, "*.md");
/// ```
pub fn parse_pattern_base_path(pattern: &str) -> (PathBuf, String) {
    if pattern.contains('/') || pattern.contains('\\') {
        // Pattern contains path separators, extract base path
        let pattern_path = Path::new(pattern);
        if let Some(parent) = pattern_path.parent() {
            if parent.is_absolute() || parent.starts_with("..") || parent.starts_with(".") {
                // Use the parent as base path and just the filename pattern
                (
                    parent.to_path_buf(),
                    pattern_path
                        .file_name()
                        .and_then(|s| s.to_str())
                        .unwrap_or(pattern)
                        .to_string(),
                )
            } else {
                // Relative path, use current directory as base
                (PathBuf::from("."), pattern.to_string())
            }
        } else {
            // No parent, use current directory
            (PathBuf::from("."), pattern.to_string())
        }
    } else {
        // Simple pattern without path separators
        (PathBuf::from("."), pattern.to_string())
    }
}

/// Computes the installation path for a merge-target resource (Hook or McpServer).
///
/// These resources are not installed as files but are merged into configuration files.
/// The installation path is determined by the tool's merge target configuration or
/// hardcoded defaults.
///
/// # Arguments
///
/// * `manifest` - The project manifest containing tool configurations
/// * `artifact_type` - The tool name (e.g., "claude-code", "opencode")
/// * `resource_type` - The resource type (Hook or McpServer)
///
/// # Returns
///
/// The normalized path to the merge target configuration file.
///
/// # Examples
///
/// ```no_run
/// use agpm_cli::core::ResourceType;
/// use agpm_cli::manifest::Manifest;
/// use agpm_cli::resolver::path_resolver::compute_merge_target_install_path;
///
/// let manifest = Manifest::new();
/// let path = compute_merge_target_install_path(&manifest, "claude-code", ResourceType::Hook);
/// assert_eq!(path, ".claude/settings.local.json");
/// ```
pub fn compute_merge_target_install_path(
    manifest: &Manifest,
    artifact_type: &str,
    resource_type: ResourceType,
) -> String {
    // Use configured merge target, with fallback to hardcoded defaults
    if let Some(merge_target) = manifest.get_merge_target(artifact_type, resource_type) {
        normalize_path_for_storage(merge_target.display().to_string())
    } else {
        // Fallback to hardcoded defaults if not configured
        match resource_type {
            ResourceType::Hook => ".claude/settings.local.json".to_string(),
            ResourceType::McpServer => {
                if artifact_type == "opencode" {
                    ".opencode/opencode.json".to_string()
                } else {
                    ".mcp.json".to_string()
                }
            }
            _ => unreachable!(
                "compute_merge_target_install_path should only be called for Hook or McpServer"
            ),
        }
    }
}

/// Computes the installation path for a regular resource (Agent, Command, Snippet, Script).
///
/// Regular resources are installed as files in tool-specific directories. This function
/// determines the final installation path by:
/// 1. Getting the base artifact path from tool configuration
/// 2. Applying any custom target override from the dependency
/// 3. Computing the relative path based on flatten behavior
/// 4. Avoiding redundant directory prefixes
///
/// # Arguments
///
/// * `manifest` - The project manifest containing tool configurations
/// * `dep` - The resource dependency specification
/// * `artifact_type` - The tool name (e.g., "claude-code", "opencode")
/// * `resource_type` - The resource type (Agent, Command, etc.)
/// * `filename` - The meaningful path structure extracted from the source file
///
/// # Returns
///
/// The normalized installation path, or an error if the resource type is not supported
/// by the specified tool.
///
/// # Errors
///
/// Returns an error if:
/// - The resource type is not supported by the specified tool
///
/// # Examples
///
/// ```no_run
/// use agpm_cli::core::ResourceType;
/// use agpm_cli::manifest::Manifest;
/// use agpm_cli::resolver::path_resolver::compute_regular_resource_install_path;
///
/// # fn example() -> anyhow::Result<()> {
/// let manifest = Manifest::new();
/// # let dep: agpm_cli::manifest::ResourceDependency = todo!();
/// let path = compute_regular_resource_install_path(
///     &manifest,
///     &dep,
///     "claude-code",
///     ResourceType::Agent,
///     "agents/helper.md"
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn compute_regular_resource_install_path(
    manifest: &Manifest,
    dep: &ResourceDependency,
    artifact_type: &str,
    resource_type: ResourceType,
    filename: &str,
) -> Result<String> {
    // Get the artifact path for this resource type
    let artifact_path =
        manifest.get_artifact_resource_path(artifact_type, resource_type).ok_or_else(|| {
            anyhow::anyhow!(
                "Resource type '{}' is not supported by tool '{}'",
                resource_type,
                artifact_type
            )
        })?;

    // Determine flatten behavior: use explicit setting or tool config default
    let flatten = get_flatten_behavior(manifest, dep, artifact_type, resource_type);

    // Determine the base target directory
    let base_target = if let Some(custom_target) = dep.get_target() {
        // Custom target is relative to the artifact's resource directory
        // Strip leading path separators (both Unix and Windows) to ensure relative path
        PathBuf::from(artifact_path.display().to_string())
            .join(custom_target.trim_start_matches(['/', '\\']))
    } else {
        artifact_path.to_path_buf()
    };

    // Use compute_relative_install_path to avoid redundant prefixes
    let relative_path = compute_relative_install_path(&base_target, Path::new(filename), flatten);
    // Convert directly to Unix format for lockfile storage (forward slashes only)
    Ok(normalize_path_for_storage(base_target.join(relative_path)))
}

/// Determines the flatten behavior for a resource installation.
///
/// Flatten behavior controls whether directory structure from the source repository
/// is preserved in the installation path. The decision is made by checking:
/// 1. Explicit `flatten` setting on the dependency (highest priority)
/// 2. Tool configuration default for this resource type
/// 3. Global default (false)
///
/// # Arguments
///
/// * `manifest` - The project manifest containing tool configurations
/// * `dep` - The resource dependency specification
/// * `artifact_type` - The tool name (e.g., "claude-code", "opencode")
/// * `resource_type` - The resource type (Agent, Command, etc.)
///
/// # Returns
///
/// `true` if directory structure should be flattened, `false` if it should be preserved.
///
/// # Examples
///
/// ```no_run
/// use agpm_cli::core::ResourceType;
/// use agpm_cli::manifest::Manifest;
/// use agpm_cli::resolver::path_resolver::get_flatten_behavior;
///
/// let manifest = Manifest::new();
/// # let dep: agpm_cli::manifest::ResourceDependency = todo!();
/// let flatten = get_flatten_behavior(&manifest, &dep, "claude-code", ResourceType::Agent);
/// ```
pub fn get_flatten_behavior(
    manifest: &Manifest,
    dep: &ResourceDependency,
    artifact_type: &str,
    resource_type: ResourceType,
) -> bool {
    let dep_flatten = dep.get_flatten();
    let tool_flatten = manifest
        .get_tool_config(artifact_type)
        .and_then(|config| config.resources.get(resource_type.to_plural()))
        .and_then(|resource_config| resource_config.flatten);

    dep_flatten.or(tool_flatten).unwrap_or(false) // Default to false if not configured
}

/// Constructs the full relative path for a matched pattern file.
///
/// Combines the base path with the matched file path, normalizing path separators
/// for storage in the lockfile.
///
/// # Arguments
///
/// * `base_path` - The base directory the pattern was resolved in
/// * `matched_path` - The path to the matched file (relative to base_path)
///
/// # Returns
///
/// A normalized path string suitable for storage in the lockfile.
///
/// # Examples
///
/// ```
/// use std::path::{Path, PathBuf};
/// use agpm_cli::resolver::path_resolver::construct_full_relative_path;
///
/// let base = PathBuf::from(".");
/// let matched = Path::new("agents/helper.md");
/// let path = construct_full_relative_path(&base, matched);
/// assert_eq!(path, "agents/helper.md");
///
/// let base = PathBuf::from("../foo");
/// let matched = Path::new("bar.md");
/// let path = construct_full_relative_path(&base, matched);
/// assert_eq!(path, "../foo/bar.md");
/// ```
pub fn construct_full_relative_path(base_path: &Path, matched_path: &Path) -> String {
    if base_path == Path::new(".") {
        crate::utils::normalize_path_for_storage(matched_path.to_string_lossy().to_string())
    } else {
        crate::utils::normalize_path_for_storage(format!(
            "{}/{}",
            base_path.display(),
            matched_path.display()
        ))
    }
}

/// Extracts the meaningful path for pattern matching.
///
/// Constructs the full path from base path and matched path, then extracts
/// the meaningful structure by removing redundant directory prefixes.
///
/// # Arguments
///
/// * `base_path` - The base directory the pattern was resolved in
/// * `matched_path` - The path to the matched file (relative to base_path)
///
/// # Returns
///
/// The meaningful path structure string.
///
/// # Examples
///
/// ```
/// use std::path::{Path, PathBuf};
/// use agpm_cli::resolver::path_resolver::extract_pattern_filename;
///
/// let base = PathBuf::from(".");
/// let matched = Path::new("agents/helper.md");
/// let filename = extract_pattern_filename(&base, matched);
/// assert_eq!(filename, "agents/helper.md");
/// ```
pub fn extract_pattern_filename(base_path: &Path, matched_path: &Path) -> String {
    let full_path = if base_path == Path::new(".") {
        matched_path.to_path_buf()
    } else {
        base_path.join(matched_path)
    };
    extract_meaningful_path(&full_path)
}

/// Extracts the meaningful path by removing redundant directory prefixes.
///
/// This prevents paths like `.claude/agents/agents/file.md` by eliminating
/// duplicate directory components.
///
/// # Arguments
///
/// * `path` - The path to extract meaningful structure from
///
/// # Returns
///
/// The normalized meaningful path string
pub fn extract_meaningful_path(path: &Path) -> String {
    let components: Vec<_> = path.components().collect();

    if path.is_absolute() {
        // Case 2: Absolute path - resolve ".." components first, then strip root
        let mut resolved = Vec::new();

        for component in components.iter() {
            match component {
                std::path::Component::Normal(name) => {
                    resolved.push(name.to_str().unwrap_or(""));
                }
                std::path::Component::ParentDir => {
                    // Pop the last component if there is one
                    resolved.pop();
                }
                // Skip RootDir, Prefix, and CurDir
                _ => {}
            }
        }

        resolved.join("/")
    } else if components.iter().any(|c| matches!(c, std::path::Component::ParentDir)) {
        // Case 1: Relative path with "../" - skip all parent components
        let start_idx = components
            .iter()
            .position(|c| matches!(c, std::path::Component::Normal(_)))
            .unwrap_or(0);

        components[start_idx..]
            .iter()
            .filter_map(|c| c.as_os_str().to_str())
            .collect::<Vec<_>>()
            .join("/")
    } else {
        // Case 3: Clean relative path - use as-is
        path.to_str().unwrap_or("").replace('\\', "/") // Normalize to forward slashes
    }
}

/// Checks if a path is a file-relative path (starts with "./" or "../").
///
/// # Arguments
///
/// * `path` - The path to check
///
/// # Returns
///
/// `true` if the path is file-relative, `false` otherwise
pub fn is_file_relative_path(path: &str) -> bool {
    path.starts_with("./") || path.starts_with("../")
}

/// Normalizes a bare filename by removing directory components.
///
/// # Arguments
///
/// * `path` - The path to normalize
///
/// # Returns
///
/// The normalized filename
pub fn normalize_bare_filename(path: &str) -> String {
    let path_buf = Path::new(path);
    path_buf.file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string()
}

// ============================================================================
// Installation Path Resolution
// ============================================================================

/// Resolves the installation path for any resource type.
///
/// This is the main entry point for computing where a resource will be installed.
/// It handles both merge-target resources (Hooks, MCP servers) and regular resources
/// (Agents, Commands, Snippets, Scripts).
///
/// # Arguments
///
/// * `manifest` - The project manifest containing tool configurations
/// * `dep` - The resource dependency specification
/// * `artifact_type` - The tool name (e.g., "claude-code", "opencode")
/// * `resource_type` - The resource type
/// * `source_filename` - The filename/path from the source repository
///
/// # Returns
///
/// The normalized installation path, or an error if the resource type is not supported
/// by the specified tool.
///
/// # Errors
///
/// Returns an error if:
/// - The resource type is not supported by the specified tool
///
/// # Examples
///
/// ```no_run
/// use agpm_cli::core::ResourceType;
/// use agpm_cli::manifest::Manifest;
/// use agpm_cli::resolver::path_resolver::resolve_install_path;
///
/// # fn example() -> anyhow::Result<()> {
/// let manifest = Manifest::new();
/// # let dep: agpm_cli::manifest::ResourceDependency = todo!();
/// let path = resolve_install_path(
///     &manifest,
///     &dep,
///     "claude-code",
///     ResourceType::Agent,
///     "agents/helper.md"
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn resolve_install_path(
    manifest: &Manifest,
    dep: &ResourceDependency,
    artifact_type: &str,
    resource_type: ResourceType,
    source_filename: &str,
) -> Result<String> {
    match resource_type {
        ResourceType::Hook | ResourceType::McpServer => {
            Ok(resolve_merge_target_path(manifest, artifact_type, resource_type))
        }
        _ => resolve_regular_resource_path(
            manifest,
            dep,
            artifact_type,
            resource_type,
            source_filename,
        ),
    }
}

/// Resolves the installation path for merge-target resources (Hook, McpServer).
///
/// These resources are not installed as files but are merged into configuration files.
/// Uses configured merge targets or falls back to hardcoded defaults.
///
/// # Arguments
///
/// * `manifest` - The project manifest containing tool configurations
/// * `artifact_type` - The tool name (e.g., "claude-code", "opencode")
/// * `resource_type` - Must be Hook or McpServer
///
/// # Returns
///
/// The normalized path to the merge target configuration file.
pub fn resolve_merge_target_path(
    manifest: &Manifest,
    artifact_type: &str,
    resource_type: ResourceType,
) -> String {
    if let Some(merge_target) = manifest.get_merge_target(artifact_type, resource_type) {
        normalize_path_for_storage(merge_target.display().to_string())
    } else {
        // Fallback to hardcoded defaults if not configured
        match resource_type {
            ResourceType::Hook => ".claude/settings.local.json".to_string(),
            ResourceType::McpServer => {
                if artifact_type == "opencode" {
                    ".opencode/opencode.json".to_string()
                } else {
                    ".mcp.json".to_string()
                }
            }
            _ => unreachable!(
                "resolve_merge_target_path should only be called for Hook or McpServer"
            ),
        }
    }
}

/// Resolves the installation path for regular file-based resources.
///
/// Handles agents, commands, snippets, and scripts by:
/// 1. Getting the base artifact path from tool configuration
/// 2. Applying custom target overrides if specified
/// 3. Computing the relative path based on flatten behavior
/// 4. Avoiding redundant directory prefixes
///
/// # Arguments
///
/// * `manifest` - The project manifest containing tool configurations
/// * `dep` - The resource dependency specification
/// * `artifact_type` - The tool name (e.g., "claude-code", "opencode")
/// * `resource_type` - The resource type (Agent, Command, Snippet, Script)
/// * `source_filename` - The filename/path from the source repository
///
/// # Returns
///
/// The normalized installation path, or an error if the resource type is not supported.
///
/// # Errors
///
/// Returns an error if the resource type is not supported by the specified tool.
pub fn resolve_regular_resource_path(
    manifest: &Manifest,
    dep: &ResourceDependency,
    artifact_type: &str,
    resource_type: ResourceType,
    source_filename: &str,
) -> Result<String> {
    // Get the artifact path for this resource type
    let artifact_path =
        manifest.get_artifact_resource_path(artifact_type, resource_type).ok_or_else(|| {
            create_unsupported_resource_error(artifact_type, resource_type, dep.get_path())
        })?;

    // Compute the final path
    let path = if let Some(custom_target) = dep.get_target() {
        compute_custom_target_path(
            &artifact_path,
            custom_target,
            source_filename,
            dep,
            manifest,
            artifact_type,
            resource_type,
        )
    } else {
        compute_default_path(
            &artifact_path,
            source_filename,
            dep,
            manifest,
            artifact_type,
            resource_type,
        )
    };

    // Convert directly to Unix format for lockfile storage (forward slashes only)
    Ok(normalize_path_for_storage(path))
}

/// Computes the installation path when a custom target directory is specified.
///
/// Custom targets are relative to the artifact's resource directory. The function
/// uses the original artifact path (not the custom target) for prefix stripping
/// to avoid duplicate directories.
fn compute_custom_target_path(
    artifact_path: &Path,
    custom_target: &str,
    source_filename: &str,
    dep: &ResourceDependency,
    manifest: &Manifest,
    artifact_type: &str,
    resource_type: ResourceType,
) -> PathBuf {
    let flatten = get_flatten_behavior(manifest, dep, artifact_type, resource_type);
    // Strip leading path separators (both Unix and Windows) to ensure relative path
    let base_target = PathBuf::from(artifact_path.display().to_string())
        .join(custom_target.trim_start_matches(['/', '\\']));
    // For custom targets, still strip prefix based on the original artifact path
    let relative_path =
        compute_relative_install_path(artifact_path, Path::new(source_filename), flatten);
    base_target.join(relative_path)
}

/// Computes the installation path using the default artifact path.
fn compute_default_path(
    artifact_path: &Path,
    source_filename: &str,
    dep: &ResourceDependency,
    manifest: &Manifest,
    artifact_type: &str,
    resource_type: ResourceType,
) -> PathBuf {
    let flatten = get_flatten_behavior(manifest, dep, artifact_type, resource_type);
    let relative_path =
        compute_relative_install_path(artifact_path, Path::new(source_filename), flatten);
    artifact_path.join(relative_path)
}

/// Creates a detailed error message when a resource type is not supported by a tool.
///
/// Provides helpful hints if it looks like a tool name was used as a resource type.
fn create_unsupported_resource_error(
    artifact_type: &str,
    resource_type: ResourceType,
    source_path: &str,
) -> anyhow::Error {
    let base_msg =
        format!("Resource type '{}' is not supported by tool '{}'", resource_type, artifact_type);

    let resource_type_str = resource_type.to_string();
    let hint = if ["claude-code", "opencode", "agpm"].contains(&resource_type_str.as_str()) {
        format!(
            "\n\nIt looks like '{}' is a tool name, not a resource type.\n\
            In transitive dependencies, use resource types (agents, snippets, commands)\n\
            as section headers, then specify 'tool: {}' within each dependency.",
            resource_type_str, resource_type_str
        )
    } else {
        format!(
            "\n\nValid resource types: agent, command, snippet, hook, mcp-server, script\n\
            Source file: {}",
            source_path
        )
    };

    anyhow::anyhow!("{}{}", base_msg, hint)
}

/// Transforms an installation path for private dependencies.
///
/// Private dependencies are installed to a `private/` subdirectory within their
/// resource type directory. For example:
/// - `.claude/agents/helper.md` becomes `.claude/agents/private/helper.md`
/// - `.agpm/snippets/utils.md` becomes `.agpm/snippets/private/utils.md`
///
/// This function intelligently inserts `private/` after the resource type directory
/// by detecting common path patterns.
///
/// # Arguments
///
/// * `path` - The original installation path
///
/// # Returns
///
/// The transformed path with `private/` inserted before the filename.
///
/// # Examples
///
/// ```
/// use agpm_cli::resolver::path_resolver::transform_path_for_private;
///
/// // Without tool namespace
/// let path = transform_path_for_private(".claude/agents/helper.md");
/// assert_eq!(path, ".claude/agents/private/helper.md");
///
/// // With tool namespace (the common case)
/// let path = transform_path_for_private(".claude/agents/agpm/helper.md");
/// assert_eq!(path, ".claude/agents/agpm/private/helper.md");
///
/// let path = transform_path_for_private(".agpm/snippets/utils.md");
/// assert_eq!(path, ".agpm/snippets/private/utils.md");
///
/// // OpenCode paths (singular directory names)
/// let path = transform_path_for_private(".opencode/agent/agpm/test.md");
/// assert_eq!(path, ".opencode/agent/agpm/private/test.md");
/// ```
pub fn transform_path_for_private(path: &str) -> String {
    // Split the path into components
    let path_obj = Path::new(path);
    let components: Vec<_> = path_obj.components().collect();

    // Insert "private" before the filename (last component)
    // This handles both paths with and without tool namespaces:
    // - .claude/agents/helper.md -> .claude/agents/private/helper.md
    // - .claude/agents/agpm/helper.md -> .claude/agents/agpm/private/helper.md
    // - .opencode/agent/agpm/test.md -> .opencode/agent/agpm/private/test.md
    if components.len() >= 2 {
        let mut result_components: Vec<String> = components
            .iter()
            .take(components.len() - 1)
            .map(|c| c.as_os_str().to_string_lossy().to_string())
            .collect();

        // Insert "private" before the filename
        result_components.push("private".to_string());

        // Add the filename
        if let Some(last) = components.last() {
            result_components.push(last.as_os_str().to_string_lossy().to_string());
        }

        result_components.join("/")
    } else {
        // Path is too short, just prepend private/
        format!("private/{path}")
    }
}

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

    #[test]
    fn test_parse_pattern_base_path_simple() {
        let (base, pattern) = parse_pattern_base_path("*.md");
        assert_eq!(base, PathBuf::from("."));
        assert_eq!(pattern, "*.md");
    }

    #[test]
    fn test_parse_pattern_base_path_with_directory() {
        let (base, pattern) = parse_pattern_base_path("agents/*.md");
        assert_eq!(base, PathBuf::from("."));
        assert_eq!(pattern, "agents/*.md");
    }

    #[test]
    fn test_parse_pattern_base_path_with_parent() {
        let (base, pattern) = parse_pattern_base_path("../foo/*.md");
        assert_eq!(base, PathBuf::from("../foo"));
        assert_eq!(pattern, "*.md");
    }

    #[test]
    fn test_parse_pattern_base_path_with_current_dir() {
        let (base, pattern) = parse_pattern_base_path("./foo/*.md");
        assert_eq!(base, PathBuf::from("./foo"));
        assert_eq!(pattern, "*.md");
    }

    #[test]
    fn test_construct_full_relative_path_current_dir() {
        let base = PathBuf::from(".");
        let matched = Path::new("agents/helper.md");
        let path = construct_full_relative_path(&base, matched);
        assert_eq!(path, "agents/helper.md");
    }

    #[test]
    fn test_construct_full_relative_path_with_base() {
        let base = PathBuf::from("../foo");
        let matched = Path::new("bar.md");
        let path = construct_full_relative_path(&base, matched);
        assert_eq!(path, "../foo/bar.md");
    }

    #[test]
    fn test_extract_pattern_filename_current_dir() {
        let base = PathBuf::from(".");
        let matched = Path::new("agents/helper.md");
        let filename = extract_pattern_filename(&base, matched);
        assert_eq!(filename, "agents/helper.md");
    }
}