import math
import datetime
import numpy as np
from config import *
from scipy.integrate import quad, dblquad

# We assume a right turn, we will compute steering torque on left and right wheels
# When turning right steering torque around kingpin axis is negative. So 

class SteeringMomentCalculator:
    def __init__(self):
        """Initialize the steering moment calculator with config parameters."""
        self.vehicle_mass = VEHICLE_MASS
        self.weight_distribution_front = WEIGHT_DISTRIBUTION_FRONT
        self.gravity = GRAVITY
        
        # Tire parameters
        self.tire_contact_patch_length = TIRE_CONTACT_PATCH_LENGTH
        self.tire_contact_patch_width = TIRE_CONTACT_PATCH_WIDTH
        self.pneumatic_trail = PNEUMATIC_TRAIL
        
        # Friction and road parameters
        self.friction_coefficient = FRICTION_COEFFICIENT
        
        # Steering geometry
        self.caster_angle = math.radians(CASTER_ANGLE)
        self.scrub_radius = SCRUB_RADIUS
        self.kingpin_inclination = math.radians(KINGPIN_INCLINATION)
        self.mecanical_trail = MECANICAL_TRAIL
        
        # Steering system
        self.steering_ratio = STEERING_RATIO
        self.mechanical_advantage = MECHANICAL_ADVANTAGE
        self.bearing_friction_coeff = BEARING_FRICTION_COEFFICIENT
        self.steering_gearbox_ratio = STEERING_GEARBOX_RATIO
        self.steering_gearbox_efficiency = STEERING_GEARBOX_EFFICIENCY
        
        # Operating conditions
        self.desired_axial_force = DESIRED_AXIAL_FORCE
        self.desired_lateral_force = DESIRED_LATERAL_FORCE
        self.force_distribution = FORCE_DISTRIBUTION
        self.vehicle_speed = VEHICLE_SPEED*1000/3600
        
        # Result storage
        self.output_lines = []
        
    def print_and_store(self, text=""):
        """Print to console and store for file output."""
        print(text)
        self.output_lines.append(text)
    
    def calculate_normal_load_right(self):
        """Calculate normal load on front wheels."""
        total_weight = self.vehicle_mass * self.gravity
        front_weight = total_weight * self.weight_distribution_front
        normal_load_per_wheel = front_weight*(1-self.force_distribution)  # assuming two front wheels
        return normal_load_per_wheel
    
    def calculate_normal_load_left(self):
        """Calculate normal load on front wheels."""
        total_weight = self.vehicle_mass * self.gravity
        front_weight = total_weight * self.weight_distribution_front
        normal_load_per_wheel = front_weight*self.force_distribution  # assuming two front wheels
        return normal_load_per_wheel
    
    def calculate_maximum_planar_force(self, normal_load):
        """Calculate maximum available planar force."""
        return self.friction_coefficient * normal_load
    
    def define_tire_reaction_vector(self, axial_force, lateral_force, normal_load):
        """Define the resulting force vector of Fx, Fy and Fz ; assuming right turn, Fy<0"""
        return np.array([axial_force, -lateral_force, normal_load])
    
    def define_Left_steering_axis_vector(self):
        """Define the steering axis vector"""
        return np.array([-np.sin(self.caster_angle), -np.sin(self.kingpin_inclination)*np.cos(self.caster_angle), np.cos(self.kingpin_inclination)*np.cos(self.caster_angle)])

    def define_Right_steering_axis_vector(self):
        """Define the steering axis vector"""
        return np.array([-np.sin(self.caster_angle), np.sin(self.kingpin_inclination)*np.cos(self.caster_angle), np.cos(self.kingpin_inclination)*np.cos(self.caster_angle)])

    def calculate_aligning_moment_right(self, reaction_vector):
        """Calculate self-aligning torque (in Pc) due to pneumatic trail."""
        MFy = -reaction_vector[1] * self.pneumatic_trail # aligning moment is positive when turning right, minus is here to respect the cross product, Fy < 0
        aligning_moment = np.array([0, 0, MFy])
        PkgPc_vector = np.array([-self.mecanical_trail, -self.scrub_radius, 0]) # difference between left and right wheel is in the sign of Scrub Radius
        aligning_moment = aligning_moment + np.cross(PkgPc_vector, reaction_vector)
        return aligning_moment
    
    def calculate_aligning_moment_left(self, reaction_vector):
        """Calculate self-aligning torque (in Pc) due to pneumatic trail."""
        MFy = -reaction_vector[1] * self.pneumatic_trail # aligning moment is positive when turning right, minus is here to respect the cross product, Fy < 0
        aligning_moment = np.array([0, 0, MFy])
        PkgPc_vector = np.array([-self.mecanical_trail, self.scrub_radius, 0]) # difference between left and right wheel is in the sign of Scrub Radius
        aligning_moment = aligning_moment + np.cross(PkgPc_vector, reaction_vector)
        return aligning_moment 

    def pressure_distribution(self, x, y,Fz):
        """Calculate the pressure on the point M(x,y)"""
        a = self.tire_contact_patch_length
        b = self.tire_contact_patch_width
        return (6*Fz/a**3/b)*(a/2-x)*(a/2+x)

    def distance_KP_axle(self, x, y):
        """Calculate the distance between M(x,y) and the kingpin axis in the ground plane"""
        n = self.mecanical_trail
        Rs = self.scrub_radius
        return (x**2+(Rs+y)**2)**0.5
        
    def mu_friction_moment(self):
        return 0.4511*np.exp(-0.4603*self.vehicle_speed)+0.2376
    
    def d_friction_moment(self,y,x,Fz):
        """Calculate the friction moment created by a small surface of the contact patch"""
        return self.mu_friction_moment()*self.pressure_distribution(x,y,Fz)*self.distance_KP_axle(x,y)
        
    def calculate_friction_moment(self,Fz):
        """Calculate road/tire friction moment on steering axis"""
        a = self.tire_contact_patch_length
        b = self.tire_contact_patch_width
        return np.array([0, 0, dblquad(self.d_friction_moment, -a/2, a/2, -b/2, b/2, args=(Fz,))[0]])  # [N.m] friction moment is positive when turning right

    # def calculate_Left_steering_moment(self, reaction_vector):
    #     """Calculate total steering moment : a vector """
    #     aligning_moment = np.array([0, 0, self.calculate_aligning_moment(reaction_vector[1])])
    #     friction_moment = np.array([0, 0, self.calculate_friction_moment(reaction_vector[2])[0]])
    #     PkgPc_vector = np.array([-self.mecanical_trail, self.scrub_radius, 0]) # difference between left and right wheel is in the sign of Scrub Radius
    #     return aligning_moment + friction_moment + np.cross(PkgPc_vector, reaction_vector) 
    
    # def calculate_Right_steering_moment(self, reaction_vector):
    #     """Calculate total steering moment : a vector """
    #     aligning_moment = np.array([0, 0, self.calculate_aligning_moment(reaction_vector[1])])
    #     friction_moment = np.array([0, 0, self.calculate_friction_moment(reaction_vector[2])[0]])
    #     PkgPc_vector = np.array([-self.mecanical_trail, -self.scrub_radius, 0]) # difference between left and right wheel is in the sign of Scrub Radius
    #     return aligning_moment + friction_moment + np.cross(PkgPc_vector, reaction_vector) 
    
    def project_steering_moment(self, steering_moment, steering_axis_vector):
       """Project the steering moment (Z axis) on steering axis."""
       return np.dot(steering_moment, steering_axis_vector)
    
    def calculate_steering_wheel_torque(self, wheel_moment_Left, wheel_moment_Right):
        """Convert wheel moment to steering wheel torque."""
        # Apply steering ratio and mechanical advantage
        steering_wheel_torque = (wheel_moment_Left + wheel_moment_Right) / (self.steering_ratio * self.mechanical_advantage*self.steering_gearbox_efficiency)
        return steering_wheel_torque
    
    def calculate_steering_column_torque(self,steering_wheel_torque):
        """Calculate the torque at the steering gearbox output shaft"""
        steering_gearbox_output_torque = steering_wheel_torque*self.steering_gearbox_ratio*self.steering_gearbox_efficiency
        return steering_gearbox_output_torque
    
    def get_config_content(self):
        """Read and return the content of config.py file."""
        try:
            with open('config.py', 'r') as file:
                return file.read()
        except FileNotFoundError:
            return "config.py file not found"
        except Exception as e:
            return f"Error reading config.py: {str(e)}"
    
    def save_results_to_file(self, results):
        """Save all results and config content to the specified file."""
        try:
            with open(RESULT_FILENAME, 'w') as file:
                # Write header with timestamp
                file.write("=" * 60 + "\n")
                file.write("STEERING MOMENT CALCULATION RESULTS\n")
                file.write("=" * 60 + "\n")
                file.write(f"Generated on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                file.write("=" * 60 + "\n\n")
                
                # Write calculation results
                file.write("CALCULATION RESULTS:\n")
                file.write("-" * 30 + "\n")
                for line in self.output_lines:
                    file.write(line + "\n")
                
                file.write("\n" + "=" * 60 + "\n")
                file.write("CONFIGURATION PARAMETERS USED:\n")
                file.write("=" * 60 + "\n")
                
                # Write config file content
                config_content = self.get_config_content()
                file.write(config_content)
                
                file.write("\n" + "=" * 60 + "\n")
                file.write("END OF REPORT\n")
                file.write("=" * 60 + "\n")
                
            self.print_and_store(f"\nResults saved to: {RESULT_FILENAME}")
            
        except Exception as e:
            self.print_and_store(f"Error saving results to file: {str(e)}")
    
    def run_full_calculation(self):
        """Run the complete steering moment calculation."""
        np.set_printoptions(precision=2)
        self.print_and_store("=== Steering Moment Calculation ===\n")
        
        # I : Right wheel
        self.print_and_store(f"\n1_ Right wheel :")
        self.print_and_store(f"________________________")
        
        # Step 1: Calculate normal load
        normal_load_right = self.calculate_normal_load_right()
        self.print_and_store(f"Step 1 - Normal Load on right Wheel: {normal_load_right:.1f} N")
        
        # Step 2: Maximum planar forces
        max_planar_force_right = self.calculate_maximum_planar_force(normal_load_right)
        self.print_and_store(f"Step 2 - Maximum Planar Force: {max_planar_force_right:.1f} N")
        
        # Use desired lateral force (should be less than maximum)
        right_lateral_force = self.desired_lateral_force*(1-self.force_distribution)   
        right_axial_force = self.desired_axial_force*(1-self.force_distribution)
        right_planar_force = (right_lateral_force**2+right_axial_force**2)**0.5
        self.print_and_store(f"         Using Lateral Force: {right_lateral_force:.1f} N")
        self.print_and_store(f"         Using Axial Force: {right_axial_force:.1f} N")
        self.print_and_store(f"         Planar Force = {right_planar_force:.1f} N")
        # Safety check
        if right_planar_force >= max_planar_force_right:
            self.print_and_store("WARNING: Desired planar forces exceed tire friction limit!")
            
        # Step 3: Define steering axis vector
        KP_vector_Right = self.define_Right_steering_axis_vector()
        self.print_and_store(f"\nStep 3 - Right steering axis vector:"+str(KP_vector_Right))
        
        # Step 4: Calculate steering moment
        reaction_vector_right = self.define_tire_reaction_vector(right_axial_force, right_lateral_force, normal_load_right)
        self_aligning_moment_right = self.calculate_aligning_moment_right(reaction_vector_right)
        friction_moment = self.calculate_friction_moment(normal_load_right)
        steering_moment_Right = self_aligning_moment_right + friction_moment
        self.print_and_store(f"\nStep 4 -  ")
        self.print_and_store(f"         Total Steering Moment: "+str(steering_moment_Right)+" Nm")
        self.print_and_store(f"Friction Moment: ")
        self.print_and_store(f"         "+str(friction_moment)+" Nm (one tire)")
        self.print_and_store(f"Self Aligning Moment: ")
        self.print_and_store(f"         "+str(self_aligning_moment_right)+" Nm (one tire)")
        
        # Step 5: Project steering moment on steering axis vector
        steering_moment_KP_Right = self.project_steering_moment(steering_moment_Right, KP_vector_Right)
        self.print_and_store(f"\nStep 5 - Steering moment around steering axis:")
        self.print_and_store(f"         Right : {steering_moment_KP_Right:.2f} Nm")
        
        
        # II : Left wheel
        self.print_and_store(f"\n2_ Left wheel :")
        self.print_and_store(f"________________________")
        
        # Step 1: Calculate normal load
        normal_load_left = self.calculate_normal_load_left()
        self.print_and_store(f"Step 1 - Normal Load on left Wheel: {normal_load_left:.1f} N")
        
        # Step 2: Maximum planar forces
        max_planar_force_left = self.calculate_maximum_planar_force(normal_load_left)
        self.print_and_store(f"Step 2 - Maximum Planar Force: {max_planar_force_left:.1f} N")
        # Use desired lateral force (should be less than maximum)
        left_lateral_force = self.desired_lateral_force*self.force_distribution   
        left_axial_force = self.desired_axial_force*self.force_distribution
        left_planar_force = (left_lateral_force**2+left_axial_force**2)**0.5
        self.print_and_store(f"         Using Lateral Force: {left_lateral_force:.1f} N")
        self.print_and_store(f"         Using Axial Force: {left_axial_force:.1f} N")
        self.print_and_store(f"         Planar Force = {left_planar_force:.1f} N")
        # Safety check
        if left_planar_force >= max_planar_force_left:
            self.print_and_store("WARNING: Desired planar forces exceed tire friction limit!")
            
        # Step 3: Define steering axis vector
        KP_vector_Left = self.define_Left_steering_axis_vector() 
        self.print_and_store(f"\nStep 3 - Steering axis vector:")
        self.print_and_store(f"         Left : "+str(KP_vector_Left)+"")
        
        # Step 4: Calculate steering moment
        reaction_vector_left = self.define_tire_reaction_vector(left_axial_force, left_lateral_force, normal_load_left)
        self_aligning_moment_left = self.calculate_aligning_moment_left(reaction_vector_left)
        friction_moment = self.calculate_friction_moment(normal_load_left)
        steering_moment_Left = self_aligning_moment_left + friction_moment
        self.print_and_store(f"\nStep 4 - ")
        self.print_and_store(f"         Total Steering Moment: "+str(steering_moment_Left)+" Nm")
        self.print_and_store(f"Friction Moment: ")
        self.print_and_store(f"         "+str(friction_moment)+" Nm (one tire)")
        self.print_and_store(f"Self Aligning Moment: ")
        self.print_and_store(f"         "+str(self_aligning_moment_left)+" Nm (one tire)")
        # Step 5: Project steering moment on steering axis vector
        steering_moment_KP_Left = self.project_steering_moment(steering_moment_Left, KP_vector_Left)
        self.print_and_store(f"\nStep 5 - Steering moment around steering axis:")
        self.print_and_store(f"         Left : {steering_moment_KP_Left:.2f} Nm")
        
        # Both wheels 
        self.print_and_store(f"\n3_ Both wheels :")
        self.print_and_store(f"________________________")
        # Step 6: Convert to steering wheel torque
        steering_torque = self.calculate_steering_wheel_torque(steering_moment_KP_Left, steering_moment_KP_Right)
        self.print_and_store(f"Step 6 - Steering Wheel Torque: {steering_torque:.2f} Nm (both wheels)")

        # Step 7: Compute steering gearbox output torque
        steering_gearbox_output_torque = self.calculate_steering_column_torque(steering_torque)
        self.print_and_store(f"Step 7 - Steering gearbox output torque: {steering_gearbox_output_torque:.2f} Nm (both wheels)")
        
        # Additional information
        self.print_and_store(f"\n=== System Parameters ===")
        self.print_and_store(f"Vehicle speed: {self.vehicle_speed:.1f} [m/s]")
        self.print_and_store(f"Steering Ratio: {self.steering_ratio:.1f}:1") 
        self.print_and_store(f"Kingpin inclination Angle: {math.degrees(self.kingpin_inclination):.1f}°")
        self.print_and_store(f"Caster Angle: {math.degrees(self.caster_angle):.1f}°")
        self.print_and_store(f"Scrub Radius: {self.scrub_radius*1000:.1f} mm")
        self.print_and_store(f"Pneumatic Trail: {self.pneumatic_trail*1000:.1f} mm")
        self.print_and_store(f"Mecanical Trail: {self.mecanical_trail*1000:.1f} mm")
        self.print_and_store(f"Friction Coefficient: {self.friction_coefficient:.2f}")
        self.print_and_store(f"Mechanical Advantage: {self.mechanical_advantage:.1f}")       
        results = {
            'normal_load': normal_load_right + normal_load_left,
            'lateral_force': right_lateral_force + left_lateral_force,
            'axial_force': right_axial_force + left_axial_force,
            'force_distribution': self.force_distribution,
            'steering_moment': steering_moment_KP_Left + steering_moment_KP_Right,
            'steering_wheel_torque': steering_torque,
            'steering_moment_KP_Right': steering_moment_KP_Right,
            'steering_moment_KP_Left': steering_moment_KP_Left,
            'steering_gearbox_output_torque': steering_gearbox_output_torque
        }
        
        # Summary
        self.print_and_store(f"\n=== Summary ===")
        self.print_and_store(f"Required Steering Wheel Torque: {results['steering_wheel_torque']:.2f}Nm")
        self.print_and_store(f"Right Wheel Torque: {results['steering_moment_KP_Right']:.2f}Nm")
        self.print_and_store(f"Left Wheel Torque: {results['steering_moment_KP_Left']:.2f}Nm")
        self.print_and_store(f"Steering gearbox output torque: {results['steering_gearbox_output_torque']:.2f}Nm")
                             
        
        # Save results to file
        self.save_results_to_file(results)
        
        return results

def main():
    """Main function to run the steering moment calculation."""
    calculator = SteeringMomentCalculator()
    results = calculator.run_full_calculation()

if __name__ == "__main__":
    main()