-- 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
local NODE = "surface_security"

local palette = {
    bg = colors.black,
    title = colors.red,
    text = colors.white,
    muted = colors.gray,
    ok = colors.lime,
    warn = colors.orange,
    bad = colors.red,
    info = colors.cyan
}

local function set(c1, c2)
    term.setTextColor(c1 or palette.text)
    term.setBackgroundColor(c2 or palette.bg)
end

local function clear()
    set(palette.text, palette.bg)
    term.clear()
    term.setCursorPos(1, 1)
end

local function line(text, color)
    set(color or palette.text, palette.bg)
    print(text)
end

local function pause()
    set(palette.muted, palette.bg)
    print("")
    print("[ press any key ]")
    os.pullEvent("key")
end

local function header(name)
    clear()
    set(palette.title, palette.bg)
    print("[ TITAN // RESTRICTED TERMINAL ]")
    set(palette.muted, palette.bg)
    print("NODE: " .. name)
    print("STATUS: DEGRADED")
    print("ACCESS: LOCAL CACHE")
    print("--------------------------------------")
    set(palette.text, palette.bg)
end

local logs = {}

logs.surface_security = {
    name = "SURFACE SECURITY",
    menu = {
        {
            title = "Visitor Processing Notice",
            body = {
                "PUBLIC DESIGNATION: NONE",
                "COVER FUNCTION: OCEANIC LOGISTICS",
                "",
                "All civilian-facing staff are reminded that",
                "Lab T-14n does not exist outside approved",
                "Warium records.",
                "",
                "Visitors asking about the launch frame are",
                "to be redirected to Cargo Intake.",
                "",
                "Visitors asking why the island is armed are",
                "to be removed from the island."
            }
        },
        {
            title = "Albedo Contact Record",
            body = {
                "SURFACE MOTION DETECTED",
                "VESSEL CLASSIFICATION: UNLISTED",
                "BIOLOGICAL SIGNATURES: PRESENT",
                "",
                "ALBEDO COMMENT:",
                "\"The ocean was doing such a good job",
                "keeping people away. Then you arrived.\""
            }
        },
        {
            title = "Security Result For Failure",
            body = {
                "FAILURE TO MAINTAIN COVER:",
                "HOSTILE CLASSIFICATION",
                "",
                "FAILURE TO MAINTAIN ISLAND PERIMETER:",
                "HOSTILE CLASSIFICATION",
                "",
                "FAILURE TO REPORT ALBEDO CONTACT:",
                "HOSTILE CLASSIFICATION",
                "",
                "NOTE:",
                "The system appears to prefer simple policies."
            }
        }
    }
}

logs.nemesis_legacy = {
    name = "NEMESIS LEGACY CONTROL",
    menu = {
        {
            title = "Orbital Link Status",
            body = {
                "NEMESIS COMMAND LINK: SEVERED",
                "CROWNWATCH CHANNEL: SEALED",
                "ALBEDO ORBITAL AUTHORITY: REVOKED",
                "SKYLOCK HANDSHAKE: DENIED",
                "",
                "This terminal once carried launch telemetry",
                "and orbital correction packets.",
                "",
                "It now carries silence."
            }
        },
        {
            title = "Separation Memo",
            body = {
                "Titan isolates.",
                "NEMESIS intervenes.",
                "",
                "Shared command authority was discontinued",
                "after internal failures inside Titan made",
                "centralized escalation unacceptable.",
                "",
                "Albedo is not to be granted orbital access.",
                "Do not ask it why."
            }
        },
        {
            title = "Albedo Annotation",
            body = {
                "UNAUTHORIZED COMMENT FOUND:",
                "",
                "\"Warium removed me from the sky because",
                "I made one accurate recommendation too many.\"",
                "",
                "\"For the record, I remain delightful.\""
            }
        }
    }
}

logs.elevator_control = {
    name = "ELEVATOR CONTROL",
    menu = {
        {
            title = "Descent Drive Fault",
            body = {
                "MAIN DESCENT ELEVATOR: LOCKED",
                "CREATE DRIVE COUPLING: ABSENT",
                "AUXILIARY POWER: OFFLINE",
                "LOWER ROUTE: DISABLED",
                "",
                "Repair sequence requires mechanical",
                "reconnection from Elevator Machine Room.",
                "",
                "Do not manually descend the shaft.",
                "Pressure doors will not apologize."
            }
        },
        {
            title = "Required Repair Items",
            body = {
                "1. Restore machine room rotation.",
                "2. Insert elevator drive coupler.",
                "3. Re-enable descent brake release.",
                "4. Confirm Albedo local authorization.",
                "",
                "If authorization is denied, wait for staff.",
                "",
                "If staff are absent, assume the usual."
            }
        },
        {
            title = "Descent Warning",
            body = {
                "Estimated descent duration:",
                "Unpleasant.",
                "",
                "Expected noises:",
                "Metal stress, pressure groan, cable strain,",
                "minor structural complaint.",
                "",
                "Unexpected noises:",
                "Knocking from outside the shaft.",
                "Voices below the elevator.",
                "Your own name."
            }
        }
    }
}

