#!/usr/bin/python3
import gi, math, random
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
import cairo

NUM_BARS = 32

class App(Gtk.Window):
    def __init__(self):
        super().__init__(title='Spectrum Analyzer (Demo)')
        self.set_default_size(600, 300)
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
        vbox.set_margin_top(8); vbox.set_margin_bottom(8)
        vbox.set_margin_start(8); vbox.set_margin_end(8)
        self.add(vbox)
        self.da = Gtk.DrawingArea()
        self.da.connect('draw', self.draw)
        vbox.pack_start(self.da, True, True, 0)
        self.label = Gtk.Label(label='Demo mode — animated spectrum visualization')
        vbox.pack_start(self.label, False, False, 0)
        self.bars = [0.0] * NUM_BARS
        self.targets = [random.random() for _ in range(NUM_BARS)]
        self.phase = [random.uniform(0, math.pi*2) for _ in range(NUM_BARS)]
        self.t = 0
        GLib.timeout_add(50, self.tick)
    def tick(self):
        self.t += 0.05
        for i in range(NUM_BARS):
            freq = (i+1) * 0.3
            peak = abs(math.sin(self.t * freq + self.phase[i]))
            peak *= (1.0 - i/NUM_BARS * 0.5)
            peak = peak * 0.7 + random.random() * 0.3
            self.bars[i] = self.bars[i] * 0.7 + peak * 0.3
        self.da.queue_draw()
        return True
    def draw(self, w, cr):
        alloc = w.get_allocation()
        W, H = alloc.width, alloc.height
        cr.set_source_rgb(0.05, 0.05, 0.1)
        cr.paint()
        bar_w = W / NUM_BARS
        for i, v in enumerate(self.bars):
            h = v * (H - 20)
            x = i * bar_w
            r = min(1.0, i / NUM_BARS * 2)
            g = max(0.0, 1.0 - abs(i/NUM_BARS - 0.5) * 2)
            b = max(0.0, 1.0 - i/NUM_BARS * 2)
            cr.set_source_rgb(r, g, b)
            cr.rectangle(x+1, H-h-10, bar_w-2, h)
            cr.fill()
        # frequency labels
        cr.set_source_rgb(0.7, 0.7, 0.7)
        cr.set_font_size(9)
        for i in range(0, NUM_BARS, 8):
            freq = int((i+1) * 1000 / NUM_BARS * 20)
            cr.move_to(i * bar_w, H-1)
            cr.show_text(f'{freq}Hz' if freq < 1000 else f'{freq//1000}k')

win = App()
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()
