//! Contract Analyzer
//!
//! Analyzes Nickel contracts to infer conditional expressions for form generation.

use super::schema_ir::{NickelFieldIR, NickelSchemaIR, NickelType};

/// Analyzer for inferring conditional expressions from Nickel contracts
pub struct ContractAnalyzer;

impl ContractAnalyzer {
    /// Infer a conditional expression from a field based on optional status and schema context
    ///
    /// Returns a `when` expression (e.g., "tls_enabled == true") if the field appears to be
    /// conditionally dependent on another field's value, typically a boolean enable flag.
    pub fn infer_condition(field: &NickelFieldIR, schema: &NickelSchemaIR) -> Option<String> {
        if !field.optional {
            return None;
        }
        Self::find_boolean_dependency(field, schema)
    }

    fn find_boolean_dependency(field: &NickelFieldIR, schema: &NickelSchemaIR) -> Option<String> {
        let field_prefix = Self::extract_prefix(&field.flat_name)?;

        for candidate in &schema.fields {
            if candidate.nickel_type == NickelType::Bool {
                let candidate_prefix = Self::extract_prefix(&candidate.flat_name)?;
                if candidate_prefix == field_prefix && candidate.flat_name.ends_with("_enabled") {
                    return Some(format!("{} == true", candidate.flat_name));
                }
            }
        }

        None
    }

    fn extract_prefix(flat_name: &str) -> Option<String> {
        flat_name
            .split('_')
            .next()
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
    }
}