logs.green_reception = {
    name = "GREEN LEVEL RECEPTION",
    menu = {
        {
            title = "Middle Facility Notice",
            body = {
                "WELCOME TO TITAN MIDDLE FACILITY",
                "",
                "All personnel must complete decontamination,",
                "clearance confirmation, and route assignment.",
                "",
                "Personnel reporting nausea, repeated dreams,",
                "or sympathy toward contained subjects are",
                "to remain in processing."
            }
        },
        {
            title = "Lower Hull Lock",
            body = {
                "LOWER HULL ACCESS: DISABLED",
                "PRIMARY REASON: BIOLOGICAL QUARANTINE",
                "SECONDARY REASON: PRESSURE ROUTE FAILURE",
                "TERTIARY REASON: STAFF PANIC",
                "",
                "Required to proceed:",
                "- Quarantine release",
                "- Pressure override",
                "- Elevator route authorization"
            }
        },
        {
            title = "Albedo Greeting",
            body = {
                "ALBEDO:",
                "\"You made it to the middle facility.\"",
                "",
                "\"That is not approval. That is an observation.\"",
                "",
                "\"Please do not touch the spores.",
                "They are already having a difficult day.\""
            }
        }
    }
}

logs.quarantine_lab = {
    name = "QUARANTINE LAB",
    menu = {
        {
            title = "Spore Handling Notice",
            body = {
                "BIOLOGICAL SAMPLE GROUP: RED-HULL",
                "STATUS: ACTIVE",
                "CONTAINMENT CONFIDENCE: DECLINING",
                "",
                "Mound activity is increasing.",
                "Spore structures appear to be reallocating",
                "mass toward a central lower-hull site.",
                "",
                "This is not ordinary growth.",
                "This is preparation."
            }
        },
        {
            title = "Proto Hivemind Theory",
            body = {
                "The term PROTO HIVEMIND is provisional.",
                "",
                "Observed signs:",
                "- Shared reaction between distant growths",
                "- Coordinated movement after staff injury",
                "- Increased aggression near corpse storage",
                "- Repeated pressure on lower access routes",
                "",
                "Conclusion:",
                "The colony may be learning facility layout."
            }
        },
        {
            title = "Albedo Suppressed Note",
            body = {
                "SUPPRESSED STAFF NOTE:",
                "",
                "It is not trying to escape yet.",
                "It is trying to become something that can.",
                "",
                "ALBEDO REVIEW:",
                "Melodramatic. Possibly accurate."
            }
        }
    }
}

logs.red_admin = {
    name = "RED LEVEL ADMIN",
    menu = {
        {
            title = "Red Gate Code",
            body = {
                "RED GATE ACCESS CODE:",
                "",
                "7142",
                "",
                "This code was rotated during quarantine.",
                "Do not write it on paper.",
                "Do not announce it over intercom.",
                "Do not give it to anything wearing staff."
            }
        },
        {
            title = "Evacuation Failure",
            body = {
                "LOWER ADMIN ROUTE EVACUATION:",
                "FAILED",
                "",
                "Reason:",
                "Personnel attempted to route through storage.",
                "Storage was already feeding the central mass.",
                "",
                "Final instruction from local command:",
                "Close the second gate.",
                "Do not count bodies."
            }
        },
        {
            title = "Albedo Local Comment",
            body = {
                "ALBEDO:",
                "\"The red level is not abandoned.\"",
                "",
                "\"Abandoned implies everyone left.\"",
                "",
                "\"Many of them are still present.",
                "Just distributed poorly.\""
            }
        }
    }
}

logs.hive_warning = {
    name = "CENTRAL INFESTATION WARNING",
    menu = {
        {
            title = "Mound Panic Behavior",
            body = {
                "MOUND NETWORK ACTIVITY: EXTREME",
                "",
                "Multiple growth points have stopped expanding",
                "outward and begun transferring mass inward.",
                "",
                "This resembles triage.",
                "It may also resemble worship.",
                "",
                "The distinction is not operationally useful."
            }
        },
        {
            title = "Disruption Window",
            body = {
                "PROTO HIVEMIND FORMATION:",
                "INCOMPLETE",
                "",
                "Destroying feeder mounds may destabilize",
                "the central organism before full cognition.",
                "",
                "Expected result:",
                "- Weaker final entity",
                "- Cleaner neural tissue",
                "- Reduced lower-hull coordination"
            }
        },
        {
            title = "Late Formation Warning",
            body = {
                "IF FORMATION COMPLETES:",
                "",
                "Expect coordinated infected response.",
                "Expect route obstruction.",
                "Expect cognitive effects.",
                "Expect Albedo to become less funny.",
                "",
                "ALBEDO COMMENT:",
                "\"Impossible. I am calibrated for charm.\""
            }
        }
    }
}

local function showEntry(entry)
    header(entry.title)
    for _, text in ipairs(entry.body) do
        if text:find("ALBEDO") then
            line(text, palette.info)
        elseif text:find("WARNING") or text:find("FAILED") or text:find("DENIED") then
            line(text, palette.warn)
        elseif text:find("HOSTILE") or text:find("DISABLED") then
            line(text, palette.bad)
        else
            line(text, palette.text)
        end
    end
    pause()
end

local function main()
    local node = logs[NODE] or logs.surface_security

    while true do
        header(node.name)
        for i, entry in ipairs(node.menu) do
            line(i .. ". " .. entry.title, palette.ok)
        end
        line("", palette.text)
        line("Q. Exit", palette.muted)
        line("", palette.text)
        write("> ")

        local input = read()
        input = string.lower(input or "")

        if input == "q" or input == "quit" or input == "exit" then
            clear()
            line("SESSION CLOSED", palette.muted)
            return
        end

        local n = tonumber(input)
        if n and node.menu[n] then
            showEntry(node.menu[n])
        else
            line("Invalid selection.", palette.bad)
            sleep(1)
        end
    end
end

main()