"""
title: Summary statistics table
summary: The "Table 1" of an empirical paper — N, mean, SD, min, median and max per variable in panels, with group means and a test of their difference.
r: modelsummary::datasummary_balance()
tags: [summary statistics, descriptive statistics, balance table, Welch t-test, great tables, migration]
description: |
  Before any model, a paper describes its data. This table gives, for every
  variable, the number of non-missing observations, the mean, standard deviation,
  minimum, median and maximum, grouped in **panels** (outcome, individual
  characteristics, networks). The right-hand block compares the two groups that
  the paper is about — here respondents who intend to stay and those who intend
  to move — with the **difference in means** and stars from a Welch *t*-test, as
  in a balance table.

  Everything is formatted by **Great Tables** itself rather than with Python
  strings: `fmt_integer()` and `fmt_number()` (with `drop_trailing_zeros` so that
  0/1 variables show 0 and 1), `cols_merge()` to attach the stars to the
  difference, `sub_missing()` to leave cells blank, `tab_stub()` panels from a
  group column with `tab_stub_indent()`, and `gtsave()`, the current way to
  export a PNG (it replaces the Selenium-based `save()`). The look matches the
  regression table in this family: serif type, small-caps title and horizontal
  rules only.

  The setting is Blakely & Warin (2012, *Global Economy Journal*): choice or
  mimetism in the decision to migrate in Europe. The data are **simulated** for
  illustration — they are not the paper's data or results: 2,500 survey
  respondents, with household income missing for about 6% of them, so N differs
  across rows.
"""
import numpy as np
import pandas as pd
from scipy import stats
from great_tables import GT, loc, style
# Simulated data, set in the context of Blakely & Warin (2012) [blakely2012]

# Data: 2,500 respondents; younger, unemployed and better-connected people plan to move
rng = np.random.default_rng(2012)
n = 2500
age = rng.uniform(18, 70, n).round()
tertiary = rng.binomial(1, 0.3, n)
unemployed = rng.binomial(1, 0.1, n)
network = rng.binomial(1, 0.35, n)
contacts = rng.poisson(0.6 + 2.2 * network)
satisfaction = rng.integers(1, 11, n)
income = np.exp(rng.normal(3.3 + 0.35 * tertiary - 0.4 * unemployed, 0.45, n)).round(1)
income[rng.random(n) < 0.06] = np.nan                     # item non-response
eta = -0.2 - 0.045 * age + 0.35 * tertiary + 0.7 * unemployed + 0.95 * network - 0.12 * satisfaction
move = rng.binomial(1, 1 / (1 + np.exp(-eta)))
df = pd.DataFrame({"move": move, "age": age, "female": rng.binomial(1, 0.52, n),
                   "tertiary": tertiary, "unemployed": unemployed, "income": income,
                   "satisfaction": satisfaction, "network": network, "contacts": contacts})

panels = {
    "Panel A. Outcome": {"move": "Intends to move abroad (0/1)"},
    "Panel B. Individual characteristics": {
        "age": "Age (years)", "female": "Female (0/1)", "tertiary": "Tertiary education (0/1)",
        "unemployed": "Unemployed (0/1)", "income": "Household income (€ thousand per year)",
        "satisfaction": "Life satisfaction (1–10)"},
    "Panel C. Networks": {
        "network": "Family or friends abroad (0/1)", "contacts": "Contacts abroad (number)"},
}

# One row per variable: full-sample statistics, then group means and Welch t-test
rows = []
for panel, variables in panels.items():
    for var, label in variables.items():
        x = df[var].dropna()
        row = {"panel": panel, "variable": label, "N": len(x), "mean": x.mean(), "sd": x.std(),
               "min": x.min(), "median": x.median(), "max": x.max()}
        if var != "move":                                   # the outcome defines the groups
            stay, go = x[df.move == 0], x[df.move == 1]
            t = stats.ttest_ind(go, stay, equal_var=False)
            row |= {"stay": stay.mean(), "go": go.mean(), "diff": go.mean() - stay.mean(),
                    "stars": "***" if t.pvalue < .01 else "**" if t.pvalue < .05 else "*" if t.pvalue < .1 else ""}
        rows.append(row)
tab = pd.DataFrame(rows)
n_stay, n_go = (df.move == 0).sum(), (df.move == 1).sum()

full = ["N", "mean", "sd", "min", "median", "max"]
groups = ["stay", "go", "diff"]
table = (
    GT(tab)
    .tab_stub(rowname_col="variable", groupname_col="panel")
    .tab_stub_indent(rows=list(range(len(tab))), indent=2)
    .tab_header(title="TABLE II", subtitle="Descriptive statistics")
    .tab_spanner(label="Full sample", columns=full, id="full")
    .tab_spanner(label="Mean by intention", columns=groups, id="groups")
    .cols_label(N="N", mean="Mean", sd="SD", min="Min", median="Median", max="Max",
                stay=f"Stay ({n_stay:,})", go=f"Move ({n_go:,})", diff="Difference")
    .fmt_integer(columns="N")
    .fmt_number(columns=["mean", "sd", "stay", "go", "diff"], decimals=2)
    .fmt_number(columns=["min", "median", "max"], decimals=1, drop_trailing_zeros=True)
    .cols_merge(columns=["diff", "stars"], pattern="<<{0}{1}>>")   # stars glued to the difference
    .sub_missing(columns=groups, missing_text="")
    .cols_align("center", columns=full + groups)
    .tab_source_note(f"Notes: n = {n:,} respondents (simulated). N counts non-missing observations; "
                     f"household income is missing for {df.income.isna().sum()} respondents.")
    .tab_source_note("Difference = Move − Stay, with stars from Welch t-tests of equal means: "
                     "*p < 0.1; **p < 0.05; ***p < 0.01.")
    # Same journal look as Table I: serif type, small-caps title, horizontal rules only
    .opt_table_font(font=["Latin Modern Roman", "Times New Roman", "Georgia", "serif"])
    .tab_options(
        table_width="900px", table_font_size="15px", table_font_color="#000",
        heading_title_font_size="15px", heading_subtitle_font_size="15px", heading_padding="1px",
        table_border_top_style="hidden", table_border_bottom_style="hidden",
        heading_border_bottom_style="none",
        column_labels_border_top_style="solid", column_labels_border_top_width="1.5px",   # top rule
        column_labels_border_top_color="#000",
        column_labels_border_bottom_style="solid", column_labels_border_bottom_width="1px",
        column_labels_border_bottom_color="#000",
        table_body_border_top_style="solid", table_body_border_top_width="1px",
        table_body_border_top_color="#000",
        row_group_border_top_style="none", row_group_border_bottom_style="none",
        row_group_padding="6px",
        table_body_hlines_style="none", stub_border_style="none",
        table_body_border_bottom_style="solid", table_body_border_bottom_width="1.5px",
        table_body_border_bottom_color="#000",
        data_row_padding="3px", source_notes_font_size="13px", source_notes_padding="1px",
    )
    .tab_style(style.css("font-variant: small-caps; padding-bottom: 8px;"), loc.subtitle())
    .tab_style(style.text(style="italic"), [loc.row_groups(), loc.spanner_labels(ids=["full", "groups"])])
)
table.show()
