//! Stack detection — inspect the project root for marker files and emit
//! TOML `[[component]]` entries plus `script/build|lint|test` content.

mod build;
mod components;
mod lint;
mod test_script;

pub(crate) use build::detect_script_build;
pub(crate) use components::detect_components_toml;
pub(crate) use lint::detect_script_lint;
pub(crate) use test_script::detect_script_test;

/// Detect the appropriate Node.js test command for a directory containing `package.json`.
///
/// Reads the `package.json` content to identify known test runners (vitest, jest).
/// Falls back to `npm test` or `pnpm test` based on which lock file is present.
fn detect_node_test_cmd(pkg_dir: &std::path::Path) -> String {
    let has_pnpm = pkg_dir.join("pnpm-lock.yaml").exists();
    let content = std::fs::read_to_string(pkg_dir.join("package.json")).unwrap_or_default();

    if content.contains("\"vitest\"") {
        let pm = if has_pnpm { "pnpm" } else { "npx" };
        return format!("{} vitest run", pm);
    }
    if content.contains("\"jest\"") {
        let pm = if has_pnpm { "pnpm" } else { "npx" };
        return format!("{} jest", pm);
    }

    if has_pnpm {
        "pnpm test".to_string()
    } else {
        "npm test".to_string()
    }
}

/// Detect the appropriate Node.js build command for a directory containing `package.json`.
fn detect_node_build_cmd(pkg_dir: &std::path::Path) -> String {
    if pkg_dir.join("pnpm-lock.yaml").exists() {
        "pnpm run build".to_string()
    } else {
        "npm run build".to_string()
    }
}

/// Detect the appropriate Node.js lint command for a directory containing `package.json`.
///
/// Reads the `package.json` content to identify eslint. Falls back to
/// `npm run lint` or `pnpm run lint` based on which lock file is present.
fn detect_node_lint_cmd(pkg_dir: &std::path::Path) -> String {
    let has_pnpm = pkg_dir.join("pnpm-lock.yaml").exists();
    let content = std::fs::read_to_string(pkg_dir.join("package.json")).unwrap_or_default();
    if content.contains("\"eslint\"") {
        let pm = if has_pnpm { "pnpm" } else { "npx" };
        return format!("{pm} eslint .");
    }
    if has_pnpm {
        "pnpm run lint".to_string()
    } else {
        "npm run lint".to_string()
    }
}
