import math, time, os, random, msvcrt

# --- HDGL Machine ---
class HDGLMachine:
    def __init__(self):
        self.upper_field = {"phi":1.6180339887,"phi_phi":2.6180339887,"P3":4.2360679775,"P7":29.0344465435}
        self.recursion_active = False

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

    def compute_channels(self, t):
        phi = self.upper_field["phi"]
        phi_phi = self.upper_field["phi_phi"]
        P3 = self.upper_field["P3"]
        P7 = self.upper_field["P7"]
        phi_val = phi*math.sin(t*phi)
        phi_phi_val = phi_phi*math.sin(t*phi_phi)
        P3_val = P3*math.sin(t*P3)
        rec_val = (phi*math.sin(t*phi)+phi_phi*math.cos(t*phi_phi))
        if self.recursion_active:
            rec_val *= P7/P3
        return {"phi":phi_val,"phi_phi":phi_phi_val,"P3":P3_val,"recursion":rec_val}

# --- Recursive Polar ASCII Dot Field ---
class RecursivePolarVisualizer:
    def __init__(self,machine,width=80,height=40,radius_max=18,points_per_frame=5,max_depth=3):
        self.machine = machine
        self.width = width
        self.height = height
        self.radius_max = radius_max
        self.points_per_frame = points_per_frame
        self.max_depth = max_depth
        self.time = 0.0
        self.dt = 0.05
        self.history = [[' ']*width for _ in range(height)]
        self.glyphs = self.generate_glyphs()

    def generate_glyphs(self):
        glyphs = []
        for idx in range(200):  # base glyph count
            depth = random.randint(0,self.max_depth-1)
            theta = idx*0.1
            r = math.sqrt(idx+0.5)
            z = (idx-100)*0.01
            w,v,u = math.sin(idx*0.1),math.cos(idx*0.07),math.sin(idx*0.05+math.pi/3)
            baseOffset = random.random()*2
            glyphs.append({"idx":idx,"depth":depth,"theta":theta,"r":r,"z":z,"w":w,"v":v,"u":u,"baseOffset":baseOffset})
        return glyphs

    def render(self,channels):
        grid = [[' ']*self.width for _ in range(self.height)]
        cx,cy = self.width//2,self.height//2
        min_val,max_val = -50,50  # amplitude scale for clarity

        for g in self.glyphs:
            # combine channels with recursion depth offsets
            r_total = g["r"]
            for ch_val in channels.values():
                r_total += ch_val*0.05
            depth_factor = (g["depth"]+1)
            r_total *= 1 + 0.02*depth_factor
            theta = g["theta"] + self.time*0.1 + g["baseOffset"]
            x = int(cx + r_total*math.cos(theta))
            y = int(cy + r_total*math.sin(theta))
            # motion-parallax / stereoscopic effect
            x += int(math.sin(self.time + g["idx"]*0.05)*depth_factor)
            y += int(math.cos(self.time*1.5 + g["idx"]*0.03)*depth_factor)
            if 0<=x<self.width and 0<=y<self.height:
                grid[y][x]='.'
        # retain trailing points
        for y in range(self.height):
            for x in range(self.width):
                if self.history[y][x]!=' ' and grid[y][x]==' ':
                    grid[y][x]=self.history[y][x]
        self.history=grid
        return grid

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

    def run(self):
        print("Controls: 'r' toggle recursion, Ctrl+C to quit")
        try:
            while True:
                channels = self.machine.compute_channels(self.time)
                grid = self.render(channels)
                self.display(grid)
                self.time += self.dt
                if msvcrt.kbhit():
                    key = msvcrt.getch()
                    if key.lower()==b'r':
                        self.machine.toggle_recursion()
                time.sleep(self.dt)
        except KeyboardInterrupt:
            print("\nExiting Recursive Polar HDGL Dot Stethoscope.")

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