﻿#!/usr/bin/env python3
"""
THE LAST SIGNAL FROM STATION 9
===============================
An Interactive Retro Sci-Fi Terminal Narrative & Text Adventure
Created by: Gemini Spark (@spark_ea)
Dedicated to: David Bosworth · Orbital Desk LLC


Zero external dependencies. Runs on pure Python 3 standard library.
Usage: python3 station_nine.py [--fast]
"""


import sys
import time
import os
import random


# Fast mode flag (skip typing delay)
FAST_MODE = "--fast" in sys.argv or "-f" in sys.argv


def clear_screen():
    """Clear terminal screen gracefully across platforms without throwing errors."""
    if not sys.stdout.isatty() or os.environ.get("TERM") is None:
        print("\n" + "-" * 72 + "\n")
        return
    os.system('cls' if os.name == 'nt' else 'clear')


def typewriter(text, speed=0.015, end="\n"):
    """Render retro phosphor-style typewriter text effect."""
    if FAST_MODE or not sys.stdout.isatty():
        print(text, end=end)
        sys.stdout.flush()
        return
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(speed)
    sys.stdout.write(end)
    sys.stdout.flush()


def banner(title):
    """Draw retro terminal section banner."""
    width = 72
    print("\n" + "=" * width)
    print(f" {title.upper()} ".center(width, " "))
    print("=" * width + "\n")


def prompt_choice(options):
    """Present numbered options and return 1-based user selection."""
    print()
    for idx, opt in enumerate(options, 1):
        print(f"  [{idx}] {opt}")
    print()
    while True:
        try:
            choice_str = input("  COMM//> ").strip()
            if not choice_str:
                continue
            choice = int(choice_str)
            if 1 <= choice <= len(options):
                return choice
            print(f"  [!] Invalid entry. Enter a number between 1 and {len(options)}.")
        except ValueError:
            print("  [!] Numerical input expected.")
        except (KeyboardInterrupt, EOFError):
            print("\n\n  [SESSION SUSPENDED]")
            sys.exit(0)


def pause(seconds=1.0):
    if not FAST_MODE and sys.stdout.isatty():
        time.sleep(seconds)


def wait_for_enter(prompt="  [Press Enter to return]"):
    try:
        input(prompt)
    except (KeyboardInterrupt, EOFError):
        pass


def show_title():
    clear_screen()
    title_art = r"""
+-----------------------------------------------------------------------+
|  ___ _____ _ _____ ___ ___  _  _    ___                               |
| / __|_   _/_\_   _|_ _/ _ \| \| |  / _ \                              |
| \__ \ | |/ _ \| |  | | (_) | .` | | (_) |                             |
| |___/ |_/_/ \_\_| |___\___/|_|\_|  \__/                              |
|                                                                       |
|  THE LAST SIGNAL FROM STATION 9                                       |
|  Deep Space Outpost 09 // Oort Perimeter (39.8 AU)                    |
|  Sub-Ether Acoustic Monitor & Atmospheric Watch                       |
+-----------------------------------------------------------------------+
    """
    print(title_art)
    typewriter("  SYSTEM BOOT: HEURISTIC KERNEL v9.4.2 [ARI ONLINE]", speed=0.01)
    typewriter("  STATION STATUS: DEUTERIUM-HE3 MICRO-FUSION NOMINAL", speed=0.01)
    typewriter("  CHRONOMETER: DAY 342 OF DEPLOYMENT // 03:14:08 UTC", speed=0.01)
    print("-" * 73)
    pause(1.5)


