# Copyright 2022-2026 XMOS LIMITED.
# This Software is subject to the terms of the XMOS Public Licence: Version 1.

import sys
from pathlib import Path
import argparse
from datetime import datetime

class Tee:
    def __init__(self, *streams):
        self.streams = streams
    def write(self, s):
        for st in self.streams:
            st.write(s)
    def flush(self):
        for st in self.streams:
            st.flush()

def build_parser(prog="filters"):
    p = argparse.ArgumentParser(prog=prog)
    p.add_argument("coef_pkl_file", type=str,
                   help="Path to pkl file containing first and second stage coefficients.")
    p.add_argument("--file-prefix", "-fp", type=str, default=None,
                   help="Filename prefix; if set, writes <prefix>.h.")
    p.add_argument("--file-dir", "-fd", type=str, default=str(Path.cwd()),
                   help="Directory to create the file. Default cwd.")
    return p

def print_header(args, outstreams=[sys.stdout]):
    out = Tee(*outstreams)
    year = datetime.now().year
    copyright_str = (f"// Copyright {year} XMOS LIMITED.\n"
    f"// This Software is subject to the terms of the XMOS Public Licence: Version 1.\n")
    print(copyright_str, file=out)
    print(f"#ifndef {args.file_prefix.upper()}_H", file=out)
    print(f"#define {args.file_prefix.upper()}_H", file=out)
    print(f"\n/* Autogenerated by running 'python combined.py {args.coef_pkl_file} -fp {args.file_prefix}'. Do not edit */", file=out)
    print(f"\n#include <stdint.h>", file=out)

def print_footer(outstreams=[sys.stdout], num_filter_stages=0):
    out = Tee(*outstreams)
    if num_filter_stages:
        print(f"\n#define NUM_DECIMATION_STAGES  ({num_filter_stages})\n", file=out)
    print("#endif", file=out)
