# replicacao_metaanalise_protestos_v0_3.py
# Metanálise exploratória: táticas de protesto e apoio público
# Entrada padrão: efeitos_extraidos_v0_3_ampliado.csv
# Saídas: tabelas e gráficos em PNG.
# Requisitos: pandas, numpy, matplotlib

import math
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

INPUT = Path("efeitos_extraidos_v0_3_ampliado.csv")
OUTDIR = Path("resultados_v0_3")
OUTDIR.mkdir(exist_ok=True)

def dl_meta(data):
    data = data.dropna(subset=["hedges_g", "variancia_g"]).copy()
    y = data["hedges_g"].astype(float).to_numpy()
    v = data["variancia_g"].astype(float).to_numpy()
    wi = 1 / v
    fixed = np.sum(wi * y) / np.sum(wi)
    q = np.sum(wi * (y - fixed) ** 2)
    k = len(y)
    df = k - 1
    c = np.sum(wi) - np.sum(wi ** 2) / np.sum(wi)
    tau2 = max(0.0, (q - df) / c) if k > 1 and c > 0 else 0.0
    w = 1 / (v + tau2)
    mu = np.sum(w * y) / np.sum(w)
    se = math.sqrt(1 / np.sum(w))
    ci_low, ci_high = mu - 1.96 * se, mu + 1.96 * se
    i2 = max(0.0, (q - df) / q) * 100 if q > 0 and k > 1 else 0.0
    pred_se = math.sqrt(tau2 + se ** 2)
    pred_low, pred_high = mu - 1.96 * pred_se, mu + 1.96 * pred_se
    return {
        "k": k, "hedges_g": mu, "erro_padrao": se,
        "ic95_inferior": ci_low, "ic95_superior": ci_high,
        "Q": q, "gl": df, "I2": i2, "tau2": tau2,
        "intervalo_preditivo_inferior": pred_low,
        "intervalo_preditivo_superior": pred_high,
    }

def forest_plot(data, summary, title, outfile):
    data = data.copy().sort_values("hedges_g")
    labels = data["autores_ano"].astype(str) + " | " + data["id_estudo"].astype(str) + " | " + data["desfecho"].astype(str)
    y = np.arange(len(data))
    fig, ax = plt.subplots(figsize=(9, max(4, 0.42 * len(data) + 2)))
    x = data["hedges_g"].astype(float).to_numpy()
    lo = data["ic95_inferior"].astype(float).to_numpy()
    hi = data["ic95_superior"].astype(float).to_numpy()
    ax.errorbar(x, y, xerr=[x - lo, hi - x], fmt="o", capsize=3)
    ax.axvline(0, linestyle="--", linewidth=1)
    ax.axvline(summary["hedges_g"], linestyle="-", linewidth=1)
    ax.set_yticks(y)
    ax.set_yticklabels(labels, fontsize=8)
    ax.set_xlabel("Hedges g (negativo = menor apoio sob tática disruptiva)")
    ax.set_title(title)
    ax.grid(axis="x", linestyle=":", linewidth=0.7)
    subtitle = (
        f"Modelo DL: g = {summary['hedges_g']:.3f}, "
        f"IC95% [{summary['ic95_inferior']:.3f}; {summary['ic95_superior']:.3f}], "
        f"I² = {summary['I2']:.1f}%, tau² = {summary['tau2']:.3f}"
    )
    ax.text(0, -0.16, subtitle, transform=ax.transAxes, fontsize=8)
    fig.tight_layout()
    fig.savefig(outfile, dpi=300, bbox_inches="tight")
    plt.close(fig)

def funnel_plot(data, title, outfile):
    fig, ax = plt.subplots(figsize=(6, 5))
    ax.scatter(data["hedges_g"].astype(float), data["erro_padrao_g"].astype(float))
    ax.axvline(0, linestyle="--", linewidth=1)
    ax.set_xlabel("Hedges g")
    ax.set_ylabel("Erro-padrão")
    ax.set_title(title)
    ax.invert_yaxis()
    ax.grid(linestyle=":", linewidth=0.7)
    fig.tight_layout()
    fig.savefig(outfile, dpi=300, bbox_inches="tight")
    plt.close(fig)

def main():
    df = pd.read_csv(INPUT)
    for col in ["hedges_g", "variancia_g", "erro_padrao_g", "ic95_inferior", "ic95_superior"]:
        df[col] = pd.to_numeric(df[col], errors="coerce")

    main_ids = [
        "E_JOLY2025_004", "E_SIMPSON2022_001",
        "E_FEINBERG2020_001", "E_FEINBERG2020_003", "E_FEINBERG2020_005",
        "E_FEINBERG2020_007", "E_FEINBERG2020_009",
        "E_NYLUND2025_001", "E_NYLUND2025_002",
    ]
    cause_ids = [
        "E_JOLY2025_002", "E_FEINBERG2020_002", "E_FEINBERG2020_004",
        "E_FEINBERG2020_006", "E_FEINBERG2020_008", "E_FEINBERG2020_010",
    ]
    flank_ids = ["E_SIMPSON2022_002", "E_SIMPSON2022_003"]

    specs = {
        "apoio_movimento_preliminar": main_ids,
        "apoio_causa_preliminar": cause_ids,
        "radical_flank_preliminar": flank_ids,
    }

    rows = []
    for name, ids in specs.items():
        dat = df[df["id_efeito"].isin(ids)].copy()
        summary = dl_meta(dat)
        summary["modelo"] = name
        rows.append(summary)
        forest_plot(dat, summary, name, OUTDIR / f"forest_{name}.png")
        if name == "apoio_movimento_preliminar":
            funnel_plot(dat, "Funnel plot preliminar: apoio ao grupo/movimento", OUTDIR / "funnel_apoio_movimento_preliminar.png")

    pd.DataFrame(rows).to_csv(OUTDIR / "modelos_preliminares_v0_3.csv", index=False)

if __name__ == "__main__":
    main()