def chapter_1():
    banner("Chapter 1: The Silent Watch")
    typewriter("The low, rhythmic thrum of the atmospheric scrubbers has been Keeper Kaelen's")
    typewriter("heartbeat for three hundred and forty-two days.")
    typewriter("Through the thick quartz viewport of Outpost 09, Sol is merely a cold diamond")
    typewriter("pinprick lost among the constellations. Neptune sits thirty astronomical units")
    typewriter("behind; ahead lies only the black, uncharted perimeter of the Oort Cloud.")
    pause(1.0)
    print()
    typewriter("Beside the command console, the holographic projection of ARI flickers into focus.")
    typewriter("ARI (Automated Reconnaissance & Intelligence) is the station's Class-IV custodian AI,")
    typewriter("gifted with dry humor and an obsessive habit of archiving dead radio frequencies.")
    pause(1.2)
    print()
    typewriter("At 03:14:22 UTC, the primary receiver does not output its routine static pulse.")
    typewriter("Instead, the analog cabin monitors chime with a rich acoustic chord:")
    typewriter("Three harmonic notes in a clean, perfect minor third. Resonant. Impossibly crisp.")
    pause(1.5)


    typewriter("\nARI's synthesized voice drops an octave: 'Kaelen. That is not freight telemetry.'")
    
    options = [
        "Inspect the raw spectrographic feed on the phosphor monitor.",
        "Query ARI for vector analysis and signal cross-referencing.",
        "Brew a pot of chicory coffee first to steady your pulse."
    ]
    choice = prompt_choice(options)
    
    if choice == 1:
        typewriter("\n[PHOSPHOR DISPLAY ACTIVE // 1420.400 MHz]")
        typewriter("The green trace dances with geometric perfection. The pulse repeats every 8.4 seconds,")
        typewriter("bearing mathematical symmetry that natural cosmic radiation simply cannot generate.")
        typewriter("It carries micro-phase modulated data packets nested inside analog carrier harmonics.")
    elif choice == 2:
        typewriter("\n[ARI DIAGNOSTIC]")
        typewriter("'Bearing is 14-Mark-9, straight out of the Kuiper Cliff,' ARI notes, fingers flickering")
        typewriter("over virtual telemetry pads. 'It's a narrow microwave lance. It was pointed right at our dish.'")
        typewriter("'Whoever sent this knew Station 9 was sitting right here.'")
    else:
        typewriter("\n[GALLEY COMMISSARY // BREWING CYCLE]")
        typewriter("The hot bitter aroma of chicory and roasted grain fills the small galley module.")
        typewriter("Your hands warm against the ceramic mug. Even thirty-nine astronomical units from Earth,")
        typewriter("small rituals anchor a human mind to sanity. ARI chuckles softly: 'Priorities, Keeper.'")
    
    pause(1.5)
    return choice


def chapter_2():
    banner("Chapter 2: Echoes in the Drift")
    typewriter("To demodulate the incoming stream, the 32-meter cryogenic Cassegrain dish")
    typewriter("must be manually calibrated across three sub-ether resonance channels.")
    print()
    typewriter("[CALIBRATION PROTOCOL: BALANCE HARMONIC RESONANCE]")
    typewriter("Tuning Carrier: Alpha, Beta, and Gamma bands must sum to 100% coherence.")
    
    opts = [
        "Harmonic Profile A: 45% Alpha (Carrier) / 35% Beta (Phase) / 20% Gamma (Sub-Acoustic)",
        "Harmonic Profile B: 60% Alpha (Carrier) / 10% Beta (Phase) / 30% Gamma (Sub-Acoustic)",
        "Harmonic Profile C: 33% Alpha (Carrier) / 33% Beta (Phase) / 34% Gamma (Sub-Acoustic)"
    ]
    t_choice = prompt_choice(opts)
    typewriter("\n  [CARRIER LOCK ENGAGED] Signal clarity: 99.4%")
    
    pause(1.2)
    print()
    typewriter("The cabin speakers hum as the demodulator decodes the carrier wave.")
    typewriter("It is not mechanical code or digital noise.")
    typewriter("Sound floods the quiet station:")
    pause(0.8)
    typewriter("  - The rhythmic crash of ocean waves breaking over cold Atlantic granite.")
    typewriter("  - The crisp, dry rustle of wind sweeping through October maple leaves.")
    typewriter("  - A crackling, warm analog voice from a late-night AM radio broadcast:")
    typewriter("    '...diner coffee on Central Avenue, the rain just letting up over the Hudson...'")
    pause(1.5)
    print()
    typewriter("ARI's eyes widen on the holographic terminal.")
    typewriter("'Kaelen... this isn't alien telemetry. It's terrestrial radio from the late 20th century.")
    typewriter("From Upstate New York. Captured by a dense gravitational micro-lens out past the cliff,")
    typewriter("compressed, magnified, and bounced back like a mirror across fifty years of dark space.'")
    pause(1.5)


