-- Mekanism Fusion Reactor Super Monitor (Table Fixed Version)
local reactor = peripheral.find("fusionReactorLogicAdapter") or peripheral.find("fusion_reactor_logic_adapter")
local monitor = peripheral.find("monitor")

if not reactor then
    error("Error: Fusion Reactor Logic Adapter not found!")
end

if not monitor then
    error("Error: Monitor not found! Check your wired modems.")
end

-- ==================================================
-- CONFIGURATION
-- ==================================================
local TARGET_INJECTION_RATE = 128  
local LOOP_TICK_RATE = 1.0       
local TEXT_SCALE = 1.0  -- Adjust this if text overflows your screen layout

print("=== Fusion Reactor Super Monitor Initialized ===")

monitor.setTextScale(TEXT_SCALE)
local origTerm = term.current()

if reactor.setInjectionRate then
    reactor.setInjectionRate(TARGET_INJECTION_RATE)
end

-- Helper to safely unpack Mekanism's gas/chemical objects if they are returned as a table
local function parseGasAmount(gasData)
    if not gasData then return 0 end
    if type(gasData) == "number" then return gasData end
    if type(gasData) == "table" then
        return gasData.amount or gasData.amount or 0
    end
    return 0
end

-- Helper to safely format massive power numbers into readable strings
local function formatPower(num)
    if not num or type(num) ~= "number" then return "0 FE" end
    if num >= 1000000000 then return string.format("%.2f BFE", num / 1000000000)
    elseif num >= 1000000 then return string.format("%.2f MFE", num / 1000000)
    elseif num >= 1000 then return string.format("%.2f kFE", num / 1000)
    else return string.format("%d FE", num) end
end

while true do
    -- 1. Gather Telemetry Data Safely
    local isBurning = false
    local plasmaTemp = 0
    
    if reactor.getPlasmaTemperature then
        pcall(function() plasmaTemp = reactor.getPlasmaTemperature() end)
        if plasmaTemp > 0 then isBurning = true end
    elseif reactor.getPlasmaTemp then
        pcall(function() plasmaTemp = reactor.getPlasmaTemp() end)
        if plasmaTemp > 0 then isBurning = true end
    end
    
    -- Fuel Metrics (Safely unpack tables if they exist)
    local rawDeuterium = 0
    if reactor.getDeuterium then 
        pcall(function() rawDeuterium = reactor.getDeuterium() end)
    elseif reactor.getDeuteriumFilled then 
        pcall(function() rawDeuterium = reactor.getDeuteriumFilled() end) 
    end
    local deuterium = parseGasAmount(rawDeuterium)
    
    local rawTritium = 0
    if reactor.getTritium then 
        pcall(function() rawTritium = reactor.getTritium() end)
    elseif reactor.getTritiumFilled then 
        pcall(function() rawTritium = reactor.getTritiumFilled() end) 
    end
    local tritium = parseGasAmount(rawTritium)

    -- Power Metrics (Protected to prevent the "0 arguments" crash)
    local energyGen = 0
    local success = false
    
    if reactor.getPassiveGeneration then
        success, result = pcall(function() return reactor.getPassiveGeneration() end)
        if success and type(result) == "number" then energyGen = result end
    end
    
    -- If getPassiveGeneration failed, try fallback methods
    if energyGen == 0 and reactor.getProduced then
        success, result = pcall(function() return reactor.getProduced() end)
        if success and type(result) == "number" then energyGen = result end
    end
    
    if energyGen == 0 and reactor.getProductionRate then
        success, result = pcall(function() return reactor.getProductionRate() end)
        if success and type(result) == "number" then energyGen = result end
    end
    
    -- Energy Storage Buffers
    local energyBuffer = 0
    if reactor.getEnergy then pcall(function() energyBuffer = reactor.getEnergy() end) end
    
    local maxEnergy = 0
    if reactor.getMaxEnergy then pcall(function() maxEnergy = reactor.getMaxEnergy() end) end

    -- 2. Render to Monitor Screen
    term.redirect(monitor)
    term.clear()
    term.setCursorPos(1,1)
    
    term.setTextColor(colors.yellow)
    print("=========================================")
    print("         FUSION CORE METRICS             ")
    print("=========================================")
    
    -- Status Bar
    term.setTextColor(colors.white)
    write(" Core Status:      ")
    if isBurning then 
        term.setTextColor(colors.green)
        print("ONLINE / BURNING")
    else 
        term.setTextColor(colors.red)
        print("READY / NO PLASMA")
    end
    
    -- Plasma Temperature
    term.setTextColor(colors.white)
    write(" Plasma Temp:     ")
    term.setTextColor(colors.orange)
    print(string.format(" %.2f K", plasmaTemp))
    
    print(" ") -- Spacer

    -- Fuel Statistics
    term.setTextColor(colors.yellow)
    print(" --- FUEL LEVELS ---")
    term.setTextColor(colors.white)
    
    write(" Deuterium:       ")
    term.setTextColor(colors.blue)
    print(string.format(" %d mB", deuterium))
    
    term.setTextColor(colors.white)
    write(" Tritium:         ")
    term.setTextColor(colors.green)
    print(string.format(" %d mB", tritium))
    
    term.setTextColor(colors.white)
    write(" Injection Rate:  ")
    term.setTextColor(colors.cyan)
    print(" " .. TARGET_INJECTION_RATE .. " mB/t")
    
    print(" ") -- Spacer

    -- Power Generation Details
    term.setTextColor(colors.yellow)
    print(" --- POWER MATRIX ---")
    term.setTextColor(colors.white)
    
    write(" Production Rate: ")
    term.setTextColor(colors.magenta)
    print(" " .. formatPower(energyGen) .. "/t")
    
    term.setTextColor(colors.white)
    write(" Internal Buffer: ")
    term.setTextColor(colors.lightBlue)
    print(" " .. formatPower(energyBuffer) .. " / " .. formatPower(maxEnergy))

    term.setTextColor(colors.yellow)
    print("=========================================")

    -- Enforce injection rate config safety
    if isBurning and reactor.setInjectionRate then
        reactor.setInjectionRate(TARGET_INJECTION_RATE)
    end

    -- Loop pacing return
    term.redirect(origTerm)
    sleep(LOOP_TICK_RATE)
end
