-- FF_STORY_COMPUTER_GUARD
local function ff_story_computer_allowed()
  local label = os.getComputerLabel and os.getComputerLabel() or nil
  return fs.exists(".ff_story_computer")
    or fs.exists(".ff_titan_computer")
    or fs.exists(".ff_titan_program_id")
    or fs.exists(".ff_titan_allow_autoinstall")
    or fs.exists(".ff_titan_allow_autorun")
    or (label ~= nil and string.sub(string.lower(label), 1, 9) == "ff_titan:")
end

if not ff_story_computer_allowed() then
  return
end
-- TITAN GREEN SECTOR
-- RED LEVEL ELEVATOR UNLOCK BOARD
-- Save as: startup
--
-- Attach monitor if possible.
--
-- Inputs:
-- left   = pressure override
-- right  = quarantine release
-- back   = black clearance
--
-- Output:
-- bottom = red level elevator unlock
--
-- Suggested command block on bottom output:
-- setblock -454 74 -133 create:elevator_contact[facing=north] replace

local PRESSURE_SIDE = "left"
local QUARANTINE_SIDE = "right"
local SECURITY_SIDE = "back"
local OUTPUT_SIDE = "bottom"

local STATE_FILE = ".green_red_elevator_unlocked"
local FINAL_WORD = "DESCEND"

local function findMonitor()
  local mon = peripheral.find("monitor")
  if mon then
    mon.setTextScale(0.5)
    return mon
  end
  return nil
end

local monitor = findMonitor()

local function useTerminal()
  if term.native then
    term.redirect(term.native())
  end
end

local function useMonitor()
  if monitor then
    term.redirect(monitor)
  end
end

local function hasColor()
  return term.isColor and term.isColor()
end

local function c(col)
  if hasColor() then term.setTextColor(col) end
end

local function bg(col)
  if hasColor() then term.setBackgroundColor(col) end
end

local function cls()
  bg(colors.black)
  term.clear()
  term.setCursorPos(1, 1)
end

local function writeLine(text, col)
  c(col or colors.white)
  print(text)
end

local function at(x, y, text, col)
  term.setCursorPos(x, y)
  c(col or colors.white)
  write(text)
end

