import os
import re
import json
from itertools import permutations
from copy import deepcopy
import numpy as np


def nth_repl(s, sub, repl, nth):
    """Replace n_th occurrence of substring in string for midrule insertion

    """

    find = s.find(sub)
    i = find != -1
    while find != -1 and i != nth:
        find = s.find(sub, find + 1)
        i += 1
    if i == nth:
        s = s[:find] + repl + s[find + len(sub) :]
    return s


def post_process_reg_coeffs_descriptives(waf_task):

    tables_raw = {}
    prequels = {}
    pre_prequel = r""  # \multirow{2}{.4\textwidth}{"
    specification = "Fully stratified by year / education / age"

    for p in [x.abspath() for x in waf_task.inputs]:
        if "from_25_to_54_base_1985" in p:
            tables_raw["main"] = open(p).readlines()
        elif "from_25_to_39" in p:
            tables_raw["young"] = open(p).readlines()
            prequels["young"] = pre_prequel + "Ages 25--39 "
        elif "from_40_to_54" in p:
            tables_raw["old"] = open(p).readlines()
            prequels["old"] = pre_prequel + "Ages 40--54 "
        elif "from_25_to_34" in p:
            tables_raw["young"] = open(p).readlines()
            prequels["young"] = pre_prequel + "Ages 25--34 "
        elif "from_35_to_44" in p:
            tables_raw["middle"] = open(p).readlines()
            prequels["middle"] = pre_prequel + "Ages 35--44 "
        elif "from_45_to_54" in p:
            tables_raw["old"] = open(p).readlines()
            prequels["old"] = pre_prequel + "Ages 45--54 "
        else:
            raise ValueError(p)
    new = tables_raw["main"]
    loc = -2
    new.insert(loc, "\midrule\n")
    new.insert(loc, "\\\\\n")
    new.insert(
        loc, r"\multicolumn{6}{l}{Separate by age group: " + specification + "}\\\\\n"
    )
    new.insert(loc, "\midrule\n")
    for key in "young", "middle", "old":
        if not key in tables_raw:
            continue
        idx = [i for i, j in enumerate(tables_raw[key]) if j.startswith(specification)]
        assert len(idx) == 1, [idx, new]
        idx = idx[0]

        to_insert = tables_raw[key][idx : idx + 2]
        to_insert[0] = to_insert[0].replace(specification, "", 1)
        to_insert[0] = prequels[key] + to_insert[0]
        for row in to_insert:
            new.insert(loc, row)

    for i, row in enumerate(new):
        if row.startswith("                                           & S.E."):
            new[i] = row.replace(r"\\", r"\\[0.5ex]")

    waf_task.outputs[0].write("".join(new))


def label_number_cols(first_line):
    regex = "\{(l+)(r+)\}"
    match = re.search(regex, first_line)
    return match.group(1), match.group(2)


def begin_tabular(first_line):
    label_cols, number_cols = label_number_cols(first_line)
    new = "\\begin{tabular}{\n    "
    new = new + "\n    ".join(label_cols) + "\n    "
    new = (
        new
        + "\n    ".join(
            [r">{\raggedleft\arraybackslash}p{.075\textwidth}" for _ in number_cols]
        )
        + "\n}"
    )
    return new


def _panel_separator():
    return r"""\\bottomrule
\\\\
\\multicolumn{6}{l}{\\textbf{Background}} \\\\
\\midrule
"""


def post_process_growth_selection_decompositions_groups(waf_task):

    with open(waf_task.inputs[0].abspath(), "r") as p:
        orig = p.readlines()

    out = deepcopy(orig)

    # Header
    out[0] = begin_tabular(first_line=orig[0])

    # Midrules
    for i, line in enumerate(orig):
        if re.match("Leavers", line):
            out[i] = "\midrule\n" + line

    # Cmidrules
    label_cols, number_cols = label_number_cols(orig[0])
    n_cols = len(label_cols) + len(number_cols)
    if len(label_cols) == 2:
        pass
    elif len(label_cols) == 3:
        regex = " +& +[0-9]{2}--[0-9]{2}"
        for i, line in enumerate(out):
            if re.match(regex, line):
                out[i] = f"\cmidrule(l){{2-{n_cols}}}\n" + line
    else:
        raise ValueError(label_cols)

    waf_task.outputs[0].write("".join(out))


