/*!
 * Stage-1 CLI bridge - modules list collector
 *
 * Parses nyash.toml [modules] section and formats module mappings
 * for Stage-1 CLI environment variables.
 */

use std::collections::HashSet;
use std::fs;
use std::path::PathBuf;

/// Collect modules list from nyash.toml [modules] section
///
/// Returns a "|||"-separated list of "key=value" entries for HAKO_STAGEB_MODULES_LIST.
/// Includes well-known aliases required by Stage-1 CLI if absent in nyash.toml.
pub(super) fn collect_modules_list() -> Option<String> {
    let path = PathBuf::from("nyash.toml");
    if !path.exists() {
        return None;
    }
    let content = fs::read_to_string(&path).ok()?;
    let mut entries: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    let mut in_modules = false;
    for raw in content.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with('[') {
            in_modules = line == "[modules]";
            continue;
        }
        if !in_modules {
            continue;
        }
        if let Some((k, v_raw)) = line.split_once('=') {
            let key = k.trim().trim_matches('"');
            let mut v = v_raw.trim();
            if let Some((head, _comment)) = v.split_once('#') {
                v = head.trim();
            }
            if v.starts_with('"') && v.ends_with('"') && v.len() >= 2 {
                v = &v[1..v.len().saturating_sub(1)];
            }
            if !key.is_empty() && !v.is_empty() {
                if seen.insert(key.to_string()) {
                    entries.push(format!("{key}={v}"));
                }
            }
        }
    }
    // Add a few well-known aliases required by Stage-1 CLI if they are absent in nyash.toml.
    for (k, v) in [
        (
            "lang.compiler.entry.using_resolver_box",
            "lang/src/compiler/entry/using_resolver_box.hako",
        ),
        (
            "selfhost.shared.host_bridge.codegen_bridge",
            "lang/src/shared/host_bridge/codegen_bridge_box.hako",
        ),
    ] {
        if seen.insert(k.to_string()) {
            entries.push(format!("{k}={v}"));
        }
    }
    if entries.is_empty() {
        None
    } else {
        Some(entries.join("|||"))
    }
}
