import math
import time
import os
import msvcrt  # Windows keypress detection

# --- HDGL Machine ---
class HDGLMachine:
    def __init__(self):
        self.upper_field = {"phi": 1.6180339887, "phi_power_phi": 2.6180339887, "pi": 3.1415926535, "P3": 4.2360679775}
        self.analog_dims = {"dim_switch": 1.0, "P7": 29.0344465435}
        self.lower_field = {"inv_phi": 0.6180339887, "inv_P3": 0.2360679775}
        self.void = 0.0
        self.current_state = self.void
        self.dimension = self.analog_dims["dim_switch"]
        self.recursion_active = False
        self.seed = 0.0  # calculator input placeholder

    def toggle_recursion(self):
        self.recursion_active = not self.recursion_active
        print(f"Recursion: {'ON' if self.recursion_active else 'OFF'}")

    def compute_harmonic_state(self, t):
        state = self.void
        phi = self.upper_field["phi"]
        phi_phi = self.upper_field["phi_power_phi"]
        pi = self.upper_field["pi"]

        for val in self.upper_field.values():
            state += val * math.sin(t*phi)
        for val in self.lower_field.values():
            state += val * math.cos(t*self.lower_field["inv_phi"])
        for val in self.analog_dims.values():
            state += val * math.sin(t*phi_phi)

        if self.dimension == 1.0:
            state *= math.sin(t*pi)
        else:
            state *= math.cos(t*pi)

        state += self.seed
        return state

    def step(self, t):
        state = self.compute_harmonic_state(t)
        if self.recursion_active:
            state *= self.analog_dims["P7"] / self.lower_field["inv_P3"]
        self.current_state = state
        return state

# --- ASCII Analog Waveform for Windows ---
class ASCIIVisualizer:
    def __init__(self, machine, width=80, height=20):
        self.machine = machine
        self.width = width
        self.height = height
        self.time = 0.0
        self.dt = 0.05
        self.history = [[' ']*self.width for _ in range(self.height)]

    def render(self, value):
        min_val, max_val = -500, 500
        y = int((value - min_val) / (max_val - min_val) * (self.height-1))
        y = max(0, min(self.height-1, y))
        grid = [[' ']*self.width for _ in range(self.height)]
        grid[self.height - y - 1][-1] = '*'  # newest point rightmost
        # shift previous columns left
        for row in range(self.height):
            grid[row][:-1] = self.history[row][1:]
        self.history = grid
        return grid

    def display(self, grid):
        os.system('cls')  # clear console
        for row in grid:
            print(''.join(row))

    def run(self):
        print("Press 'r' to toggle recursion. Ctrl+C to quit.")
        try:
            while True:
                val = self.machine.step(self.time)
                grid = self.render(val)
                self.display(grid)
                self.time += self.dt

                # Windows keypress detection
                if msvcrt.kbhit():
                    key = msvcrt.getch()
                    if key.lower() == b'r':
                        self.machine.toggle_recursion()

                time.sleep(self.dt)
        except KeyboardInterrupt:
            print("\nExiting ASCII HDGL Visualizer.")

# --- Run ---
if __name__ == "__main__":
    machine = HDGLMachine()
    vis = ASCIIVisualizer(machine)
    vis.run()