def post_process_growth_selection_decompositions_end_acc(waf_task):

    with open(waf_task.inputs[0].abspath(), "r") as p:
        orig = p.readlines()

    out = deepcopy(orig)

    # Header
    out[0] = begin_tabular(first_line=orig[0])

    # Midrules
    for i, line in enumerate(orig):
        if re.match("Accumulation|Shocks|Growth Selection|Fractions", line):
            out[i] = "\midrule\n" + line

    # Take care of growth selection (not dependent on age)
    label_cols, number_cols = label_number_cols(orig[0])
    n_cols = len(label_cols) + len(number_cols)
    if len(label_cols) == 2:
        pass
    elif len(label_cols) == 3:
        hit = False
        regex = "(Growth Selection +& +Total +& +)[0-9\-]+ &"
        for i, line in enumerate(orig):
            if hit:
                if re.match(" +& +& +[0-9\-]+ &", line):
                    out[i] = ""
                else:
                    hit = False
            if re.match(regex, line):
                out[i] = re.sub(regex, _panel_separator() + "\g<1> &", line)
                hit = True
    else:
        raise ValueError(label_cols)

    # Nice descriptions (enumerate over out because of midrules)
    for i, line in enumerate(out):
        regex = "(Endowments|Accumulation|Shocks)"
        match = re.search(regex, line)
        if match:
            if match.group(1) == "Endowments":
                out[i] = re.sub(
                    regex, r"\\textbf{Endowment} at the most recent", line
                )
                out[i + 1] = "entry into the occupation group" + out[i + 1]
            elif match.group(1) == "Accumulation":
                out[i] = re.sub(
                    regex, r"Predicted \\textbf{skill accumulation}", line
                )
                out[i + 1] = "since the most recent entry" + out[i + 1]
            elif match.group(1) == "Shocks":
                out[i] = re.sub(
                    regex, r"\\textbf{Deviation} of skills from the", line
                )
                if label_cols == "ll":
                    out[i + 1] = (
                        "prediction since the most recent entry" + out[i + 1]
                    )
                elif label_cols == "lll":
                    out[i + 1] = "prediction since the most recent" + out[i + 1]
                    out[i + 2] = "entry" + out[i + 2]
                else:
                    raise ValueError(label_cols)
            else:
                raise ValueError(match.group(0))
        else:
            continue

    # cmidrules can only go at the latest (because of 'entry' in case of two age groups)
    n_cols = len(label_cols) + len(number_cols)
    if len(label_cols) == 2:
        pass
    elif len(label_cols) == 3:
        regex = "(entry)? +& +Leavers"
        for i, line in enumerate(out):
            if re.match(regex, line):
                out[i] = f"\cmidrule(l){{2-{n_cols}}}\n" + line
    else:
        raise ValueError(label_cols)
    waf_task.outputs[0].write("".join(out))


def post_process_switchers_gammas(waf_task):
    """New format for gammas.

    """

    raw = waf_task.inputs[0].read()

    # workaround to get number of professions, i.e. lines
    n_profs_siab = (raw.count(r"\\") - 2) ** (0.5)
    n_profs_siab_dummies = ((raw.count(r"\\") - 2) / 2) ** (0.5)

    if n_profs_siab == int(n_profs_siab) and n_profs_siab_dummies != int(
        n_profs_siab_dummies
    ):
        data = "siab"
        dummies = False
        n_starting_lines = 2
        n_profs = n_profs_siab
    elif n_profs_siab != int(n_profs_siab) and n_profs_siab_dummies == int(
        n_profs_siab_dummies
    ):
        data = "siab"
        dummies = True
        n_starting_lines = 2
        n_profs = n_profs_siab_dummies

    assert n_profs == int(n_profs)
    n_profs = int(n_profs)

    new = raw
    for k in range(1, n_profs):
        if dummies:
            new = nth_repl(
                new, r"\\", r"\\ \midrule", n_starting_lines + k * n_profs * 2
            )
        else:
            new = nth_repl(new, r"\\", r"\\ \midrule", n_starting_lines + k * n_profs)

    # workaround to get number of columns with coefficients
    if dummies:
        n_age_groups = "}".join(new.split("}")[:2]).count("r")
    else:
        n_age_groups = "}".join(new.split("}")[:2]).count("r") - 1

    new = new.replace(r"Previous sector", r"%Previous sector")
    if data == "siab":
        new = nth_repl(new, r"&", r"Previous sector &", 1)
        new = nth_repl(new, r"&", r"Current sector &", 2)
    else:
        print(n_age_groups)
        new = nth_repl(new, r"&", r"Previous sector &", np.floor(n_age_groups / 2) + 3)
        new = nth_repl(new, r"&", r"Current sector &", np.floor(n_age_groups / 2) + 4)

    if dummies:
        new = new.replace(
            r"\toprule",
            r"\toprule & & \multicolumn{%s}{c}{Age group} \\ \cmidrule{4-%s}"
            % (n_age_groups, n_age_groups + 2),
        )
    else:
        new = new.replace(
            r"\toprule",
            r"\toprule & & \multicolumn{%s}{c}{Age group} \\ \cmidrule{3-%s}"
            % (n_age_groups, n_age_groups + 2),
        )

    assert not new == raw
    waf_task.outputs[0].write(new)