local function center(y, text, col)
  local w = term.getSize()
  local x = math.floor((w - #text) / 2) + 1
  if x < 1 then x = 1 end
  at(x, y, text, col)
end

local function hline(y, col)
  local w = term.getSize()
  at(1, y, string.rep("-", w), col or colors.gray)
end

local function readClean()
  c(colors.white)
  write("> ")
  local s = read() or ""
  s = string.upper(s)
  s = string.gsub(s, "^%s+", "")
  s = string.gsub(s, "%s+$", "")
  return s
end

local function pause()
  c(colors.gray)
  print("")
  print("[key] back")
  os.pullEvent("key")
end

local function unlocked()
  return fs.exists(STATE_FILE)
end

local function saveUnlocked()
  local f = fs.open(STATE_FILE, "w")
  f.write("RED ELEVATOR UNLOCKED")
  f.close()
end

local function setOutput(on)
  redstone.setOutput(OUTPUT_SIDE, on)
end

local function bootOutput()
  setOutput(unlocked())
end

local function pressureOK()
  return redstone.getInput(PRESSURE_SIDE)
end

local function quarantineOK()
  return redstone.getInput(QUARANTINE_SIDE)
end

local function securityOK()
  return redstone.getInput(SECURITY_SIDE)
end

local function allOK()
  return pressureOK() and quarantineOK() and securityOK()
end

local function drawMonitor()
  if not monitor then return end

  useMonitor()
  cls()

  local w, h = term.getSize()

  center(1, "RED LEVEL ELEVATOR ROUTE", colors.red)
  center(2, "TITAN GREEN SECTOR / LOWER DESCENT BOARD", colors.gray)
  hline(3, colors.red)

  at(2, 5, "BLACKSITE LOCKDOWN", colors.red)
  at(2, 6, "Lower access remains physically sealed.", colors.gray)
  at(2, 7, "This board only publishes elevator route.", colors.gray)

  at(2, 9, "FACILITY INTEGRITY", colors.gray)
  at(28, 9, "78%", colors.white)

  at(2, 10, "EXTERNAL PRESSURE", colors.gray)
  at(28, 10, "240 o", colors.white)

  at(2, 11, "CONTAINMENT", colors.gray)
  at(28, 11, "RAGNAROK", colors.red)

  at(2, 12, "RED ELEVATOR STOP", colors.gray)
  if unlocked() then
    at(28, 12, "PUBLISHED", colors.lime)
  else
    at(28, 12, "ABSENT", colors.red)
  end

  at(2, 14, "ROUTE REQUIREMENTS", colors.white)

  at(4, 16, "PRESSURE OVERRIDE", colors.white)
  at(31, 16, pressureOK() and "[X]" or "[ ]", pressureOK() and colors.lime or colors.red)

  at(4, 17, "QUARANTINE RELEASE", colors.white)
  at(31, 17, quarantineOK() and "[X]" or "[ ]", quarantineOK() and colors.lime or colors.red)

  at(4, 18, "BLACK CLEARANCE", colors.white)
  at(31, 18, securityOK() and "[X]" or "[ ]", securityOK() and colors.lime or colors.red)

  at(2, 20, "ROUTE BOARD NOTE", colors.orange)

  if unlocked() then
    at(4, 22, "Red elevator stop is now available.", colors.lime)
    at(4, 23, "Iris gate remains locked below.", colors.red)
  elseif allOK() then
    at(4, 22, "All wing inputs present.", colors.lime)
    at(4, 23, "Use terminal and enter final word.", colors.white)
  else
    at(4, 22, "Input chain incomplete.", colors.red)
    at(4, 23, "Solve green sector wing terminals.", colors.white)
  end

  if w > 58 then
    at(48, 5, "LOCAL EVENTS", colors.red)
    at(48, 7, "13:22 pressure board accessed", colors.white)
    at(48, 8, "13:31 sample freezer ping", colors.orange)
    at(48, 9, "13:37 black clearance request", colors.white)
    at(48, 10, "13:41 lower bell heard once", colors.red)
    at(48, 11, "13:48 red route map hidden", colors.red)
    at(48, 12, "13:58 elevator contact absent", colors.red)
    at(48, 13, "14:02 route board waiting", colors.white)

    at(48, 16, "OUTPUT TARGET", colors.gray)
    at(48, 17, "-454 74 -133", colors.white)
    at(48, 18, "create:elevator_contact", colors.white)
    at(48, 19, "facing=north", colors.white)

    at(48, 22, "IRIS GATE:", colors.gray)
    at(60, 22, "NOT CONTROLLED HERE", colors.red)
  end

  hline(h, colors.red)
end

local function terminalHeader(title)
  useTerminal()
  cls()
  c(colors.red)
  print("RED LEVEL ELEVATOR ROUTE")
  c(colors.gray)
  print("GREEN SECTOR ROUTE BOARD")
  print("---------------------------------------")
  if title then
    c(colors.white)
    print(title)
    c(colors.gray)
    print("---------------------------------------")
  end
  c(colors.white)
end

local function status()
  terminalHeader("STATUS")

  if unlocked() then
    writeLine("RED ELEVATOR STOP: PUBLISHED", colors.lime)
  else
    writeLine("RED ELEVATOR STOP: ABSENT", colors.red)
  end

  print("")
  writeLine("Pressure override:  " .. (pressureOK() and "OK" or "MISSING"), pressureOK() and colors.lime or colors.red)
  writeLine("Quarantine release: " .. (quarantineOK() and "OK" or "MISSING"), quarantineOK() and colors.lime or colors.red)
  writeLine("Black clearance:    " .. (securityOK() and "OK" or "MISSING"), securityOK() and colors.lime or colors.red)

  print("")

  if allOK() and not unlocked() then
    writeLine("All inputs present.", colors.lime)
    writeLine("Run UNLOCK.")
  elseif not unlocked() then
    writeLine("Green wing work incomplete.", colors.orange)
  else
    writeLine("Output is held ON.", colors.lime)
    writeLine("Iris gate is still separate.", colors.red)
  end

  pause()
end

local function localFile()
  terminalHeader("LOCAL FILE")

  writeLine("RED ELEVATOR ROUTE")
  print("")
  writeLine("This board does not open the iris gate.")
  print("")
  writeLine("It publishes the lower elevator stop")
  writeLine("after green sector requirements pass.")
  print("")
  writeLine("Required inputs:")
  writeLine("pressure override")
  writeLine("quarantine release")
  writeLine("black clearance")
  print("")
  writeLine("Final word:")
  print("")
  writeLine("DESCEND", colors.lime)

  pause()
end

local function elevatorNote()
  terminalHeader("ELEVATOR NOTE")

  writeLine("After route unlock:")
  print("")
  writeLine("Use the elevator control.")
  print("")
  writeLine("MIDDLE MOUSE BUTTON", colors.cyan)
  writeLine("or SCROLL WHEEL", colors.cyan)
  writeLine("selects the floor.", colors.cyan)
  print("")
  writeLine("RIGHT CLICK", colors.cyan)
  writeLine("confirms the selected floor.", colors.cyan)
  print("")
  writeLine("If red floor does not appear,")
  writeLine("the elevator contact was not placed.")
  print("")
  writeLine("The iris gate opens later, below.")

  pause()
end

local function unlockRoute()
  if unlocked() then
    terminalHeader("UNLOCK")
    writeLine("Route already published.", colors.lime)
    pause()
    return
  end

  terminalHeader("UNLOCK")

  if not allOK() then
    writeLine("Route denied.", colors.red)
    print("")
    writeLine("Missing input:")
    if not pressureOK() then writeLine("PRESSURE", colors.red) end
    if not quarantineOK() then writeLine("QUARANTINE", colors.red) end
    if not securityOK() then writeLine("BLACK CLEARANCE", colors.red) end
    pause()
    return
  end

  writeLine("All inputs present.", colors.lime)
  print("")
  writeLine("Enter final word.")
  print("")

  local got = readClean()

  if got ~= FINAL_WORD then
    c(colors.red)
    print("")
    print("INCORRECT")
    sleep(0.8)

    terminalHeader("DENIED")
    writeLine("Input:", colors.gray)
    writeLine(got)
    print("")
    writeLine("Result:", colors.gray)
    writeLine("WRONG", colors.red)
    print("")
    writeLine("Check the local file.")
    pause()
    return
  end

  c(colors.lime)
  print("")
  print("CORRECT")
  sleep(0.8)

  saveUnlocked()
  setOutput(true)

  terminalHeader("ROUTE PUBLISHED")
  writeLine("RED ELEVATOR STOP UNLOCKED", colors.lime)
  print("")
  writeLine("Output is now held ON.")
  print("")
  writeLine("Use this output to place:")
  c(colors.gray)
  print("create:elevator_contact[facing=north]")
  print("at -454 74 -133")
  c(colors.white)
  print("")
  writeLine("This does not open the iris gate.", colors.red)

  pause()
end

bootOutput()

while true do
  drawMonitor()

  useTerminal()
  terminalHeader()

  if unlocked() then
    writeLine("RED ELEVATOR STOP: PUBLISHED", colors.lime)
  else
    writeLine("RED ELEVATOR STOP: ABSENT", colors.red)
  end

  print("")
  writeLine("1. Status")
  writeLine("2. Local file")
  writeLine("3. Elevator note")
  writeLine("U. UNLOCK")
  writeLine("Q. Close")
  print("")

  local input = readClean()

  if input == "Q" or input == "QUIT" or input == "EXIT" then
    cls()
    writeLine("SESSION CLOSED", colors.gray)
    return
  elseif input == "1" then
    status()
  elseif input == "2" then
    localFile()
  elseif input == "3" then
    elevatorNote()
  elseif input == "U" or input == "UNLOCK" then
    unlockRoute()
  else
    c(colors.red)
    print("Invalid.")
    sleep(0.7)
  end
end