import math
import time
import os
import msvcrt

# --- HDGL Machine (Windows-ready) ---
class HDGLMachine:
    def __init__(self):
        self.phi = 1.6180339887
        self.phi_phi = 2.6180339887
        self.P3 = 4.2360679775
        self.P7 = 29.0344465435
        self.recursion_active = False
        self.dimension = 1.0  # 2D double-helix
        self.offset = 2  # stereoscopic offset
        self.zoom = 1.0  # terminal zoom

    def toggle_recursion(self):
        self.recursion_active = not self.recursion_active

    def compute_state(self, t, idx):
        val = (self.phi*math.sin(t*self.phi) +
               self.phi_phi*math.sin(t*self.phi_phi) +
               self.P3*math.sin(t*self.P3))
        if self.recursion_active:
            val *= self.P7/self.P3
        # Helix: alternating sign for double strand
        sign = 1 if idx % 2 == 0 else -1
        return val * sign

# --- Terminal Renderer ---
class TerminalHologram:
    def __init__(self, machine, width=80, height=24):
        self.machine = machine
        self.width = width
        self.height = height

    def clear(self):
        os.system('cls' if os.name=='nt' else 'clear')

    def render(self, t):
        grid = [[' ' for _ in range(self.width)] for _ in range(self.height)]
        for i in range(0, self.width, 2):
            val = self.machine.compute_state(t, i)
            x = int((i/self.width)*self.width*self.machine.zoom)
            y = int((self.height/2) + val/self.machine.P7 * (self.height/2) )
            y = max(0, min(self.height-1, y))
            # Apply stereoscopic offset
            offset = self.machine.offset
            grid[y][min(self.width-1, x)] = '.'
            grid[y][min(self.width-1, x+offset)] = '.'
        # Print
        self.clear()
        print("\n".join("".join(row) for row in grid))
        print(f"Recursion: {'ON' if self.machine.recursion_active else 'OFF'} | Offset: {self.machine.offset} | Zoom: {self.machine.zoom:.2f}")
        print("Controls: r=toggle recursion, [/] adjust offset, +/- zoom, q=quit")

# --- Main Loop ---
def main():
    machine = HDGLMachine()
    renderer = TerminalHologram(machine, width=80, height=24)
    t = 0.0
    dt = 0.05

    while True:
        renderer.render(t)
        t += dt
        time.sleep(dt)

        # Check keys
        if msvcrt.kbhit():
            key = msvcrt.getwch()
            if key.lower() == 'q':
                break
            elif key.lower() == 'r':
                machine.toggle_recursion()
            elif key == '+':
                machine.zoom *= 1.1
            elif key == '-':
                machine.zoom /= 1.1
            elif key == '[':
                machine.offset = max(0, machine.offset-1)
            elif key == ']':
                machine.offset += 1

if __name__ == "__main__":
    main()
