using System;

namespace HydraulicSimulator.Models
{
    /// <summary>
    /// Bomba con curva H(Q)=H0*(1-(Q/Q0)²) y ley de afinidad con velocidad relativa
    /// </summary>
    public class PumpHQ : Element
    {
        public double H0 { get; set; } // m, a velocidad nominal (shutoff head)
        public double Q0 { get; set; } // m³/s, caudal a cabeza cero, vel nominal
        public double SpeedRel { get; set; } = 1.0; // n / n_nominal
        public int Direction { get; set; } = 1; // +1 si impulsa de i->j, -1 si al revés

        public PumpHQ(double h0, double q0, double speedRel = 1.0, int direction = 1)
        {
            H0 = h0;
            Q0 = q0;
            SpeedRel = speedRel;
            Direction = direction;
        }

        private (double H0s, double Q0s) Scaled
        {
            get
            {
                var s = Math.Max(1e-3, SpeedRel);
                return (H0 * (s * s), Q0 * s);
            }
        }

        public override double Dp(double q, Fluid fluid)
        {
            var (h0s, q0s) = Scaled;
            // Limitamos fuera de rango para estabilidad
            var qq = Math.Max(-q0s * 0.999, Math.Min(q0s * 0.999, q));
            var h = h0s * (1.0 - Math.Pow(qq / q0s, 2));
            var dp = -Direction * fluid.Rho * 9.80665 * h;
            // dp es negativo si la bomba agrega presión en el sentido de la rama
            return dp;
        }

        public override double DdpDq(double q, Fluid fluid)
        {
            var (h0s, q0s) = Scaled;
            var dhDq = -2.0 * h0s * q / (q0s * q0s);
            return -Direction * fluid.Rho * 9.80665 * dhDq + 1e-12;
        }
    }
}
