-- Mekanism Fusion Reactor Control & Automation Script
local reactor = peripheral.wrap("logicAdapter_0") -- Change to your peripheral name
local monitor = peripheral.wrap("monitor_0")      -- Change to your monitor name (Optional)

-- SAFETY LIMITS
local MAX_PLASMA_TEMP = 400000000   -- Max safe plasma temp in Kelvin
local TARGET_TEMP = 300000000       -- Target plasma temp for steady state
local SAFE_START_TEMP = 50000000    -- Minimum temp to start increasing fuel

-- In mB/t (Min/Max injection rates for Mekanism)
local MIN_INJECTION_RATE = 2
local MAX_INJECTION_RATE = 98

-- Helper function to print to terminal/monitor
local function displayStatus(msg)
    print(msg)
    if monitor then
        monitor.clear()
        monitor.setCursorPos(1, 1)
        monitor.write(msg)
    end
end

-- Main Control Loop
while true do
    if reactor then
        local isIgnited = reactor.isIgnited()
        local plasmaTemp = reactor.getTemperatureInKelvin()
        local currentInjection = reactor.getBurnRate()
        
        displayStatus("Reactor Ignited: " .. tostring(isIgnited))
        
        if isIgnited then
            -- SAFETY SHUTDOWN if Plasma Temp exceeds limits
            if plasmaTemp > MAX_PLASMA_TEMP then
                reactor.activateReactor(false) -- Turns off the reactor
                displayStatus("EMERGENCY SHUTDOWN: Temp too high!")
                
            -- AUTOMATE INJECTION RATE based on temperature
            elseif plasmaTemp < TARGET_TEMP then
                -- Ramp up fuel if safe
                if currentInjection < MAX_INJECTION_RATE then
                    reactor.setBurnRate(currentInjection + 2)
                end
            elseif plasmaTemp > TARGET_TEMP then
                -- Reduce fuel if too hot
                if currentInjection > MIN_INJECTION_RATE then
                    reactor.setBurnRate(currentInjection - 2)
                end
            end
        else
            -- Auto-ignite if temperature is within safe parameters
            if plasmaTemp > SAFE_START_TEMP then
                reactor.activateReactor(true)
                displayStatus("Igniting reactor...")
            else
                displayStatus("Reactor cold. Waiting for laser ignition...")
            end
        end
    else
        displayStatus("Error: Logic Adapter not found.")
    end

    os.sleep(5) -- Update every 5 seconds
end