//! Residual embedding for One-Shot inverse control.
//!
//! This module implements the core innovation of Epic 5: embedding constraints
//! directly into the residual system for simultaneous solving with cycle equations.
//!
//! # Mathematical Foundation
//!
//! In One-Shot inverse control, constraints are added to the residual vector:
//!
//! $$r_{total} = [r_{cycle}, r_{constraints}]^T$$
//!
//! where:
//! - $r_{cycle}$ are the component residual equations
//! - $r_{constraints}$ are constraint residuals: $f(x) - y_{target}$
//!
//! The solver adjusts both edge states AND control variables simultaneously
//! to satisfy all equations.
//!
//! # Degrees of Freedom (DoF) Validation
//!
//! For a well-posed system:
//!
//! $$n_{equations} = n_{edge\_eqs} + n_{constraints}$$
//! $$n_{unknowns} = n_{edge\_unknowns} + n_{controls}$$
//!
//! The system is balanced when: $n_{equations} = n_{unknowns}$
//!
//! # Example
//!
//! ```rust,ignore
//! use entropyk_solver::inverse::{Constraint, ConstraintId, ComponentOutput};
//! use entropyk_solver::inverse::{BoundedVariable, BoundedVariableId};
//!
//! // Define constraint: superheat = 5K
//! let constraint = Constraint::new(
//!     ConstraintId::new("superheat_control"),
//!     ComponentOutput::Superheat { component_id: "evaporator".into() },
//!     5.0,
//! );
//!
//! // Define control variable: valve position
//! let valve = BoundedVariable::new(
//!     BoundedVariableId::new("expansion_valve"),
//!     0.5, 0.0, 1.0,
//! )?;
//!
//! // Link constraint to control for One-Shot solving
//! system.add_constraint(constraint)?;
//! system.add_bounded_variable(valve)?;
//! system.link_constraint_to_control(
//!     &ConstraintId::new("superheat_control"),
//!     &BoundedVariableId::new("expansion_valve"),
//! )?;
//!
//! // Validate DoF before solving
//! system.validate_inverse_control_dof()?;
//! ```

use std::collections::HashMap;
use thiserror::Error;

use super::{BoundedVariableId, ConstraintError, ConstraintId};

// ─────────────────────────────────────────────────────────────────────────────
// DoFError - Degrees of Freedom Validation Errors
// ─────────────────────────────────────────────────────────────────────────────

/// Errors during degrees of freedom validation for inverse control.
#[derive(Error, Debug, Clone, PartialEq)]
pub enum DoFError {
    /// The system has more constraints than control variables.
    #[error(
        "Over-constrained system: {constraint_count} constraints but only {control_count} control variables \
         (equations: {equation_count}, unknowns: {unknown_count})"
    )]
    OverConstrainedSystem {
        constraint_count: usize,
        control_count: usize,
        equation_count: usize,
        unknown_count: usize,
    },

    /// The system has fewer constraints than control variables (may still converge).
    #[error(
        "Under-constrained system: {constraint_count} constraints for {control_count} control variables \
         (equations: {equation_count}, unknowns: {unknown_count})"
    )]
    UnderConstrainedSystem {
        constraint_count: usize,
        control_count: usize,
        equation_count: usize,
        unknown_count: usize,
    },

    /// The referenced constraint does not exist.
    #[error("Constraint '{constraint_id}' not found when linking to control")]
    ConstraintNotFound { constraint_id: ConstraintId },

    /// The referenced bounded variable does not exist.
    #[error("Bounded variable '{bounded_variable_id}' not found when linking to constraint")]
    BoundedVariableNotFound {
        bounded_variable_id: BoundedVariableId,
    },

    /// The constraint is already linked to a control variable.
    #[error("Constraint '{constraint_id}' is already linked to control '{existing}'")]
    AlreadyLinked {
        constraint_id: ConstraintId,
        existing: BoundedVariableId,
    },

    /// The control variable is already linked to another constraint.
    #[error(
        "Control variable '{bounded_variable_id}' is already linked to constraint '{existing}'"
    )]
    ControlAlreadyLinked {
        bounded_variable_id: BoundedVariableId,
        existing: ConstraintId,
    },
}

