import argparse
import configparser
import logging
import pathlib

import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
from scipy import fft

from .olaflow import OFModel

parser = argparse.ArgumentParser(description="Convert swash output to olaFlow input")
parser.add_argument("-v", "--verbose", action="count", default=0)
parser.add_argument("-c", "--config", default="config.ini")
args = parser.parse_args()

logging.basicConfig(level=max((10, 20 - 10 * args.verbose)))
log = logging.getLogger("sws_ola")

log.info("Starting sws -> olaFlow converter")
log.warning("This does not provide the correct boundary condition")
config = configparser.ConfigParser()
config.read(args.config)

sws_out = pathlib.Path(config.get("swash", "np_out"))


def data(var):
    return np.load(sws_out.joinpath(f"{var}.npy"))


x = data("x")
t = data("t")[-100:]

watl = data("watl")

arg_x0 = np.argmin(np.abs(x + 1250))

wl = watl[-100:, arg_x0]

f = fft.rfftfreq(t.size, np.diff(t).mean())[1:]
w_fft = fft.rfft(wl, norm="forward")[1:]
amp = np.abs(w_fft)
phi = np.angle(w_fft)

olaflow_root = pathlib.Path(config.get("olaflow", "root"))
org = olaflow_root.joinpath("constant", "waveDict_irregular.org").read_text()
org = org.replace("{n}", str(f.size))
org = org.replace("{wh}", "\n".join(amp.astype(np.str_)))
org = org.replace("{wph}", "\n".join(phi.astype(np.str_)))
org = org.replace("{wper}", "\n".join((1 / f).astype(np.str_)))
olaflow_root.joinpath("constant", "waveDict").write_text(org)
print(f, amp, phi, sep="\n")