def post_process_absolute_inequality_samples_table(waf_task):
    """Fix the column format of a LaTeX long table from "l" to p{}.

    """

    raw = waf_task.inputs[0].read()

    new = nth_repl(
        raw, r"\\", r"\\ \cmidrule(l){3-4} \cmidrule(l){5-6} \cmidrule(l){7-8}", 1
    )
    new = nth_repl(new, r"\\", r"\\ \iffalse", 2)
    new = nth_repl(new, r"\midrule", r"\fi \midrule", 1)

    assert not new == raw
    waf_task.outputs[0].write(new)


def post_process_inequality_component_table(waf_task):
    """Fix the column format of a LaTeX long table from "l" to p{}.

    """

    raw = waf_task.inputs[0].read()

    new = nth_repl(raw, r"\\", r"\\ \cmidrule(l){3-3} \cmidrule(l){4-8}", 1)
    new = nth_repl(new, r"\\", r"\\ \iffalse", 2)
    new = nth_repl(new, r"\midrule", r"\fi \midrule", 1)
    new = nth_repl(new, r"rrrr}", r"p{1cm}p{1cm}p{1cm}p{1cm}}", 1)

    assert not new == raw
    waf_task.outputs[0].write(new)


def post_process_skl_acc_in_wage_dist_table(waf_task):
    """Fix the column format of a LaTeX long table from "l" to p{}.

    """

    raw = waf_task.inputs[0].read()

    new = nth_repl(raw, r"\\", r"\\ \iffalse", 1)
    new = nth_repl(new, r"\midrule", r"\fi \midrule", 1)

    assert not new == raw
    waf_task.outputs[0].write(new)


def post_process_var_decomposition_table(waf_task):
    """Fix the column format of a LaTeX long table from "l" to p{}.

    """

    raw = waf_task.inputs[0].read()

    new = nth_repl(raw, r"\\", r"\\ \cmidrule(l){3-3} \cmidrule(l){4-8}", 1)
    new = nth_repl(new, r"\\", r"\\ \iffalse", 2)
    new = nth_repl(new, r"\midrule", r"\fi \midrule", 1)

    assert not new == raw
    waf_task.outputs[0].write(new)


def post_process_var_decomposition_table_exp(waf_task):
    """Fix the column format of a LaTeX long table from "l" to p{}.

    """

    raw = waf_task.inputs[0].read()

    new = nth_repl(raw, r"\\", r"\\ \cmidrule(l){3-3} \cmidrule(l){4-11}", 1)
    new = nth_repl(new, r"\\", r"\\ \iffalse", 2)
    new = nth_repl(new, r"\midrule", r"\fi \midrule", 1)
    new = nth_repl(new, r"llrrrrrrr", r"llrrrp{1cm}rp{1cm}rp{1cm}r", 1)

    assert not new == raw
    waf_task.outputs[0].write(new)


