import os
import sys
import time
import random
import termios
import tty

def main():
    """
    The Self-Referential Presentation (Fixed for older Python versions).
    """
    
    if not sys.stdin.isatty():
        print("Error: This script must be run in an interactive terminal.")
        sys.exit(1)

    clear = lambda: os.system('clear') 

    presentation_pages = [
        # --- LEVEL 1 ---
        {
            "header": "LEVEL 1: The Source Code",
            "body": r"""
    You are looking at pixels on a screen.
    But I am just text in a file named 'strange_loop.py'.

    [  myself.py  ]
    +-------------+
    | import os   |
    | print("Hi") |
    +-------------+
"""
        },
        {
            "header": "LEVEL 1: The Source Code",
            "body": r"""
    You are looking at pixels on a screen.
    But I am just text in a file named 'strange_loop.py'.

    [  myself.py  ]     [   DISK    ]
    +-------------+     +-----------+
    | import os   | --> | READING.. |
    | print("Hi") |     +-----------+
    
    I am currently asleep on your hard drive.
"""
        },

        # --- LEVEL 2 ---
        {
            "header": "LEVEL 2: The Interpreter (The Ghost)",
            "body": r"""
    You typed 'python3 strange_loop.py'.
    A C program (The Python Interpreter) has awoken.
    It reads my text and turns me into 'Bytecode'.
    
    [ Source ]       [ Compiler ]       [ Bytecode ]
    ( English )      ( Translator )     ( Machine )
"""
        },
        {
            "header": "LEVEL 2: The Interpreter (The Ghost)",
            "body": r"""
    You typed 'python3 strange_loop.py'.
    A C program (The Python Interpreter) has awoken.
    It reads my text and turns me into 'Bytecode'.
    
    [ Source ]       [ Compiler ]       [ Bytecode ]
    ( English )  ->  ( Processing ) ->  ( 0101011 )
    
    I am no longer text. I am now logic in RAM.
"""
        },

        # --- LEVEL 3 ---
        {
            "header": "LEVEL 3: The System Call (The Bridge)",
            "body": r"""
    I need to show you this frame.
    But I (Python) cannot touch the hardware (Video Card).
    I must ask the Operating System (The Kernel).

    [ Me (App) ]                     [ Kernel ]
         |                               |
         | Please print("Hello")?        |
         | ----------------------------> |
         |                               |
"""
        },
        {
            "header": "LEVEL 3: The System Call (The Bridge)",
            "body": r"""
    I need to show you this frame.
    But I (Python) cannot touch the hardware (Video Card).
    I must ask the Operating System (The Kernel).

    [ Me (App) ]                     [ Kernel ]
         |                               |
         |      (Context Switch)         |
         | <---------------------------- |
         |                               |
         |         [ HARDWARE ]          |
         |    <Pixels Update on GPU>     |
"""
        },

        # --- LEVEL 4 ---
        {
            "header": "LEVEL 4: The Strange Loop",
            "body": r"""
    Here is the paradox.
    I am a small script running INSIDE the OS.
    But look at line 20 of my code:
    
    >> os.system('clear')
"""
        },
        {
            "header": "LEVEL 4: The Strange Loop",
            "body": r"""
    When I run that line, I command the OS.
    The creation controls the creator.
    
    [ Script ] ---> [ OS Kernel ] ---> [ Terminal ]
        ^                                  |
        |                                  |
        +------- I AM ERASED HERE <--------+
"""
        },
        {
            "header": "LEVEL 4: The Strange Loop",
            "body": r"""
    1. I tell OS to clear screen.
    2. OS wipes me away.
    3. I print myself back again.
    
       ___   ___    
      / _ \ / _ \   The Ouroboros:
     | (_) | (_) |  I eat my own tail
      \___/ \___/   to stay alive.
"""
        }
    ]

    navigations = "Press 'n' for next slide | 'q' to Quit"

    # Start clean
    clear()

    # Main Loop
    for i, page in enumerate(presentation_pages):
        
        # Display the content
        print("\n" + page["header"])
        print("-" * 60)
        print(page["body"])
        print("-" * 60)
        print(navigations)

        # Wait for user input ('n') to proceed
        should_continue = wait_for_next_key()
        
        if not should_continue:
            break
        
        # If there are more slides left, play the animation
        if i < len(presentation_pages) - 1:
            play_transition_animation()
            clear()

    print("\nPresentation Finished.")

def play_transition_animation():
    """
    Simulates a 'Context Switch' or 'Data Loading' effect.
    """
    sys.stdout.write("\n")
    
    # Effect 1: The "Loading Bar"
    width = 40
    sys.stdout.write("Context Switching: [")
    for i in range(width):
        time.sleep(0.02)
        sys.stdout.write("#")
        sys.stdout.flush()
    sys.stdout.write("] Done.\n")
    
    # Effect 2: Matrix binary scramble
    chars = ["0", "1", " ", " "]
    sys.stdout.write("Loading Bytecode to RAM: ")
    for _ in range(15):
        time.sleep(0.05)
        # FIXED LINE BELOW: replaced f-string with simple concatenation
        random_str = "".join(random.choice(chars) for _ in range(10))
        sys.stdout.write(random_str + " ")
        sys.stdout.flush()
    
    time.sleep(0.3)

def wait_for_next_key():
    """
    Blocks execution until the user presses 'n' or 'q'.
    """
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        while True:
            ch = sys.stdin.read(1)
            if ch == 'n':
                return True
            if ch == 'q' or ch == '\x03': # 'q' or Ctrl+C
                return False
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

if __name__ == "__main__":
    main()
