//! Path computation helpers for module and item files.

/// Directory name used for module indexes (e.g., `api/<crate>/mod/...`).
pub const MODULE_DIR: &str = "mod";

/// Directory names used for specific item kinds under a module.
pub const ITEM_DIR_FUNCTION: &str = "fn";
pub const ITEM_DIR_STRUCT: &str = "struct";
pub const ITEM_DIR_ENUM: &str = "enum";
pub const ITEM_DIR_TRAIT: &str = "trait";
pub const ITEM_DIR_CONSTANT: &str = "const";
pub const ITEM_DIR_TYPE_ALIAS: &str = "type";
pub const ITEM_DIR_REEXPORT: &str = "reexport";

/// Compute absolute path for a module index file.
///
/// Returns path like `"api/my_crate/mod/my_crate/utils/index.md"`.
pub fn module_index_path(out_root: &str, fqpath: &str) -> String {
    if fqpath.is_empty() {
        format!("{}/{}/index.md", out_root, MODULE_DIR)
    } else {
        format!(
            "{}/{}/{}/index.md",
            out_root,
            MODULE_DIR,
            fqpath.replace("::", "/")
        )
    }
}

/// Compute relative link from parent module to child module index.
///
/// Returns path like `"./utils/index.md"`.
pub fn module_index_rel_link(parent_fq: &str, child_fq: &str) -> String {
    if parent_fq.is_empty() {
        format!("./{}/index.md", child_fq.replace("::", "/"))
    } else {
        let prefix = format!("{}::", parent_fq);
        let tail = child_fq.strip_prefix(&prefix).unwrap_or(child_fq);
        format!("./{}/index.md", tail.replace("::", "/"))
    }
}

/// Compute absolute path for an item file.
///
/// Returns path like `"api/my_crate/mod/my_crate/utils/fn/helper.md"`.
pub fn module_item_path(out_root: &str, fqpath: &str, kind_dir: &str, name: &str) -> String {
    if fqpath.is_empty() {
        format!("{}/{}/{}/{}.md", out_root, MODULE_DIR, kind_dir, name)
    } else {
        format!(
            "{}/{}/{}/{}/{}.md",
            out_root,
            MODULE_DIR,
            fqpath.replace("::", "/"),
            kind_dir,
            name
        )
    }
}

/// Compute relative link from module to an item page.
///
/// Returns path like `"./struct/my_crate/Config.md"`.
pub fn module_item_rel_link(
    parent_fq: &str,
    qualified: &str,
    kind_dir: &str,
    name: &str,
) -> String {
    let _ = qualified; // reserved for future anchors
    if parent_fq.is_empty() {
        format!("./{}/{}.md", kind_dir, name)
    } else {
        format!(
            "./{}/{}/{}.md",
            kind_dir,
            parent_fq.replace("::", "/"),
            name
        )
    }
}
