use std::collections::HashMap;

/// Extract a short title from the first line of a prompt.
pub fn extract_intent_title(prompt: &str) -> String {
    let first_line = prompt.lines().next().unwrap_or(prompt);
    let trimmed = first_line.trim();
    if trimmed.len() > 80 {
        format!("{:.80}...", trimmed)
    } else {
        trimmed.to_string()
    }
}

/// Decompose a prompt into candidate features via keyword scanning.
pub fn decompose_features(prompt: &str) -> Vec<String> {
    let mut features = Vec::new();
    let lower = prompt.to_lowercase();

    let keyword_map: HashMap<&str, Vec<&str>> = [
        ("auth", vec!["Authentication flow", "Session management"]),
        ("login", vec!["User login flow", "Credential validation"]),
        ("oauth", vec!["OAuth2 integration", "Token refresh"]),
        ("database", vec!["Database schema", "Migration support"]),
        ("api", vec!["REST API endpoints", "API documentation"]),
        ("ui", vec!["Frontend components", "User interface design"]),
        ("test", vec!["Unit tests", "Integration tests"]),
        ("deploy", vec!["Deployment pipeline", "Infrastructure setup"]),
        ("cache", vec!["Caching layer", "Cache invalidation"]),
        ("search", vec!["Search indexing", "Query optimization"]),
    ]
    .iter()
    .cloned()
    .collect();

    for (keyword, feats) in keyword_map {
        if lower.contains(keyword) {
            for feat in feats {
                if !features.contains(&feat.to_string()) {
                    features.push(feat.to_string());
                }
            }
        }
    }

    if features.is_empty() {
        features.push("Core feature".to_string());
    }

    features
}

/// URL-friendly slug.
pub fn slugify(s: &str) -> String {
    s.to_lowercase()
        .replace(|c: char| !c.is_alphanumeric() && c != ' ', "")
        .replace(' ', "-")
        .replace("--", "-")
        .trim_matches('-')
        .to_string()
}

/// Average confidence across all node and edge meta blocks.
pub fn compute_confidence(graph: &agileplus_domain::intent_graph::IntentGraph) -> f64 {
    let mut scores = Vec::new();
    for node in &graph.nodes {
        if let Some(c) = node.meta.confidence {
            scores.push(c);
        }
    }
    for edge in &graph.edges {
        if let Some(c) = edge.meta.confidence {
            scores.push(c);
        }
    }
    if scores.is_empty() {
        return 0.0;
    }
    let sum: f64 = scores.iter().sum();
    sum / scores.len() as f64
}
