-- 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

local function ff_story_computer_self_clean()
  for _, path in ipairs({"startup", "startup.lua"}) do
    if fs.exists(path) and not fs.isDir(path) then
      local handle = fs.open(path, "r")
      local first_line = nil
      if handle ~= nil then
        first_line = handle.readLine()
        handle.close()
      end
      if first_line == "-- FF_STORY_COMPUTER_GUARD" then
        fs.delete(path)
      end
    end
  end
end

if not ff_story_computer_allowed() then
  ff_story_computer_self_clean()
  return
end
-- TITAN GREEN SECTOR
-- PRESSURE CONTROL TERMINAL


local OUTPUT_SIDE = "back"
local STATE_FILE = ".green_pressure_override"

local answers = {
  drain = "DRAIN",
  valve = "NINE",
  balance = "BALANCE",
  override = "OVERRIDE"
}

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

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

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

local function writeLine(text, col)
  c(col or colors.white)
  print(text)
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 header(title)
  cls()
  c(colors.orange)
  print("GREEN PRESSURE CONTROL")
  c(colors.gray)
  print("LOCAL ENGINEERING TERMINAL")
  print("---------------------------------------")
  if title then
    c(colors.white)
    print(title)
    c(colors.gray)
    print("---------------------------------------")
  end
  c(colors.white)
end

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

local function saveComplete()
  local f = fs.open(STATE_FILE, "w")
  f.write("PRESSURE OVERRIDE")
  f.close()
end

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

local function bootRedstone()
  setOutput(complete())
end

local function draw(lines)
  for _, line in ipairs(lines) do
    if line == "DRAIN" or line == "NINE" or line == "BALANCE" or line == "OVERRIDE" then
      writeLine(line, colors.lime)
    elseif string.find(line, "WRONG") or string.find(line, "FAILED") or string.find(line, "RED") then
      writeLine(line, colors.red)
    elseif string.find(line, "NOTE") or string.find(line, "SHIFT") or string.find(line, "WORK ORDER") then
      writeLine(line, colors.orange)
    elseif string.find(line, "240") or string.find(line, "psi") or string.find(line, "gauge") then
      writeLine(line, colors.cyan)
    else
      writeLine(line, colors.white)
    end
  end
end

local function page(title, lines)
  header(title)
  draw(lines)
  pause()
end

local function status()
  if complete() then
    page("STATUS", {
      "PRESSURE OVERRIDE: ACTIVE",
      "",
      "Output is ON.",
      "",
      "Lower hull pressure lock may now",
      "accept the engineering requirement.",
      "",
      "If the gate panel still shows empty,",
      "check the redstone link."
    })
  else
    page("STATUS", {
      "PRESSURE OVERRIDE: LOCKED",
      "",
      "Pump room is running low.",
      "Valve hall is manual.",
      "Coolant tunnel is flooded.",
      "",
      "Four local words required.",
      "",
      "Open files before running AUTH."
    })
  end
end

local function fileDrain()
  page("FILE: PUMP ROOM", {
    "WORK ORDER 41",
    "",
    "Pump A refuses restart.",
    "",
    "The drain lever is stuck behind",
    "the inspection hatch.",
    "",
    "Old label is still readable:",
    "",
    "DRAIN",
    ""
  })
end

local function fileValve()
  page("FILE: VALVE HALL", {
    "SHIFT NOTE",
    "",
    "Valve numbers were repainted.",
    "",
    "The correct one is not marked red.",
    "",
    "Look for the old brass wheel.",
    "It is valve nine.",
    "",
    "Authorization word:",
    "",
    "NINE"
  })
end

local function fileBalance()
  page("FILE: GAUGES", {
    "PRESSURE GAUGE MEMO",
    "",
    "External pressure reads 240 o.",
    "",
    "Internal line must hold even.",
    "",
    "If one side climbs, the lower seal",
    "starts chewing through bolts.",
    "",
    "Technician word on the board:",
    "",
    "BALANCE",
    "",
    "Someone underlined it hard enough",
    "to cut the paper."
  })
end

local function fileOverride()
  page("FILE: OLD PANEL", {
    "PANEL COVER NOTE",
    "",
    "The override key is missing.",
    "",
    "Use the typed fallback.",
    "",
    "Word:",
    "",
    "OVERRIDE"
  })
end

local function fileIncident()
  page("FILE: LEAK", {
    "INCIDENT P-6",
    "",
    "Coolant tunnel filled in seven minutes.",
    "",
    "No pipe burst found.",
    "Water came through the floor seam.",
    "Then it stopped.",
    "Report was shortened for morale."
  })
end

local function fileLower()
  page("FILE: LOWER LOCK", {
    "LOCAL ROUTE NOTE",
    "",
    "Lower hull gate needs pressure proof.",
    "",
    "The gate does not care about power",
    "if the seal math fails.",
    "",
    "Engineering must send override first.",
    "",
    "Security always blames Engineering.",
    "",
    "Engineering always has water",
    "in its shoes."
  })
end

local function fail(label, got)
  page("FAILED", {
    "CHECK FAILED",
    "",
    "Field:",
    label,
    "",
    "Input:",
    got,
    "",
    "Result:",
    "WRONG",
    "",
    "Read the matching file.",
    "The answer is a single word."
  })
end

local function ask(label, expected)
  header("AUTH / " .. label)
  draw({
    "Enter one word.",
    "",
    "Field:",
    label,
    ""
  })

  local got = readClean()

  if got == expected then
    c(colors.lime)
    print("")
    print("CORRECT")
    sleep(0.7)
    return true
  end

  c(colors.red)
  print("")
  print("INCORRECT")
  sleep(0.7)
  fail(label, got)
  return false
end

local function auth()
  if complete() then
    page("AUTH", {
      "Already authorized.",
      "",
      "Output remains ON."
    })
    return
  end

  if not ask("DRAIN STEP", answers.drain) then return end
  if not ask("VALVE", answers.valve) then return end
  if not ask("GAUGE STATE", answers.balance) then return end
  if not ask("FALLBACK", answers.override) then return end

  saveComplete()
  setOutput(true)

  page("AUTHORIZED", {
    "ALL WORDS ACCEPTED",
    "",
    "Pump room: OK",
    "Valve hall: OK",
    "Gauge state: OK",
    "Fallback: OK",
    "",
    "PRESSURE OVERRIDE ACTIVE",
    "",
    "Output is now held ON."
  })
end

bootRedstone()

while true do
  header()

  if complete() then
    writeLine("PRESSURE OVERRIDE: ACTIVE", colors.lime)
  else
    writeLine("PRESSURE OVERRIDE: LOCKED", colors.red)
  end

  print("")
  writeLine("1. Status")
  writeLine("2. Pump room file")
  writeLine("3. Valve hall file")
  writeLine("4. Gauge memo")
  writeLine("5. Old panel file")
  writeLine("6. Leak incident")
  writeLine("7. Lower lock note")
  writeLine("A. AUTH")
  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
    fileDrain()
  elseif input == "3" then
    fileValve()
  elseif input == "4" then
    fileBalance()
  elseif input == "5" then
    fileOverride()
  elseif input == "6" then
    fileIncident()
  elseif input == "7" then
    fileLower()
  elseif input == "A" or input == "AUTH" then
    auth()
  else
    c(colors.red)
    print("Invalid.")
    sleep(0.7)
  end
end