// ─────────────────────────────────────────────────────────────────────────────
// ControlMapping - Constraint → Control Variable Mapping
// ─────────────────────────────────────────────────────────────────────────────

/// A mapping from a constraint to its control variable.
///
/// This establishes the relationship needed for One-Shot solving where
/// the solver adjusts the control variable to satisfy the constraint.
#[derive(Debug, Clone, PartialEq)]
pub struct ControlMapping {
    /// The constraint to satisfy.
    pub constraint_id: ConstraintId,
    /// The control variable to adjust.
    pub bounded_variable_id: BoundedVariableId,
    /// Whether this mapping is active.
    pub enabled: bool,
}

impl ControlMapping {
    /// Creates a new control mapping.
    pub fn new(constraint_id: ConstraintId, bounded_variable_id: BoundedVariableId) -> Self {
        ControlMapping {
            constraint_id,
            bounded_variable_id,
            enabled: true,
        }
    }

    /// Creates a disabled mapping.
    pub fn disabled(constraint_id: ConstraintId, bounded_variable_id: BoundedVariableId) -> Self {
        ControlMapping {
            constraint_id,
            bounded_variable_id,
            enabled: false,
        }
    }

    /// Enables this mapping.
    pub fn enable(&mut self) {
        self.enabled = true;
    }

