"""
Example analysis — father's socioeconomic rank by laureate birth decade.

Why this file exists:
    A template showing how to run your OWN question against the replication
    data. It is NOT in the paper: it asks whether the socioeconomic rank of
    Nobel laureates' fathers has shifted across the laureates' birth decades.

    It follows the same contract as every generator in ../../ : read from
    data/, write only into this folder's output/. Copy this folder
    as a starting point for your own analysis.

Inputs:  data/nobelists_analysis.csv
Outputs: output/father_rank_by_decade.json  (+ a table printed to stdout)
"""

import json
from pathlib import Path

import pandas as pd

# Resolve paths relative to this file so the script runs from anywhere. The
# package root is the nearest parent holding both data/ and code/, so this
# script keeps working when copied to code/<name>/ as a template.
HERE = Path(__file__).resolve().parent
PACKAGE_ROOT = next(p for p in HERE.parents if (p / "data").is_dir() and (p / "code").is_dir())
DATA = PACKAGE_ROOT / "data" / "nobelists_analysis.csv"
OUT_DIR = HERE / "output"
OUT_DIR.mkdir(exist_ok=True)

# The three father-rank measures the paper builds (national median-income rank,
# global median-income rank, and education rank), each a 0-100 percentile.
RANKS = {
    "mean_med_inctot_rank": "med_inctot_rank",
    "mean_global_med_inctot_rank": "global_med_inctot_rank",
    "mean_educ_rank": "educ_rank",
}


def main() -> None:
    df = pd.read_csv(DATA, low_memory=False)

    # `cohort` is the laureate's birth decade (e.g. 1910, 1940). Keep rows that
    # have a decade and at least the primary rank measure.
    df = df.dropna(subset=["cohort", "med_inctot_rank"]).copy()
    df["decade"] = df["cohort"].astype(int)

    rows = []
    for decade, g in df.groupby("decade"):
        row = {"decade": int(decade), "n": int(len(g))}
        for out_col, src_col in RANKS.items():
            row[out_col] = round(float(g[src_col].mean()), 2)
        rows.append(row)
    rows.sort(key=lambda r: r["decade"])

    (OUT_DIR / "father_rank_by_decade.json").write_text(
        json.dumps(rows, indent=2) + "\n"
    )

    # Print a readable table.
    print(f"{'decade':>7} {'n':>4} {'inc_rank':>9} {'global':>8} {'educ':>7}")
    for r in rows:
        print(
            f"{r['decade']:>7} {r['n']:>4} "
            f"{r['mean_med_inctot_rank']:>9} "
            f"{r['mean_global_med_inctot_rank']:>8} "
            f"{r['mean_educ_rank']:>7}"
        )


if __name__ == "__main__":
    main()
