import ansys.motorcad.core as MCAD
import os
def simularMCAD(corriente, frecuencia, material, iteration):
    working_folder = os.getcwd()
    motPath = os.path.join(working_folder, "motores", f"{material}.mot")
    materialPath = os.path.join(working_folder, f"{material}.mdb")

    mcad = MCAD.MotorCAD()
    
    mcad.set_variable("MessageDisplayState", 2)
    mcad.set_visible(True)
    mcad.load_from_file(motPath)
    print("Archivo de motor cargado desde:", motPath)

    # Simulation config
    mcad.set_variable("DriveType_BPM", 0)
    mcad.set_variable("MagneticThermalCoupling", 0)
    mcad.set_variable("CurrentDefinition", 1)
    mcad.set_variable("BackEMFCalculation", True)
    mcad.set_variable("CoggingTorqueCalculation", False)
    mcad.set_variable("ElectromagneticForcesCalc_OC", False)
    mcad.set_variable("TorqueSpeedCalculation", False)
    mcad.set_variable("DemagnetizationCalc", False)
    mcad.set_variable("ElectromagneticForcesCalc_Load", False)
    mcad.set_variable("InductanceCalc", False)
    mcad.set_variable("BPMShortCircuitCalc", False)
    mcad.set_variable("TorqueCalculation", False)

    # Operation point
    polos = mcad.get_variable("Pole_Number")
    n = frecuencia * 60 / (polos/2)
    mcad.set_variable("ShaftSpeed", n)
    mcad.set_variable("RMSCurrent", corriente)
    mcad.set_variable("DCBusVoltage", 230)
    mcad.set_variable("PhaseAdvance", 0)
 
    # Material
    mcad.import_solid_material(materialPath, material)
    mcad.set_component_material("Rotor Lam (Back Iron)", material)
    print("Material importado desde:", materialPath)

    # Ejecución y resultados
    mcad.do_magnetic_calculation()
    
    E = mcad.get_variable("RmsBackEMFPhase")

    resultsPath = os.path.join(working_folder, "results", f"results_{iteration}.txt")
    mcad.export_results("EMagnetic", resultsPath)
    print("Resultados exportados a ", resultsPath)
        
    return E