    /// Disables this mapping.
    pub fn disable(&mut self) {
        self.enabled = false;
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// InverseControlConfig - Configuration for Inverse Control
// ─────────────────────────────────────────────────────────────────────────────

/// Configuration for One-Shot inverse control.
///
/// Manages constraint-to-control-variable mappings for embedding constraints
/// into the residual system.
#[derive(Debug, Clone)]
pub struct InverseControlConfig {
    /// Mapping from constraint ID to control variable ID.
    constraint_to_control: HashMap<ConstraintId, BoundedVariableId>,
    /// Mapping from control variable ID to constraint ID (reverse lookup).
    control_to_constraint: HashMap<BoundedVariableId, ConstraintId>,
    /// Whether inverse control is enabled globally.
    enabled: bool,
    /// Finite difference epsilon for numerical Jacobian computation.
    /// Default is 1e-6, which balances numerical precision against floating-point rounding errors.
    finite_diff_epsilon: f64,
}

impl Default for InverseControlConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl InverseControlConfig {
    /// Default finite difference epsilon for numerical Jacobian computation.
    pub const DEFAULT_FINITE_DIFF_EPSILON: f64 = 1e-6;

    /// Creates a new empty inverse control configuration.
    pub fn new() -> Self {
        InverseControlConfig {
            constraint_to_control: HashMap::new(),
            control_to_constraint: HashMap::new(),
            enabled: true,
            finite_diff_epsilon: Self::DEFAULT_FINITE_DIFF_EPSILON,
        }
    }

    /// Creates a disabled configuration.
    pub fn disabled() -> Self {
        InverseControlConfig {
            constraint_to_control: HashMap::new(),
            control_to_constraint: HashMap::new(),
            enabled: false,
            finite_diff_epsilon: Self::DEFAULT_FINITE_DIFF_EPSILON,
        }
    }

    /// Returns the finite difference epsilon used for numerical Jacobian computation.
    pub fn finite_diff_epsilon(&self) -> f64 {
        self.finite_diff_epsilon
    }

    /// Sets the finite difference epsilon for numerical Jacobian computation.
    ///
    /// # Errors
    ///
    /// Returns `ConstraintError::InvalidEpsilon` if epsilon is not a finite positive value in (0, 1].
    pub fn set_finite_diff_epsilon(&mut self, epsilon: f64) -> Result<(), ConstraintError> {
        if !epsilon.is_finite() {
            return Err(ConstraintError::InvalidEpsilon {
                value: epsilon,
                reason: "epsilon must be finite".to_string(),
            });
        }
        if epsilon <= 0.0 || epsilon > 1.0 {
            return Err(ConstraintError::InvalidEpsilon {
                value: epsilon,
                reason: format!("epsilon must be in (0, 1], got {}", epsilon),
            });
        }
        self.finite_diff_epsilon = epsilon;
        Ok(())
    }

    /// Returns whether inverse control is enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Enables inverse control.
    pub fn enable(&mut self) {
        self.enabled = true;
    }

    /// Disables inverse control.
    pub fn disable(&mut self) {
        self.enabled = false;
    }

    /// Returns the number of constraint-control mappings.
    pub fn mapping_count(&self) -> usize {
        self.constraint_to_control.len()
    }

    /// Links a constraint to a control variable.
    ///
    /// # Errors
    ///
    /// Returns `DoFError::AlreadyLinked` if the constraint is already linked.
    /// Returns `DoFError::ControlAlreadyLinked` if the control is already linked.
    pub fn link(
        &mut self,
        constraint_id: ConstraintId,
        bounded_variable_id: BoundedVariableId,
    ) -> Result<(), DoFError> {
        if let Some(existing) = self.constraint_to_control.get(&constraint_id) {
            return Err(DoFError::AlreadyLinked {
                constraint_id,
                existing: existing.clone(),
            });
        }

        if let Some(existing) = self.control_to_constraint.get(&bounded_variable_id) {
            return Err(DoFError::ControlAlreadyLinked {
                bounded_variable_id,
                existing: existing.clone(),
            });
        }

        self.constraint_to_control
            .insert(constraint_id.clone(), bounded_variable_id.clone());
        self.control_to_constraint
            .insert(bounded_variable_id, constraint_id);
        Ok(())
    }

    /// Unlinks a constraint from its control variable.
    ///
    /// Returns the bounded variable ID that was linked, or `None` if not linked.
    pub fn unlink_constraint(&mut self, constraint_id: &ConstraintId) -> Option<BoundedVariableId> {
        if let Some(bounded_var_id) = self.constraint_to_control.remove(constraint_id) {
            self.control_to_constraint.remove(&bounded_var_id);
            Some(bounded_var_id)
        } else {
            None
        }
    }

    /// Unlinks a control variable from its constraint.
    ///
    /// Returns the constraint ID that was linked, or `None` if not linked.
    pub fn unlink_control(
        &mut self,
        bounded_variable_id: &BoundedVariableId,
    ) -> Option<ConstraintId> {
        if let Some(constraint_id) = self.control_to_constraint.remove(bounded_variable_id) {
            self.constraint_to_control.remove(&constraint_id);
            Some(constraint_id)
        } else {
            None
        }
    }

    /// Returns the control variable linked to a constraint.
    pub fn get_control(&self, constraint_id: &ConstraintId) -> Option<&BoundedVariableId> {
        self.constraint_to_control.get(constraint_id)
    }

    /// Returns the constraint linked to a control variable.
    pub fn get_constraint(&self, bounded_variable_id: &BoundedVariableId) -> Option<&ConstraintId> {
        self.control_to_constraint.get(bounded_variable_id)
    }

    /// Returns constraint→control mappings in **stable** order (sorted by constraint id).
    ///
    /// HashMap iteration is randomized per process; residual rows, Jacobian rows/columns,
    /// and control state indices must share one deterministic order or Newton flakes.
    pub fn mappings(&self) -> impl Iterator<Item = (&ConstraintId, &BoundedVariableId)> {
        let mut items: Vec<_> = self.constraint_to_control.iter().collect();
        items.sort_by(|a, b| a.0.cmp(b.0));
        items.into_iter()
    }

    /// Linked constraint IDs in the same order as [`Self::mappings`].
    pub fn linked_constraints(&self) -> impl Iterator<Item = &ConstraintId> {
        self.mappings().map(|(c, _)| c)
    }

    /// Linked control IDs in the same order as [`Self::mappings`] (column / state layout).
    pub fn linked_controls(&self) -> impl Iterator<Item = &BoundedVariableId> {
        self.mappings().map(|(_, c)| c)
    }

    /// Checks if a constraint is linked.
    pub fn is_constraint_linked(&self, constraint_id: &ConstraintId) -> bool {
        self.constraint_to_control.contains_key(constraint_id)
    }

    /// Checks if a control variable is linked.
    pub fn is_control_linked(&self, bounded_variable_id: &BoundedVariableId) -> bool {
        self.control_to_constraint.contains_key(bounded_variable_id)
    }

    /// Clears all mappings.
    pub fn clear(&mut self) {
        self.constraint_to_control.clear();
        self.control_to_constraint.clear();
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn make_constraint_id(s: &str) -> ConstraintId {
        ConstraintId::new(s)
    }

    fn make_bounded_var_id(s: &str) -> BoundedVariableId {
        BoundedVariableId::new(s)
    }

    #[test]
    fn test_dof_error_display() {
        let err = DoFError::OverConstrainedSystem {
            constraint_count: 3,
            control_count: 1,
            equation_count: 10,
            unknown_count: 8,
        };
        let msg = err.to_string();
        assert!(msg.contains("3"));
        assert!(msg.contains("1"));
        assert!(msg.contains("10"));
        assert!(msg.contains("8"));
        assert!(msg.contains("Over-constrained"));
    }

    #[test]
    fn test_dof_error_constraint_not_found() {
        let err = DoFError::ConstraintNotFound {
            constraint_id: make_constraint_id("test"),
        };
        assert!(err.to_string().contains("test"));
    }

    #[test]
    fn test_dof_error_already_linked() {
        let err = DoFError::AlreadyLinked {
            constraint_id: make_constraint_id("c1"),
            existing: make_bounded_var_id("v1"),
        };
        let msg = err.to_string();
        assert!(msg.contains("c1"));
        assert!(msg.contains("v1"));
    }

    #[test]
    fn test_control_mapping_creation() {
        let mapping = ControlMapping::new(
            make_constraint_id("superheat"),
            make_bounded_var_id("valve"),
        );

        assert_eq!(mapping.constraint_id.as_str(), "superheat");
        assert_eq!(mapping.bounded_variable_id.as_str(), "valve");
        assert!(mapping.enabled);
    }

    #[test]
    fn test_control_mapping_disabled() {
        let mapping = ControlMapping::disabled(
            make_constraint_id("superheat"),
            make_bounded_var_id("valve"),
        );

        assert!(!mapping.enabled);
    }

    #[test]
    fn test_control_mapping_enable_disable() {
        let mut mapping = ControlMapping::new(make_constraint_id("c"), make_bounded_var_id("v"));

        mapping.disable();
        assert!(!mapping.enabled);

        mapping.enable();
        assert!(mapping.enabled);
    }

    #[test]
    fn test_inverse_control_config_new() {
        let config = InverseControlConfig::new();

        assert!(config.is_enabled());
        assert_eq!(config.mapping_count(), 0);
    }

    #[test]
    fn test_inverse_control_config_disabled() {
        let config = InverseControlConfig::disabled();

        assert!(!config.is_enabled());
    }

    #[test]
    fn test_inverse_control_config_enable_disable() {
        let mut config = InverseControlConfig::new();

        config.disable();
        assert!(!config.is_enabled());

        config.enable();
        assert!(config.is_enabled());
    }

    #[test]
    fn test_inverse_control_config_link() {
        let mut config = InverseControlConfig::new();

        let result = config.link(make_constraint_id("c1"), make_bounded_var_id("v1"));
        assert!(result.is_ok());
        assert_eq!(config.mapping_count(), 1);

        let control = config.get_control(&make_constraint_id("c1"));
        assert!(control.is_some());
        assert_eq!(control.unwrap().as_str(), "v1");

        let constraint = config.get_constraint(&make_bounded_var_id("v1"));
        assert!(constraint.is_some());
        assert_eq!(constraint.unwrap().as_str(), "c1");
    }

    #[test]
    fn test_inverse_control_config_link_already_linked_constraint() {
        let mut config = InverseControlConfig::new();

        config
            .link(make_constraint_id("c1"), make_bounded_var_id("v1"))
            .unwrap();

        let result = config.link(make_constraint_id("c1"), make_bounded_var_id("v2"));
        assert!(matches!(result, Err(DoFError::AlreadyLinked { .. })));
        if let Err(DoFError::AlreadyLinked {
            constraint_id,
            existing,
        }) = result
        {
            assert_eq!(constraint_id.as_str(), "c1");
            assert_eq!(existing.as_str(), "v1");
        }
    }

    #[test]
    fn test_inverse_control_config_link_already_linked_control() {
        let mut config = InverseControlConfig::new();

        config
            .link(make_constraint_id("c1"), make_bounded_var_id("v1"))
            .unwrap();

        let result = config.link(make_constraint_id("c2"), make_bounded_var_id("v1"));
        assert!(matches!(result, Err(DoFError::ControlAlreadyLinked { .. })));
        if let Err(DoFError::ControlAlreadyLinked {
            bounded_variable_id,
            existing,
        }) = result
        {
            assert_eq!(bounded_variable_id.as_str(), "v1");
            assert_eq!(existing.as_str(), "c1");
        }
    }

    #[test]
    fn test_inverse_control_config_unlink_constraint() {
        let mut config = InverseControlConfig::new();

        config
            .link(make_constraint_id("c1"), make_bounded_var_id("v1"))
            .unwrap();

        let removed = config.unlink_constraint(&make_constraint_id("c1"));
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().as_str(), "v1");
        assert_eq!(config.mapping_count(), 0);

        let removed_again = config.unlink_constraint(&make_constraint_id("c1"));
        assert!(removed_again.is_none());
    }

    #[test]
    fn test_inverse_control_config_unlink_control() {
        let mut config = InverseControlConfig::new();

        config
            .link(make_constraint_id("c1"), make_bounded_var_id("v1"))
            .unwrap();

        let removed = config.unlink_control(&make_bounded_var_id("v1"));
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().as_str(), "c1");
        assert_eq!(config.mapping_count(), 0);
    }

    #[test]
    fn test_inverse_control_config_is_linked() {
        let mut config = InverseControlConfig::new();

        assert!(!config.is_constraint_linked(&make_constraint_id("c1")));
        assert!(!config.is_control_linked(&make_bounded_var_id("v1")));

        config
            .link(make_constraint_id("c1"), make_bounded_var_id("v1"))
            .unwrap();

        assert!(config.is_constraint_linked(&make_constraint_id("c1")));
        assert!(config.is_control_linked(&make_bounded_var_id("v1")));
    }

    #[test]
    fn test_inverse_control_config_mappings_iterator() {
        let mut config = InverseControlConfig::new();

        // Insert out of alphabetical order — iteration must still be sorted.
        config
            .link(make_constraint_id("z_probe"), make_bounded_var_id("z_ua_cond"))
            .unwrap();
        config
            .link(make_constraint_id("a_probe"), make_bounded_var_id("z_ua_evap"))
            .unwrap();

        let ids: Vec<&str> = config.mappings().map(|(c, _)| c.as_str()).collect();
        assert_eq!(ids, vec!["a_probe", "z_probe"]);
        let controls: Vec<&str> = config.linked_controls().map(|c| c.as_str()).collect();
        assert_eq!(controls, vec!["z_ua_evap", "z_ua_cond"]);
    }

    #[test]
    fn test_inverse_control_config_clear() {
        let mut config = InverseControlConfig::new();

        config
            .link(make_constraint_id("c1"), make_bounded_var_id("v1"))
            .unwrap();
        config
            .link(make_constraint_id("c2"), make_bounded_var_id("v2"))
            .unwrap();

        config.clear();
        assert_eq!(config.mapping_count(), 0);
    }
}
