use crate::types::Type;
use std::fmt::{Display, Formatter, Write};

/// A function type representing a callable with parameter types and a return type.
///
/// Function types are structural - equality depends only on parameter and return types,
/// not parameter names.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Function {
    pub params: Vec<Type>,
    pub return_type: Box<Type>,
}

impl Function {
    pub fn new(params: Vec<Type>, return_type: Type) -> Self {
        Self {
            params,
            return_type: Box::new(return_type),
        }
    }

    pub fn fmt_indented(
        &self,
        f: &mut impl Write,
        indentation: usize,
        max_fields: usize,
    ) -> std::fmt::Result {
        write!(f, "fn(")?;
        for (i, param) in self.params.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            param.fmt_indented(f, indentation, max_fields)?;
        }
        write!(f, ") -> ")?;
        self.return_type.fmt_indented(f, indentation, max_fields)
    }

    pub fn subfields(&self) -> usize {
        self.params.iter().map(|p| p.subfields()).sum::<usize>() + self.return_type.subfields()
    }
}

impl Display for Function {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0, usize::MAX)
    }
}
