import math
import time
import os
import msvcrt

# --- HDGL Machine ---
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.offset = 2  # stereoscopic offset
        self.zoom = 0.5  # terminal zoom
        self.tilt = 0.0  # rotation angle around X
        self.pan = 0.0   # rotation angle around Y

    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
        sign = 1 if idx % 2 == 0 else -1
        return val * sign

# --- Terminal 3D Hologram ---
class TerminalHologram3D:
    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 rotate_point(self, x, y, z):
        # Tilt around X
        cos_t = math.cos(self.machine.tilt)
        sin_t = math.sin(self.machine.tilt)
        y2 = y*cos_t - z*sin_t
        z2 = y*sin_t + z*cos_t
        # Pan around Y
        cos_p = math.cos(self.machine.pan)
        sin_p = math.sin(self.machine.pan)
        x2 = x*cos_p + z2*sin_p
        z3 = -x*sin_p + z2*cos_p
        return x2, y2, z3

    def render(self, t):
        grid = [[' ' for _ in range(self.width)] for _ in range(self.height)]
        radius = min(self.width, self.height)//4

        for i in range(0, 360, 2):  # polar angle steps
            angle = math.radians(i)
            # Circular helix + waveform
            helix_radius = radius + self.machine.compute_state(t, i)
            x = helix_radius * math.cos(angle)
            y = helix_radius * math.sin(angle)
            z = (i%20 - 10)  # small vertical wiggle

            # Apply rotation
            x_rot, y_rot, z_rot = self.rotate_point(x, y, z)

            # Project to terminal 2D
            col = int(self.width/2 + x_rot*self.machine.zoom)
            row = int(self.height/2 - y_rot*self.machine.zoom)
            if 0 <= row < self.height and 0 <= col < self.width:
                grid[row][col] = '.'
            # Stereoscopic offset
            col_offset = int(col + self.machine.offset)
            if 0 <= row < self.height and 0 <= col_offset < self.width:
                grid[row][col_offset] = '.'

        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} | Tilt: {self.machine.tilt:.2f} | Pan: {self.machine.pan:.2f}")
        print("Controls: r=toggle recursion, [/] offset, +/- zoom, w/s tilt, a/d pan, q=quit")

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

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

        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
            elif key.lower() == 'w':
                machine.tilt += 0.05
            elif key.lower() == 's':
                machine.tilt -= 0.05
            elif key.lower() == 'a':
                machine.pan -= 0.05
            elif key.lower() == 'd':
                machine.pan += 0.05

if __name__ == "__main__":
    main()
