import numpy as np
from scipy.io import wavfile
import svgwrite

# ======================
# PARAMS (edit these)
# ======================

WAV_PATH = "Hedwigs Theme.wav"
SVG_PATH = "hedwig_waveform_parametric.svg"

SVG_WIDTH = 2000        # px
SVG_HEIGHT = 400        # px
STROKE_WIDTH = 2        # px

SAMPLES = 1200          # horizontal resolution
AMPLITUDE_SCALE = 0.9   # 0–1, vertical exaggeration

START_TIME = 0.0        # seconds into the track
DURATION = 12.0         # seconds to visualize

MIRROR = False          # True = top/bottom symmetric
CLOSED_SHAPE = False    # True = filled solid waveform

# ======================
# LOAD AUDIO
# ======================

rate, data = wavfile.read(WAV_PATH)

if data.ndim > 1:
    data = data.mean(axis=1)

# Slice time window
start_sample = int(START_TIME * rate)
end_sample = int((START_TIME + DURATION) * rate)
data = data[start_sample:end_sample]

# Normalize
data = data / np.max(np.abs(data))

# Downsample
indices = np.linspace(0, len(data) - 1, SAMPLES).astype(int)
data = data[indices] * AMPLITUDE_SCALE

# ======================
# SVG BUILD
# ======================

dwg = svgwrite.Drawing(SVG_PATH, size=(SVG_WIDTH, SVG_HEIGHT))
mid_y = SVG_HEIGHT / 2

top_points = []
bottom_points = []

for i, amp in enumerate(data):
    x = i * (SVG_WIDTH / (SAMPLES - 1))
    y = mid_y - amp * (SVG_HEIGHT / 2)
    top_points.append((x, y))

    if MIRROR:
        y_mirror = mid_y + amp * (SVG_HEIGHT / 2)
        bottom_points.append((x, y_mirror))

# ======================
# DRAW
# ======================

if CLOSED_SHAPE and MIRROR:
    shape = top_points + bottom_points[::-1]
    dwg.add(
        dwg.polygon(
            points=shape,
            fill="black",
            stroke="none"
        )
    )
else:
    dwg.add(
        dwg.polyline(
            points=top_points,
            fill="none",
            stroke="black",
            stroke_width=STROKE_WIDTH
        )
    )

dwg.save()
print("Saved:", SVG_PATH)