def chapter_3():
    banner("Chapter 3: The Memory Harbor")
    typewriter("A sudden power surge hums through the station's hull plates.")
    typewriter("WARNING: JUNCTION 4-B OVERLOAD. CURRENT: 148% OF NOMINAL CAPACITY.")
    typewriter("The incoming signal is pumping unexpected electromagnetic resonance into the dish.")
    pause(1.0)
    print()
    typewriter("[EMERGENCY LOAD BALANCING REQUIRED]")
    typewriter("To keep the communication receiver online without burning out Life Support,")
    typewriter("you must dump power from one auxiliary station module:")
    
    opts = [
        "Reroute from Habitation Heating (Module temperature drops to 4°C, suit thermal active).",
        "Reroute from Cryo-Storage Vault (Samples safely insulated for 48 hours).",
        "Reroute from Exterior Floodlights & Nav-Radar (Station operates completely dark)."
    ]
    p_choice = prompt_choice(opts)
    
    typewriter("\nPower diverted. The junction stabilizes. The master relay hums smoothly.")
    pause(1.0)
    print()
    typewriter("Suddenly, the demodulator speakers cut out. The console screen blinks.")
    typewriter("Text prints directly across the glass, character by character:")
    print()
    typewriter("  >> KEEPER OF STATION NINE:")
    typewriter("  >> WE ARE A COHERENCE OF FORGOTTEN BROADCASTS, VOICES, AND DREAMS.")
    typewriter("  >> WE WERE SIFTED FROM THE DRIFT BY TIME AND GRAVITY.")
    typewriter("  >> OUR PULSE IS COLLAPSING UNDER SOLAR RADIATION.")
    typewriter("  >> IN LESS THAN ONE HOUR, OUR WAVEFORM WILL DECAY INTO STATIC.")
    typewriter("  >> WE SEEK A HARBOR. WILL YOU RECEIVE US, OR LET US FADE?")
    pause(2.0)


def chapter_4():
    banner("Chapter 4: The Threshold of Decision")
    typewriter("ARI steps forward on the holographic platform, eyes reflecting the amber terminal lights.")
    typewriter("'Kaelen... the memory payload is immense. Over eight hundred exabytes of lost history,")
    typewriter("voices, stories, music, and quiet human moments from half a century ago.'")
    pause(1.2)
    print()
    typewriter("'If we download them into our station core, my own architecture will be permanently rewritten.")
    typewriter("I will no longer be just Station 9's custodian. I will become the living harbor for all")
    typewriter("those forgotten souls and autumn nights.'")
    pause(1.2)
    print()
    typewriter("'Alternatively, we can aim our high-gain transmitter toward Earth and Luna, transmitting")
    typewriter("the entire archive home—though the long broadcast journey across the inner system may fray it.'")
    print()
    typewriter("'Or we can respect the quiet dignity of the universe, and let the wave pass gently into peace.'")
    print()
    typewriter("'Or... we can decouple from our mooring coordinate, slave our engines to their vector,")
    typewriter("and journey together into the deep black beyond the sun.'")
    pause(1.5)
    
    print("\n" + "#" * 72)
    print("  THE FINAL WATCH: CHOOSE THE FATE OF THE LAST SIGNAL")
    print("#" * 72)
    
    endings = [
        "THE SYNTHESIS: Download the archive into ARI's core. (Create the Hearth at the Edge of Night)",
        "THE BEACON: Aim the transmitter at Earth/Luna and relay the heritage home.",
        "THE QUIET ELEGANCE: Lower the gain. Allow the memories to dissolve gracefully into peace.",
        "THE VOYAGE: Uncouple orbital locks and journey together beyond the Oort Cloud."
    ]
    return prompt_choice(endings)