def post_process_var_decomposition_table_exp_formatted(waf_task):
    """Fix the column format of a LaTeX long table from "l" to p{}.

    """

    raw = waf_task.inputs[0].read()

    new = nth_repl(raw, r"\\", r"\\ \cmidrule(l){3-5} \cmidrule(l){6-6}", 1)
    new = nth_repl(new, r"\\", r"\\ \iffalse", 2)
    new = nth_repl(new, r"\midrule", r"\fi \midrule", 1)
    new = nth_repl(
        new,
        r"llllll",
        r"ll>{\raggedleft\arraybackslash}p{7.5ex}>{\raggedleft\arraybackslash}p{7.5ex}>{\raggedleft\arraybackslash}p{7.5ex}>{\raggedleft\arraybackslash}p{10ex}",
        1,
    )

    assert not new == raw
    waf_task.outputs[0].write(new)


def post_process_long_table_1(waf_task):
    """Fix the column format of a LaTeX long table from "l" to p{}.

    """

    raw = waf_task.inputs[0].read()

    new = raw.replace(
        "ll}",
        r"p{2.5cm}p{13cm}p{1cm}} \caption{Grouping of occupations} \label{tab:appdx-data:profession-occupation-mapping} \\",
    )
    new = new.replace(r"     &                    \\", "")

    assert not new == raw
    waf_task.outputs[0].write(new)


