#!/bin/env python3

import argparse
from TTS.utils import audio
import librosa
import struct
from io import BytesIO

from fm_feed import fm_feed, SAMPLE_RATE


def main():
    parser = argparse.ArgumentParser(
        prog="fm_feed",
        description="Send audio data to mmdvm host as USRP frames",
        epilog="Audio format: Any wav file should work. This script uses librosa to convert.",
    )

    parser.add_argument(
        "--local-addr", help="sender address to use in the UDP frames", required=True
    )
    parser.add_argument(
        "--local-port", help="sender port to use in the UDP frames", default=4810
    )
    parser.add_argument(
        "--remote-addr", help="remote address to use in the UDP frames", required=True
    )
    parser.add_argument(
        "--remote-port", help="remote port to use in the UDP frames", default=3810
    )

    parser.add_argument(
        "--wav",
        help="file with raw audio data to send.",
        required=True,
    )

    args = parser.parse_args()

    audio_data, sr = librosa.load(args.wav, mono=True, sr=SAMPLE_RATE)

    audio_bytes = b""
    for sample in librosa.util.normalize(audio_data):
        sample_int = int(sample * (2**15 - 1))
        audio_bytes += struct.pack("<h", sample_int)

    fm_feed(
        args.local_addr,
        args.local_port,
        args.remote_addr,
        args.remote_port,
        BytesIO(audio_bytes),
    )


if __name__ == "__main__":
    main()