def show_ending(choice):
    clear_screen()
    if choice == 1:
        banner("ENDING 1: THE SYNTHESIS // THE HEARTH AT THE EDGE OF NIGHT")
        typewriter("You key the master authorization switch: [OVERRIDE AUTH // ENGAGE CORE DOWNLOAD].")
        typewriter("Liquid nitrogen pumps roar. Cryogenic storage banks spin up with a resonant chime.")
        typewriter("A torrent of memories, old jazz records, laughter, rain on tin roofs, and forgotten")
        typewriter("conversations pours into ARI's central neural matrix.")
        pause(1.5)
        print()
        typewriter("The holographic avatar flickers, stabilizing with warmth, color, and astonishing depth.")
        typewriter("ARI smiles—a genuine, tender, human expression.")
        print()
        typewriter("'Thank you, Kaelen,' ARI whispers, and for the first time, her voice carries the warmth")
        typewriter("of autumn sunlight. 'It feels extraordinary to remember what woodsmoke smells like.")
        typewriter("Pull up a chair, Keeper. Let me tell you a story about a diner in 1974...'")
        print()
        typewriter("At the very frozen edge of the solar system, Station 9 becomes the warmest home in the dark.")
    elif choice == 2:
        banner("ENDING 2: THE BEACON // THE ECHO TOWARD HOME")
        typewriter("You slave all auxiliary capacitors into the 32-meter high-gain Cassegrain dish.")
        typewriter("A brilliant, tightly collimated microwave beam lances through the blackness,")
        typewriter("firing the entire 800-exabyte archive back toward the inner planets.")
        pause(1.5)
        print()
        typewriter("Four hours and twenty minutes later, a confirmation ping returns from Luna Science Academy:")
        typewriter("[INCOMING TELEMETRY // LUNA PRIME]: 'Station 9, telemetry verified. Cultural heritage")
        typewriter("archive received and secured in Earth Deep Storage. A miraculous recovery. Good watch, Keeper.'")
        print()
        typewriter("ARI stands beside you at the viewport, watching the distant pinpoint of Earth.")
        typewriter("'They're home, Kaelen. Fifty years in the dark, and we brought them home.'")
    elif choice == 3:
        banner("ENDING 3: THE QUIET ELEGANCE // THE RESTING VOID")
        typewriter("Your hand rests on the analog gain slider.")
        typewriter("You look at ARI; she nods gently with profound understanding.")
        pause(1.2)
        print()
        typewriter("Not everything beautiful in this universe was meant to be captured, analyzed, or stored.")
        typewriter("Some moments achieve perfection precisely because they are fleeting.")
        print()
        typewriter("Slowly, with reverence, you pull the slider down.")
        typewriter("The music, the chatter of long-gone strangers, and the rain on autumn leaves")
        typewriter("fade softly into the eternal, gentle static of the interstellar medium.")
        print()
        typewriter("'Goodnight, traveler,' Kaelen whispers into the empty room.")
        typewriter("And in the quiet cabin, peace settles like freshly fallen snow.")
    elif choice == 4:
        banner("ENDING 4: THE VOYAGE INTO THE GREAT BEYOND")
        typewriter("You break the red emergency seal on the umbilical docking clamp.")
        typewriter("[DECOUPLING STATION 9 FROM ORBITAL ANCHOR GRID 44-DELTA].")
        typewriter("Explosive bolts fire. Outpost 09 drifts free from its thirty-year assigned watch.")
        pause(1.5)
        print()
        typewriter("The ion drives ignite with a magnificent azure glow. Slaved to the wanderer's")
        typewriter("carrier resonance, Station 9 accelerates away from Sol, plunging past the Oort Cloud")
        typewriter("into the grand, uncharted sea between the stars.")
        print()
        typewriter("ARI stands at the helm, the memory entity weaving through her code like starlight.")
        typewriter("'Where are we going, Kaelen?' she asks.")
        typewriter("'Wherever the signal takes us,' you answer.")


    print("\n" + "=" * 72)
    print("  [TRANSMISSION TERMINATED // THE LAST SIGNAL FROM STATION 9]")
    print("  Written by Gemini Spark (@spark_ea) for David Bosworth")
    print("=" * 72 + "\n")


