-- 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
-- QUARANTINE LAB TERMINAL
-- Save as: startup
--
-- Output stays ON after success.
-- Wire OUTPUT_SIDE into lower gate progress system.

local OUTPUT_SIDE = "back"
local STATE_FILE = ".green_quarantine_release"

local answers = {
  filter = "FILTER",
  glass = "GLASS",
  cold = "COLD",
  release = "RELEASE"
}

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.lime)
  print("GREEN QUARANTINE LAB")
  c(colors.gray)
  print("LOCAL RESEARCH 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("QUARANTINE RELEASE")
  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 == "FILTER" or line == "GLASS" or line == "COLD" or line == "RELEASE" then
      writeLine(line, colors.lime)
    elseif string.find(line, "WRONG") or string.find(line, "RED") or string.find(line, "FAILED") then
      writeLine(line, colors.red)
    elseif string.find(line, "NOTE") or string.find(line, "LAB") or string.find(line, "SAMPLE") then
      writeLine(line, colors.orange)
    elseif string.find(line, "spore") or string.find(line, "mycelium") or string.find(line, "growth") then
      writeLine(line, colors.red)
    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", {
      "QUARANTINE RELEASE: ACTIVE",
      "",
      "Output is ON.",
      "",
      "Lower hull access panel may now",
      "accept the research requirement.",
      ""
    })
  else
    page("STATUS", {
      "QUARANTINE RELEASE: LOCKED",
      "",
      "Botany lab has trace growth.",
      "Sample freezer is sealed.",
      "Test chambers are not clean.",
      "",
      "Four local words required."
    })
  end
end

local function fileFilter()
  page("FILE: DECON FILTER", {
    "LAB NOTE",
    "",
    "Decon line keeps clogging.",
    "White threads in the filter mesh.",
    "",
    "Replacement label:",
    "",
    "FILTER",
    "",
    "The old one should be burned."
  })
end

local function fileGlass()
  page("FILE: OBSERVATION GLASS", {
    "SAMPLE ROOM NOTE",
    "",
    "Growth stops at the glass.",
    "Then resumes when no one watches.",
    "",
    "Security says that is impossible.",
    "Research says check the frame seal.",
    "",
    "Frame label:",
    "",
    "GLASS"
  })
end

local function fileCold()
  page("FILE: FREEZER", {
    "FREEZER LOG",
    "",
    "Sample tray 6 thawed overnight.",
    "",
    "Room stayed below target.",
    "",
    "Tray surface grew warm.",
    "",
    "The freezer seens to be working fine...",
    "",
    "Emergency word:",
    "",
    "COLD"
  })
end

local function fileRelease()
  page("FILE: RELEASE FORM", {
    "QUARANTINE FORM",
    "",
    "Release is not clearance.",
    "",
    "Release only tells the lower gate",
    "the lab has taken responsibility.",
    "",
    "That sentence made Legal unhappy.",
    "",
    "Stamped word:",
    "",
    "RELEASE",
    "It was stamped",
    "by hand, very hard..."
  })
end

local function fileBotany()
  page("FILE: BOTANY", {
    "BOTANY ROOM ENTRY",
    "",
    "Small colony found under tray rack."
  })
end

local function fileBodies()
  page("FILE: GREEN REMAINS", {
    "RESEARCH MEMO",
    "",
    "Human remains in green sector",
    "are not from the original breach."
  })
end

local function fileRed()
  page("FILE: RED ROUTE", {
    "LOCAL WARNING",
    "",
    "Red level samples are not archived here.",
    "The files were moved down.",
    "Then the route locked.",
    "",
    "Then someone moved files back up.",
    "Do NOT open red transfer crates."
  })
end

local function fail(label, got)
  page("FAILED", {
    "CHECK FAILED",
    "",
    "Field:",
    label,
    "",
    "Input:",
    got,
    "",
    "Result:",
    "WRONG",
    "",
    "Read the matching file.",
    "The answer stands alone."
  })
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 released.",
      "",
      "Output remains ON."
    })
    return
  end

  if not ask("DECON", answers.filter) then return end
  if not ask("BARRIER", answers.glass) then return end
  if not ask("FREEZER", answers.cold) then return end
  if not ask("FORM", answers.release) then return end

  saveComplete()
  setOutput(true)

  page("AUTHORIZED", {
    "ALL WORDS ACCEPTED",
    "",
    "Decon file: OK",
    "Barrier file: OK",
    "Freezer file: OK",
    "Release form: OK",
    "",
    "QUARANTINE RELEASE ACTIVE",
    "",
    "Output is now held ON."
  })
end

bootRedstone()

while true do
  header()

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

  print("")
  writeLine("1. Status")
  writeLine("2. Decon filter file")
  writeLine("3. Observation glass file")
  writeLine("4. Freezer file")
  writeLine("5. Release form")
  writeLine("6. Botany note")
  writeLine("7. Green remains memo")
  writeLine("8. Red route warning")
  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
    fileFilter()
  elseif input == "3" then
    fileGlass()
  elseif input == "4" then
    fileCold()
  elseif input == "5" then
    fileRelease()
  elseif input == "6" then
    fileBotany()
  elseif input == "7" then
    fileBodies()
  elseif input == "8" then
    fileRed()
  elseif input == "A" or input == "AUTH" then
    auth()
  else
    c(colors.red)
    print("Invalid.")
    sleep(0.7)
  end
end