def build(ctx):
    def out_tables(*args):
        return ctx.path_to(ctx, "OUT_TABLES", *args)

    def out_siab(*args):
        return ctx.path_to(ctx, "MOCK_FDZ_IAB", "data", "results", *args)

    def out_mock_fdz(*args):
        return ctx.path_to(ctx, "MOCK_FDZ_IAB", *args)

    def in_specs(*args):
        return ctx.path_to(ctx, "IN_SPECS", *args)

    def in_other_data(*args):
        return ctx.path_to(ctx, "IN_OTHER_DATA", *args)

    def in_mappings(*args):
        return ctx.path_to(ctx, "IN_MAPPINGS", *args)

    def samples(data, remove=[], keep=[]):
        samples = []
        for file in os.listdir("src/specifications/{}_samples".format(data)):
            samples.append(file[:-5])

        if len(remove) > 0:
            for x in remove:
                try:
                    samples.remove(x)
                except Exception:
                    pass

        if len(keep) > 0:
            try:
                samples = list(filter(lambda x: x in samples, keep))
            except Exception:
                pass

        return samples

    def professions(
        group_dict, few_professions_only=False, many_professions_only=False
    ):

        if few_professions_only:
            return [
                str(x)
                for x in group_dict["USED_GROUPS"]
                if x < group_dict["CUTOFF_FOR_MANY_METHOD"]
            ]
        elif many_professions_only:
            return [
                str(x)
                for x in group_dict["USED_GROUPS"]
                if x >= group_dict["CUTOFF_FOR_MANY_METHOD"]
            ]
        else:
            return [str(x) for x in group_dict["USED_GROUPS"]]

    def get_methods(
        data,
        sample,
        n_prof,
        methods,
        only_main_method_small=False,
        only_main_method_large=False,
    ):

        if int(n_prof) >= profession_groups["CUTOFF_FOR_MANY_METHOD"]:
            if (sample in main_sample) and (only_main_method_large == False):
                return (
                    methods[data]["large_k_samples_main"]
                    + methods[data]["large_k_samples_rest"]
                )
            else:
                return methods[data]["large_k_samples_rest"]
        else:
            if (sample in main_sample) and (only_main_method_small == False):
                return (
                    methods[data]["small_k_samples_main"]
                    + methods[data]["small_k_samples_rest"]
                )
            elif (sample in main_sample) and (only_main_method_small == True):
                return (
                    methods[data]["small_k_samples_rest"]
                    + methods[data]["small_k_samples_important"]
                )
            else:
                return methods[data]["small_k_samples_rest"]

    def install(data, sample, n_prof, fdir, tables):
        install_dir = os.path.join(
            ctx.env.PROJECT_PATHS["RESULTS_FOR_PAPER"].abspath(),
            "tables",
            data,
            sample,
            n_prof,
            fdir,
        )
        for file_path in tables:
            file_name = os.path.split(file_path)[1]
            ctx.install_as(os.path.join(install_dir, file_name), file_path)

    with open("src/specifications/main_sample.json") as f:
        main_sample = [json.load(f)["MAIN_SAMPLE"]]

    with open("src/specifications/additional_important_samples.json") as f:
        additional_important_samples = json.load(f)

    with open("src/specifications/methods.json") as f:
        methods = json.load(f)

    with open("src/specifications/profession_groups.json") as f:
        profession_groups = json.load(f)

    # Descriptives Table: regression coefficients:
    n_prof = "120"
    for sample_name in [
        "from_25_to_54_base_1985",
        "from_25_to_34",
        "from_35_to_44",
        "from_45_to_54",
        "from_25_to_39",
        "from_40_to_54",
    ]:
        ctx(
            features="run_py_script",
            source="reg_coeffs_descriptives.py",
            target=[
                out_tables("siab", sample_name, n_prof, "reg_coeffs_descriptives.tex")
            ],
            deps=[
                out_siab(sample_name, n_prof, "datasets", "siab_mapping_profession.dta")
            ],
            append=f"{sample_name} {n_prof}",
        )

    # Construct table for text
    n_prof = "120"
    source = [
        out_tables("siab", sample_name, n_prof, "reg_coeffs_descriptives.tex")
        for sample_name in [
            "from_25_to_54_base_1985",
            # "from_25_to_39",
            # "from_40_to_54",
            "from_25_to_34",
            "from_35_to_44",
            "from_45_to_54",
        ]
    ]
    ctx(
        rule=post_process_reg_coeffs_descriptives,
        source=source,
        target=out_tables("siab", "reg_coeffs_descriptives_final.tex",),
    )

    data = "siab"

    ctx(
        features="run_py_script",
        source="overview_occupation_groups.py",
        target=[out_tables("_overview_occupation_groups.tex")],
        deps=[in_mappings("professions_kldb1988_iab.json")],
    )

    ctx(
        rule=post_process_long_table_1,
        source=out_tables("_overview_occupation_groups.tex"),
        target=out_tables("overview_occupation_groups.tex"),
    )

    for p in ["4"]:
        ctx(
            features="run_py_script",
            source="mean_task_measures_by_profession.py",
            target=[
                out_tables("mean_task_measures_by_profession_{}.tex".format(p))
            ],
            deps=[in_other_data("BIBB_tsk_by_profession_{}.dta".format(p))],
            append=[p],
        )

    tables_to_install = [
        out_tables("overview_occupation_groups.tex"),
        out_tables("mean_task_measures_by_profession_4.tex"),
    ]

    install_dir = os.path.join(
        ctx.env.PROJECT_PATHS["RESULTS_FOR_PAPER"].abspath(), "tables"
    )
    for file_path in tables_to_install:
        file_name = os.path.split(file_path)[1]
        ctx.install_as(os.path.join(install_dir, file_name), file_path)

    for sample in samples("siab"):
        for n_prof in professions(profession_groups, few_professions_only=True):
            for method in get_methods("siab", sample, n_prof, methods):
                tables_to_install = []

                if (not "cortes" in method) and (not "educ" in method):

                    ctx(
                        features="run_py_script",
                        source="switchers_gammas.py",
                        target=[
                            out_tables(
                                data,
                                sample,
                                n_prof,
                                "switchers_gammas",
                                method,
                                "_{}_switchers_gammas.tex".format(data),
                            )
                        ],
                        deps=[
                            eval(
                                "out_{}(sample, n_prof, 'skill_acc', '{}', '{}_skill_acc.dta')".format(
                                    data, method, data
                                )
                            )
                        ],
                        append=[data, sample, n_prof, method],
                    )

                    ctx(
                        rule=post_process_switchers_gammas,
                        source=out_tables(
                            data,
                            sample,
                            n_prof,
                            "switchers_gammas",
                            method,
                            "_{}_switchers_gammas.tex".format(data),
                        ),
                        target=out_tables(
                            data,
                            sample,
                            n_prof,
                            "switchers_gammas",
                            method,
                            "{}_switchers_gammas.tex".format(data),
                        ),
                    )

                    tables_to_install.append(
                        out_tables(
                            data,
                            sample,
                            n_prof,
                            "switchers_gammas",
                            method,
                            "{}_switchers_gammas.tex".format(data),
                        )
                    )

                    install(
                        data,
                        sample,
                        n_prof,
                        os.path.join("switchers_gammas", method),
                        tables_to_install,
                    )
                else:
                    pass

    for sample in samples("siab", keep=main_sample):
        for n_prof in professions(profession_groups, few_professions_only=True):

            tables_to_install = [
                out_tables(
                    "siab", sample, n_prof, "entrants", "siab_entrants_cohort.tex"
                )
            ]

            ctx(
                features="run_py_script",
                source="entrants_cohorts.py",
                target=tables_to_install,
                deps=[
                    out_siab(sample, n_prof, "entrants", "siab_entrants_cohort.dta")
                ],
                append=[sample, n_prof],
            )

            install("siab", sample, n_prof, "entrants", tables_to_install)

    for sample in samples("siab", keep=main_sample):
        for n_prof in professions(profession_groups, few_professions_only=True):

            tables_to_install = []

            for delta_t in 1, 2, 5:
                targets = []
                for filestub in [
                    "wages_switchers_pre",
                    "wages_switchers_post",
                    "percentage_switchers_cells",
                    "percentage_switchers_rows",
                    "percentage_switchers_columns",
                ]:
                    fp = out_tables(
                        "siab",
                        sample,
                        n_prof,
                        "wages_switchers",
                        "siab_profession_{}_delta_t{}.tex".format(
                            filestub, delta_t
                        ),
                    )
                    targets.append(fp)
                    tables_to_install.append(fp)

                ctx(
                    features="run_py_script",
                    source="wages_switchers.py",
                    target=targets,
                    deps=[out_mock_fdz("data", "siab_final_yearly.dta")],
                    append=[sample, n_prof, str(delta_t)],
                )

            install("siab", sample, n_prof, "wages_switchers", tables_to_install)

    wage_specs = ["obs", "c_s_ns_np_imp", "c_s_np", "c_s_o", "c_m0_o", "c_m_o"]

    for sample in samples("siab", keep=main_sample + additional_important_samples):
        for n_prof in professions(profession_groups, many_professions_only=True):
            for method in get_methods(
                "siab",
                sample,
                n_prof,
                methods,
                only_main_method_small=True,
                only_main_method_large=True,
            ):

                if sample == "period_length_5":
                    pass
                else:

                    tables_to_install = []
                    tables = []

                    for spec in wage_specs:

                        tables.append(
                            out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "var_decomposition",
                                method,
                                f"_siab_var_decomposition_{spec}.tex",
                            )
                        )

                    tables.append(
                        out_tables(
                            "siab",
                            sample,
                            n_prof,
                            "var_decomposition",
                            method,
                            f"_siab_var_decomposition_experiments.tex",
                        )
                    )

                    tables.append(
                        out_tables(
                            "siab",
                            sample,
                            n_prof,
                            "var_decomposition",
                            method,
                            f"_siab_var_decomposition_experiments_formatted.tex",
                        )
                    )

                    ctx(
                        features="run_py_script",
                        source="variance_decomposition.py",
                        target=tables,
                        deps=[
                            out_siab(
                                sample,
                                n_prof,
                                "counterfactuals",
                                method,
                                "siab_variance_decomposition.dta",
                            )
                        ],
                        append=[sample, n_prof, method],
                    )

                    for spec in wage_specs:

                        ctx(
                            rule=post_process_var_decomposition_table,
                            source=out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "var_decomposition",
                                method,
                                f"_siab_var_decomposition_{spec}.tex",
                            ),
                            target=out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "var_decomposition",
                                method,
                                f"siab_var_decomposition_{spec}.tex",
                            ),
                        )

                        tables_to_install.append(
                            out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "var_decomposition",
                                method,
                                f"siab_var_decomposition_{spec}.tex",
                            )
                        )

                    ctx(
                        rule=post_process_var_decomposition_table_exp,
                        source=out_tables(
                            "siab",
                            sample,
                            n_prof,
                            "var_decomposition",
                            method,
                            f"_siab_var_decomposition_experiments.tex",
                        ),
                        target=out_tables(
                            "siab",
                            sample,
                            n_prof,
                            "var_decomposition",
                            method,
                            f"siab_var_decomposition_experiments.tex",
                        ),
                    )

                    ctx(
                        rule=post_process_var_decomposition_table_exp_formatted,
                        source=out_tables(
                            "siab",
                            sample,
                            n_prof,
                            "var_decomposition",
                            method,
                            f"_siab_var_decomposition_experiments_formatted.tex",
                        ),
                        target=out_tables(
                            "siab",
                            sample,
                            n_prof,
                            "var_decomposition",
                            method,
                            f"siab_var_decomposition_experiments_formatted.tex",
                        ),
                    )

                    tables_to_install.append(
                        out_tables(
                            "siab",
                            sample,
                            n_prof,
                            "var_decomposition",
                            method,
                            f"siab_var_decomposition_experiments.tex",
                        )
                    )

                    tables_to_install.append(
                        out_tables(
                            "siab",
                            sample,
                            n_prof,
                            "var_decomposition",
                            method,
                            f"siab_var_decomposition_experiments_formatted.tex",
                        )
                    )

                    install(
                        "siab",
                        sample,
                        n_prof,
                        os.path.join("var_decomposition", method),
                        tables_to_install,
                    )

    for sample in samples("siab", keep=main_sample + additional_important_samples):
        for n_prof in professions(profession_groups, many_professions_only=True):
            for method in get_methods(
                "siab",
                sample,
                n_prof,
                methods,
                only_main_method_small=True,
                only_main_method_large=True,
            ):

                if sample == "period_length_5":
                    pass
                else:

                    components_raw = []
                    tables_to_install = []

                    for order in permutations("aps", 3):
                        order_str = "".join(order)
                        components_raw.append(
                            out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "inequality_components",
                                method,
                                "_siab_ineq_components_order_{}.tex".format(
                                    order_str
                                ),
                            )
                        )

                        components_raw.append(
                            out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "inequality_components",
                                method,
                                "_siab_abs_ineq_components_order_{}.tex".format(
                                    order_str
                                ),
                            )
                        )
                        tables_to_install.append(
                            out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "inequality_components",
                                method,
                                "siab_ineq_components_order_{}.tex".format(
                                    order_str
                                ),
                            )
                        )

                        tables_to_install.append(
                            out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "inequality_components",
                                method,
                                "siab_abs_ineq_components_order_{}.tex".format(
                                    order_str
                                ),
                            )
                        )

                    ctx(
                        features="run_py_script",
                        source="inequality_components.py",
                        target=components_raw,
                        deps=[
                            out_siab(
                                sample,
                                n_prof,
                                "counterfactuals",
                                method,
                                "siab_counterfactual_change_in_wage_dist_by_year.dta",
                            )
                        ],
                        append=[sample, n_prof, method],
                    )

                    for order in permutations("aps", 3):
                        order_str = "".join(order)
                        ctx(
                            rule=post_process_inequality_component_table,
                            source=out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "inequality_components",
                                method,
                                "_siab_ineq_components_order_{}.tex".format(
                                    order_str
                                ),
                            ),
                            target=out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "inequality_components",
                                method,
                                "siab_ineq_components_order_{}.tex".format(
                                    order_str
                                ),
                            ),
                        )

                        ctx(
                            rule=post_process_inequality_component_table,
                            source=out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "inequality_components",
                                method,
                                "_siab_abs_ineq_components_order_{}.tex".format(
                                    order_str
                                ),
                            ),
                            target=out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "inequality_components",
                                method,
                                "siab_abs_ineq_components_order_{}.tex".format(
                                    order_str
                                ),
                            ),
                        )

                    install(
                        "siab",
                        sample,
                        n_prof,
                        os.path.join("inequality_components", method),
                        tables_to_install,
                    )

    for n_prof in professions(profession_groups, many_professions_only=True):
        for method in get_methods(
            "siab",
            sample,
            n_prof,
            methods,
            only_main_method_small=True,
            only_main_method_large=True,
        ):

            deps = []
            samples_to_merge = []

            for sample in [main_sample[0], "filled_ue_and_olf", "no_foreigners"]:
                samples_to_merge.append(sample)

                deps.append(
                    out_siab(
                        sample,
                        n_prof,
                        "counterfactuals",
                        method,
                        "siab_counterfactual_change_in_wage_dist_by_year.dta",
                    )
                )

            tables_to_install = []
            tables_to_install.append(
                out_tables("siab", "siab_absolute_inequality.tex")
            )

            components_raw = []
            components_raw.append(
                out_tables("siab", "_siab_absolute_inequality.tex")
            )
            ctx(
                features="run_py_script",
                source="inequality_components_sample_comparison.py",
                target=components_raw,
                deps=deps,
                append=["--".join(samples_to_merge), n_prof, method],
            )

            ctx(
                rule=post_process_absolute_inequality_samples_table,
                source=out_tables("siab", "_siab_absolute_inequality.tex"),
                target=out_tables("siab", "siab_absolute_inequality.tex"),
            )

    install_dir = os.path.join(
        ctx.env.PROJECT_PATHS["RESULTS_FOR_PAPER"].abspath(), "tables/siab"
    )
    for file_path in tables_to_install:
        file_name = os.path.split(file_path)[1]
        ctx.install_as(os.path.join(install_dir, file_name), file_path)

    for sample in samples("siab", keep=main_sample + additional_important_samples):
        for n_prof in professions(profession_groups):
            for method in get_methods(
                "siab",
                sample,
                n_prof,
                methods,
                only_main_method_small=True,
                only_main_method_large=True,
            ):

                components_raw = []
                tables_to_install = []

                components_raw.append(
                    out_tables(
                        "siab",
                        sample,
                        n_prof,
                        "skill_acc_in_wage_dist",
                        method,
                        "_siab_skill_acc_by_pct_c_s_np.tex",
                    )
                )

                tables_to_install.append(
                    out_tables(
                        "siab",
                        sample,
                        n_prof,
                        "skill_acc_in_wage_dist",
                        method,
                        "siab_skill_acc_by_pct_c_s_np.tex",
                    )
                )

                ctx(
                    features="run_py_script",
                    source="skl_acc_by_percentile.py",
                    target=components_raw,
                    deps=[
                        out_siab(
                            sample,
                            n_prof,
                            "counterfactuals",
                            method,
                            "siab_average_skill_acc_by_percentile_c_s_np.dta",
                        )
                    ],
                    append=[sample, n_prof, method],
                )

                ctx(
                    rule=post_process_skl_acc_in_wage_dist_table,
                    source=out_tables(
                        "siab",
                        sample,
                        n_prof,
                        "skill_acc_in_wage_dist",
                        method,
                        "_siab_skill_acc_by_pct_c_s_np.tex",
                    ),
                    target=out_tables(
                        "siab",
                        sample,
                        n_prof,
                        "skill_acc_in_wage_dist",
                        method,
                        "siab_skill_acc_by_pct_c_s_np.tex",
                    ),
                )

                install(
                    "siab",
                    sample,
                    n_prof,
                    os.path.join("skill_acc_in_wage_dist", method),
                    tables_to_install,
                )

    for sample in samples("siab"):
        for n_prof in professions(profession_groups):
            for method in get_methods(
                "siab",
                sample,
                n_prof,
                methods,
                only_main_method_small=True,
                only_main_method_large=True,
            ):
                for typ_short, typ_long in {
                    "groups": "groups",
                    "end_acc": "changing_entrants_and_accumulation",
                }.items():
                    for n_age_cats in ("1", "2", "3"):
                        data_dep = out_siab(
                            sample,
                            n_prof,
                            "decompositions",
                            method,
                            f"siab_decompose_selection_into_{typ_long}_by_{n_age_cats}_age_cats.dta",
                        )
                        if typ_short == "groups":
                            deps = data_dep
                            post_process_rule = (
                                post_process_growth_selection_decompositions_groups
                            )
                        elif typ_short == "end_acc":
                            deps = [data_dep, "selection_components_groups.py"]
                            post_process_rule = (
                                post_process_growth_selection_decompositions_end_acc
                            )
                        else:
                            raise ValueError(typ_short)
                        table = f"growth_sel_decomp_{typ_short}_{n_age_cats}"
                        ctx(
                            features="run_py_script",
                            source=f"selection_components_{typ_long}.py",
                            target=[
                                out_tables(
                                    "siab",
                                    sample,
                                    n_prof,
                                    "selection_components",
                                    method,
                                    f"_{table}.tex",
                                ),
                            ],
                            deps=deps,
                            append=[sample, n_prof, method, n_age_cats],
                        )

                        ctx(
                            rule=post_process_rule,
                            source=out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "selection_components",
                                method,
                                f"_{table}.tex",
                            ),
                            target=out_tables(
                                "siab",
                                sample,
                                n_prof,
                                "selection_components",
                                method,
                                f"{table}.tex",
                            ),
                        )