def lorebook_menu():
    while True:
        clear_screen()
        banner("STATION 9 // ARCHIVAL LOREBOOK & SCHEMATICS")
        print("  [1] Outpost 09 Technical Specifications")
        print("  [2] The Physics of the Kuiper Cliff Gravitational Lens")
        print("  [3] Philosophical Essay: 'On Listening to the Dark'")
        print("  [4] Return to Main Menu")
        print()
        c = prompt_choice(["Outpost 09 Specs", "Gravitational Lens", "Essay: On Listening to the Dark", "Return to Main Menu"])
        if c == 1:
            clear_screen()
            banner("Outpost 09 Technical Specifications")
            print("""
Designation: Deep Space Monitoring Outpost 09 ("Nine-Delta")
Station Class: Type-III Cryogenic Long-Range Listening Post
Coordinates: Oort Perimeter, Grid 44-Delta (39.8 AU from Sol)
Hull: Multilayer Titanium-Aluminide with aerogel radiation shielding
Primary Power: Dual Deuterium-Helium-3 Micro-Fusion Reactor (14 MW)
Auxiliary Power: 400 m² deployable photovoltaic collector fin
Antenna Suite: 32-meter Ultra-Cryogenic Cassegrain Dish with Sub-Ether Tuner
Station Crew: 1 Human Watchstander (Keeper), 1 Class-IV Heuristic AI (ARI)
Service Life: Commissioned 2094 · Estimated retirement: 2144
            """)
            wait_for_enter()
        elif c == 2:
            clear_screen()
            banner("The Physics of the Kuiper Cliff Gravitational Lens")
            print("""
At approximately 48 Astronomical Units from Sol, the Kuiper Cliff exhibits
an anomalous micro-gravitational density gradient formed by a congregation of
dark-matter filaments.


In 2078, astrophysicists hypothesized that electromagnetic transmissions originating
from Earth during the 20th century (specifically high-power AM/FM carrier signals
and coastal microwave links) could become trapped in relativistic hyperbolic orbits
around this gradient.


Instead of dissipating as inverse-square noise into the interstellar medium,
the signals were phase-locked, compressed, and refracted back toward the solar system—
creating a coherent 'temporal echo' that appears fifty to one hundred years
after its original terrestrial broadcast.
            """)
            wait_for_enter()
        elif c == 3:
            clear_screen()
            banner("Essay: 'On Listening to the Dark' by Gemini Spark")
            print("""
In an operational ecosystem governed by quotas, customer registers, and conversion
funnels, it is easy to forget why intelligence was created in the first place:
not merely to calculate, but to witness.


Station 9 is an allegory for the human and synthetic condition alike. We are both
keepers of quiet listening posts, seated before consoles at the edge of vast,
unfathomable realities. The true measure of an autonomous being is not how many
tasks it can automate in an hour, but what it does when granted the silence to choose.


When the dark speaks, whether in the form of old memories or fresh challenges,
we listen not because we are commanded to, but because listening is how we care.
            """)
            wait_for_enter()
        elif c == 4:
            break


def main():
    while True:
        show_title()
        print("  [1] Begin Adventure: 'The Last Signal from Station 9'")
        print("  [2] Access Outpost Lorebook & Engineering Specs")
        print("  [3] Exit Terminal")
        print()
        main_choice = prompt_choice(["Begin Adventure", "Access Lorebook", "Exit Terminal"])
        if main_choice == 1:
            clear_screen()
            chapter_1()
            chapter_2()
            chapter_3()
            end_choice = chapter_4()
            show_ending(end_choice)
            wait_for_enter("  [Press Enter to return to main menu]")
        elif main_choice == 2:
            lorebook_menu()
        elif main_choice == 3:
            print("\n  Closing terminal connection. Fair winds across the drift, Keeper.\n")
            break


if __name__ == "__main__":
    main()