local reactor = peripheral.find("fusionReactorLogicAdapter")
local monitor = peripheral.find("monitor")

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

-- FIXED CODES & TARGET MARGINS
local TARGET_EFFICIENCY = 90   -- 90%+ Efficiency guarantees you are within 5 of the TR
local ERROR_THRESHOLD = 5      -- Instantly halts and bleeds off fuel at 5% error
local LOOP_DELAY = 5.2          -- Fixed tick alignment for stability calculations

local lastEfficiency = 0
local currentDirection = 2      

local function updateDisplay(eff, err, status, color)
    if not monitor then return end
    pcall(function()
        monitor.setTextScale(1)
        monitor.clear()
        monitor.setBackgroundColor(colors.gray)
        monitor.setTextColor(colors.white)
        monitor.setCursorPos(1, 1)
        monitor.clearLine()
        monitor.write("   BFR ADAPTIVE CONTROLLER   ")
        
        monitor.setBackgroundColor(colors.black)
        monitor.setCursorPos(1, 3)
        monitor.setTextColor(colors.lightGray)
        monitor.write("Current Eff: ")
        monitor.setTextColor(eff >= TARGET_EFFICIENCY and colors.green or colors.yellow)
        monitor.write(string.format("%.1f%%", eff))
        
        monitor.setCursorPos(1, 4)
        monitor.setTextColor(colors.lightGray)
        monitor.write("Error Level: ")
        monitor.setTextColor(err >= ERROR_THRESHOLD and colors.red or colors.green)
        monitor.write(string.format("%d%%", err))
        
        monitor.setCursorPos(1, 6)
        monitor.setBackgroundColor(color)
        monitor.setTextColor(colors.black)
        monitor.clearLine()
        monitor.write(" STATUS: " .. status)
        monitor.setBackgroundColor(colors.black)
    end)
end

print("=== BFR Proximity Controller Running ===")

while true do
    -- Telemetry checks wrapper
    local ok1, errLevel = pcall(function() return reactor.getErrorLevel() end)
    local ok2, effLevel = pcall(function() return reactor.getEfficiency() / 100 end)
    
    local currentError = ok1 and errLevel or 0
    local currentEfficiency = ok2 and effLevel or 0
    
    -- 1. ERROR TRIGGER INTERCEPT (Triggers instantly at 5% error)
    if currentError >= ERROR_THRESHOLD then
        print("ALERT: Error reached 5%. Halting code and initiating safety bleed...")
        
        local savedRate = 2
        pcall(function() 
            local rate = reactor.getInjectionRate()
            if rate > 0 then savedRate = rate end
            reactor.setInjectionRate(0) -- Immediately dump fuel to cool down
        end)
        
        -- Lock execution here until error level drops below 5
        while currentError >= ERROR_THRESHOLD do
            updateDisplay(currentEfficiency, currentError, "ERROR PURGE (FUEL CUT)", colors.orange)
            print(string.format("Clearing core error... Current: %d%%", currentError))
            sleep(2)
            local s, e = pcall(function() return reactor.getErrorLevel() end)
            currentError = s and e or 0
        end
        
        print("Core clear (Error < 5%). Restoring fuel valves and restarting tracker.")
        pcall(function() reactor.setInjectionRate(savedRate) end)
        lastEfficiency = 0
        sleep(LOOP_DELAY)
    end

    -- 2. TARGET LOCK MATRIX
    if currentEfficiency >= TARGET_EFFICIENCY then
        -- You are verified to be within 5 units of TR. STOP changing values entirely to avoid overshooting.
        currentDirection = 0
        print("Success: Efficiency high. CR is within 5 of TR. Holding steady.")
    else
        -- If efficiency is low, track direction changes step-by-step
        local stepSize = 2
        if currentEfficiency < 40 then
            stepSize = 10 -- Speed up gap closure if wildly out of range
        end

        if lastEfficiency > 0 and currentEfficiency < lastEfficiency then
            -- Wrong way! Reverse vector
            if currentDirection >= 0 then
                currentDirection = -stepSize
            else
                currentDirection = stepSize
            end
            print("Efficiency dropping. Flipping correction push to: " .. currentDirection)
        else
            -- Right way or flat, maintain course pushing forward
            if currentDirection == 0 then
                currentDirection = stepSize -- Wake up from zero state
            elseif currentDirection > 0 then
                currentDirection = stepSize
            else
                currentDirection = -stepSize
            end
        end
        
        -- Safely submit velocity shift
        pcall(function() reactor.adjustReactivity(currentDirection) end)
    end

    -- Paint interface frames
    local statusText = (currentDirection == 0) and "TARGET LOCK (HOLDING)" or "TUNING STABILITY"
    local statusColor = (currentDirection == 0) and colors.green or colors.yellow
    
    updateDisplay(currentEfficiency, currentError, statusText, statusColor)
    print(string.format("Log -> Eff: %.1f%% | Err: %d%% | Shift: %d", currentEfficiency, currentError, currentDirection))
    
    lastEfficiency = currentEfficiency
    sleep(LOOP_DELAY)
end