-- Wrap the Reactor Logic Adapter peripheral
local reactor = peripheral.find("reactor_logic_adapter")

if not reactor then
    error("No Reactor Logic Adapter found! Check your connections.")
end

-- Configuration Settings
local TARGET_EFFICIENCY = 0.95 -- Aim for 95%+ efficiency
local ERROR_THRESHOLD = 50     -- SCRAM if error level hits 50%
local ADJUST_INTERVAL = 5.1    -- Reactor takes 5 seconds to stabilize after changes

-- Tracking states
local lastEfficiency = 0
local currentDirection = 2     -- Start by adjusting up (+2)

print("=== Better Fusion Reactor Stabiliser Active ===")

while true do
    -- 1. Safety First: Monitor Error Levels
    local currentError = reactor.get_error_level()
    print(string.format("Current Error: %d%%", currentError))
    
    if currentError >= ERROR_THRESHOLD then
        print("CRITICAL TRIGGER: Error threshold exceeded! Emergency SCRAM initiated.")
        reactor.setInjectionRate(0) -- Instantly cut fuel to prevent explosion
        break
    end

    -- 2. Read Current Performance
    local currentEfficiency = reactor.getEfficiency()
    print(string.format("Current Efficiency: %.1f%%", currentEfficiency * 100))

    -- 3. The Logic Engine: Only adjust if we are below our target efficiency
    if currentEfficiency < TARGET_EFFICIENCY then
        print("Efficiency low. Executing adjustment calculation...")
        
        -- If efficiency DROPPED compared to last check, we chose the wrong direction!
        if currentEfficiency < lastEfficiency then
            print("Efficiency dropping! Reversing search direction.")
            currentDirection = -currentDirection -- Flip positive to negative, or vice versa
        else
            print("Efficiency improving or stable. Maintaining direction.")
        end

        -- Apply the adjustment step to the Current Reactivity (CR)
        print("Modifying reactivity by: " .. currentDirection)
        reactor.adjust_activity(currentDirection)
    else
        print("Reactor is stable and highly efficient. Holding.")
    end

    -- Update memory state for the next check
    lastEfficiency = currentEfficiency

    print("---------------------------------------------")
    sleep(ADJUST_INTERVAL) -- Wait for the reactor's 5-second internal cooldown [1]
end