import ansys.motorcad.core as MCAD
import os
def simularMCAD(mdbName, iteration):
    working_folder = os.getcwd()

    mcad = MCAD.MotorCAD()
    
    motPath = os.path.join(working_folder, "motores", f"{mdbName}.mot")
    mcad.set_variable("MessageDisplayState", 2)
    mcad.set_visible(True)
    mcad.load_from_file(motPath)
    print("Motor file loaded:", motPath)

    # Simulation config
    mcad.set_variable("MagneticThermalCoupling", 0)
    mcad.set_variable("CurrentDefinition", 1)
    mcad.set_variable("BackEMFCalculation", False)
    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", True)

    # Operation point
    mcad.set_variable("ShaftSpeed", 1000)
    mcad.set_variable("RMSCurrent", 0.95)
    mcad.set_variable("DCBusVoltage", 400)
    mcad.set_variable("PhaseAdvance", 0)
 
    # Material
    mcad.import_solid_material("C:\\Users\\promerogomb\\Desktop\\fluxcontrol\\PLACond.mdb", "PLACond")
    mcad.set_component_material("Rotor Lam (Back Iron)", "PLACond")

    # Ejecución y resultados
    mcad.do_magnetic_calculation()
    
    E = mcad.get_variable("RMSBackEMFLine")
    I = mcad.get_variable("RMSPhaseCurrent")
    f = mcad.get_variable("FundamentalFrequency")

    resultsPath = os.path.join(working_folder, "results", f"results_{iteration}.txt")
    try:
        mcad.export_results("EMagnetic", resultsPath)
        print("Results successfully exported.")
    except mcad.MotorCADError:
        print("Results failed to export.")
        
    return E, I, f