import pandas as pd
import pytask
from pathlib import Path

from scipy import stats

from esaform2023.weiner.config import JINJA_ENV, TEX_DIR, ROOT_DIR, SIM_DIR, DATA_DIR
from esaform2023.weiner.data.config import MAX_PAUSE, IBA_EXPORT_FILES
from esaform2023.weiner.sim.config import IN_DIA_MEAN, IN_TEMP_MEAN, IN_DIA_STD, IN_TEMP_STD, \
    MEAN_REVERSING_PAUSE_DURATION, COUNT


@pytask.mark.task()
@pytask.mark.depends_on({
    "template": TEX_DIR / "_results.tex",
    "sim1": SIM_DIR / "sim1_results.csv",
    "sim2": SIM_DIR / "sim2_results.csv",
    "dist": DATA_DIR / "duo_pauses_dist.csv",
})
@pytask.mark.produces(TEX_DIR / "results.tex")
def task_jinja_results(depends_on: dict[str, Path], produces: Path):
    template = JINJA_ENV.get_template(str(depends_on["template"].relative_to(ROOT_DIR)))

    sim1_data = pd.read_csv(depends_on["sim1"], index_col=0, header=[0, 1])
    sim2_data = pd.read_csv(depends_on["sim2"], index_col=0, header=[0, 1])
    dist = pd.read_csv(depends_on["dist"], header=0)
    gamma = stats.gamma(a=dist["alpha"], scale=dist["beta"], loc=dist["loc"])

    result = template.render(
        num_trials=len(IBA_EXPORT_FILES),
        num_sims=COUNT,
        diameter=IN_DIA_MEAN * 1e3,
        temperature=IN_TEMP_MEAN,
        diameter_std=IN_DIA_STD * 1e3,
        temperature_std=IN_TEMP_STD,
        max_pause=MAX_PAUSE,
        pause_sim1=MEAN_REVERSING_PAUSE_DURATION,
        sim1_r1_in_std=sim1_data.in_temperature.R1.std(),
        sim1_f1_in_std=sim1_data.in_temperature.F1.std(),
        sim1_f4_out_std=sim1_data.out_temperature.F4.std(),
        sim2_r1_in_std=sim2_data.in_temperature.R1.std(),
        sim2_f1_in_std=sim2_data.in_temperature.F1.std(),
        sim2_f4_out_std=sim2_data.out_temperature.F4.std(),
        t_mean=dist["mean"].values[0],
        confidence90=gamma.interval(0.9),
    )

    produces.write_text(result)
