#!/usr/bin/env python3
"""
Example: Upsample a 50 Hz sine wave from 128 Hz to 2048 Hz and plot the result.

Demonstrates proper time alignment accounting for the convolution delay.
"""

import matplotlib.pyplot as plt
import numpy as np

from sgnl_cpu_interp import upsample


def main():
    # Parameters
    fs_original = 128  # Hz
    fs_target = 2048  # Hz
    signal_freq = 50  # Hz
    duration = 0.5  # seconds - need enough samples for the kernel
    factor = fs_target // fs_original

    print(f"Upsampling {fs_original} Hz -> {fs_target} Hz (factor: {factor}x)")

    # Generate finite sine wave at 128 Hz
    n_samples = int(duration * fs_original)
    t_input = np.arange(n_samples) / fs_original
    signal_input = np.sin(2 * np.pi * signal_freq * t_input).astype(np.float32)

    print(f"Input:  {len(signal_input)} samples")

    # Upsample - just pass it directly, no padding
    signal_output = upsample(
        signal_input[:, np.newaxis], factor=factor, half_length=8
    ).squeeze()

    print(f"Output: {len(signal_output)} samples")

    # Create time vector for output
    # The convolution loses (kernel_len - 1) samples
    kernel_len = 2 * 8 + 1  # half_length=8
    n_lost = kernel_len - 1  # 16 samples lost at input rate

    # The first output sample corresponds to input sample at index n_lost/2
    # So we need to shift the output time by (n_lost/2) / fs_original
    time_offset = (n_lost / 2) / fs_original

    t_output = time_offset + np.arange(len(signal_output)) / fs_target

    print(f"Lost {n_lost} input samples to convolution")
    print(f"Time offset applied: {time_offset*1000:.3f} ms")

    # Plot
    fig, ax = plt.subplots(figsize=(14, 6))

    ax.plot(
        t_input * 1000,
        signal_input,
        "o-",
        label=f"Input ({fs_original} Hz)",
        markersize=6,
        linewidth=2,
        zorder=3,
    )
    ax.plot(
        t_output * 1000,
        signal_output,
        "-",
        label=f"Output ({fs_target} Hz)",
        linewidth=1,
        alpha=0.8,
        zorder=2,
    )

    ax.set_xlabel("Time (ms)")
    ax.set_ylabel("Amplitude")
    ax.set_title(
        f"{signal_freq} Hz Sine Wave: Upsampled from {fs_original} Hz to {fs_target} Hz"
    )
    ax.legend()
    ax.grid(True, alpha=0.3)

    plt.tight_layout()
    plt.savefig("upsample_demo.png", dpi=150, bbox_inches="tight")
    print("\nPlot saved to: upsample_demo.png")


if __name__ == "__main__":
    main()
