import sys, warnings; warnings.filterwarnings("ignore")
import pandas as pd, numpy as np
from scipy import stats
import statsmodels.formula.api as smf
import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
from docx import Document
from docx.shared import Pt, Inches
src, out = sys.argv[1], sys.argv[2]
d = pd.read_csv(src, sep=None, engine="python", encoding="utf-8-sig")
y = d["AÑO"]; d = d.apply(lambda s: pd.to_numeric(s.astype(str).str.strip().str.replace(",", "."), errors="coerce")); d["YEAR"] = y.astype(int)
d["W24"] = (d.YEAR == 2024).astype(int); d["G"] = d.GENERO.where(d.GENERO.isin([1, 2]))
d["PROB"] = d.PROB_USO_BIOCOM.where(d.PROB_USO_BIOCOM >= 1)
plt.rcParams.update({"font.family": "Arial", "font.size": 9, "axes.spines.top": False, "axes.spines.right": False})
doc = Document(); doc.styles["Normal"].font.name = "Palatino Linotype"; doc.styles["Normal"].font.size = Pt(10)
doc.add_paragraph().add_run("Supplementary Materials S2 — The Social Dimension of the Circular Bioeconomy: Public Attitudes Towards and Acceptance of Biorefineries in Madrid, Spain").bold = True
def tab(title, header, rows, note=None):
    doc.add_paragraph(title)
    t = doc.add_table(rows=1, cols=len(header)); t.style = "Table Grid"
    for i, h in enumerate(header):
        r = t.rows[0].cells[i].paragraphs[0].add_run(h); r.bold = True; r.font.size = Pt(8)
    for row in rows:
        c = t.add_row().cells
        for i, v in enumerate(row): c[i].paragraphs[0].add_run(str(v)).font.size = Pt(8)
    if note: doc.add_paragraph(note).runs[0].font.size = Pt(8)
    doc.add_paragraph()
LAB = {"SOS_ACUERDO_CC":"Q9.1 Urgent climate action","SOS_ACUERDO_CIRC":"Q9.2 Circular economy","SOS_ACUERDO_SECTORES":"Q9.3 Aware of sectoral measures","SOS_ACUERDO_PRODUCTOS":"Q9.4 New solutions organic waste","SOS_ACUERDO_COMBUSTIBLES":"Q9.5 Promote sustainable fuels","SOS_ACUERDO_GEST_RESIDUOS":"Q9.6 Informed: own waste","SOS_ACUERDO_BIOGAS":"Q9.7 Informed: waste-derived fuels","SOS_ACUERDO_PLANTAS":"Q9.8 Informed: treatment plants",
"ACT_SOST":"Sustainability attitude index","CONOC_SOST":"Perceived knowledge index","ACUERDO_SEPARAR":"Q13.1 Separation is essential","ACUERDO_SEPARO_SIEMPRE":"Q13.2 I always separate","ACUERDO_INCINERACION":"Q13.3 Incineration most effective","ACUERDO_VERTIDO":"Q13.4 Landfill most effective","ACUERDO_PIROLISIS":"Q13.5 Pyrolysis most effective","ACUERDO_COMPOSTAJE":"Q13.6 Composting most effective",
"TRAT_RANK_COMPOSTAJE_INV":"Q12 Composting priority (1–4)","TRAT_RANK_PIROLISIS_INV":"Q12 Pyrolysis priority (1–4)","TRAT_RANK_VERTIDO_INV":"Q12 Landfill priority (1–4)","TRAT_RANK_INCINERACION_INV":"Q12 Incineration priority (1–4)","PROB":"Q14 Willingness to use biofuels",
"ACUERDO_BIOREF_MOLESTIAS_BENEFICIOS":"Q17.1 Benefits outweigh nuisances","ACUERDO_BIOREF_NO_CERCA":"Q17.2 Not near my home","ACUERDO_BIOREF_SOSTENIBLES":"Q17.3 More sustainable model","ACUERDO_BIOREF_CONFIANZA":"Q17.4 Trust","ACUERDO_BIOREF_PAGARIA_MAS":"Q17.5 Would pay more","DISTANCIA_MIN_BIOREF":"Q18 Minimum distance (km)"}
rows = []
for v, l in LAB.items():
    a = d.loc[d.YEAR == 2022, v].dropna(); b = d.loc[d.YEAR == 2024, v].dropna()
    t = stats.ttest_ind(a, b, equal_var=False)
    sp = np.sqrt(((len(a)-1)*a.var()+(len(b)-1)*b.var())/(len(a)+len(b)-2))
    x = d[[v, "W24", "G", "EDAD_CAT", "NIVEL_ESTUDIOS", "INGRESOS"]].dropna()
    m = smf.ols(f"{v} ~ W24 + C(G) + C(EDAD_CAT) + C(NIVEL_ESTUDIOS) + C(INGRESOS)", x).fit(cov_type="HC3"); ci = m.conf_int().loc["W24"]
    rows.append([l, f"{a.mean():.2f} ({a.std():.2f}); {len(a)}", f"{b.mean():.2f} ({b.std():.2f}); {len(b)}", f"{t.pvalue:.3f}", f"{(a.mean()-b.mean())/sp:.2f}", f"{m.params['W24']:.2f} [{ci[0]:.2f}, {ci[1]:.2f}]", f"{m.pvalues['W24']:.3f}"])
tab("Table S1. Wave comparisons for all scale items (means, SD and valid n).", ["Item", "2022 M (SD); n", "2024 M (SD); n", "Welch p", "d", "Adjusted diff. [95% CI]", "Adj. p"], rows,
    "Adjusted difference: OLS coefficient for 2024, controlling for gender, age group, education and income; HC3 standard errors. Rankings were reversed so that higher = higher priority. Exploratory; no correction for multiple testing.")
def rankrows(cols, labels, kmax):
    rr = []
    for c, l in zip(cols, labels):
        r = []
        for yr in [2022, 2024]:
            s = d.loc[d.YEAR == yr, c].dropna(); r += [f"{(s == 1).mean()*100:.1f}", f"{(s <= 3).mean()*100:.1f}"]
        sub = d[["YEAR", c]].dropna(); ct = pd.crosstab(sub.YEAR, sub[c] <= 3); rr.append([l] + r + [f"{stats.chi2_contingency(ct)[1]:.3f}"])
    return rr
H = ["Option", "2022 % first", "2022 % top 3", "2024 % first", "2024 % top 3", "p (top 3)"]
c10 = ["COMB_RANK_REDISEÑAR","COMB_RANK_REDUCIR","COMB_RANK_REUTILIZAR","COMB_RANK_REPARAR","COMB_RANK_RENOVAR","COMB_RANK_RECUPERAR","COMB_RANK_RECICLAR"]
tab("Table S2a. Q10 Priority of actions to combat climate change (ranking of 7).", H, rankrows(c10, ["Redesign","Reduce","Reuse","Repair","Renew","Recover","Recycle"], 7))
c11 = ["PRE_RANK_AIRE","PRE_RANK_SEG_ALIMENT","PRE_RANK_BIODIVERSIDAD","PRE_RANK_ELIM_RESIDUOS","PRE_RANK_RECURSOS","PRE_RANK_CONT_AGUA","PRE_RANK_IMPACTO_SOCIOEC","PRE_RANK_DDHH"]
tab("Table S2b. Q11 Environmental and socioeconomic concerns (ranking of 8).", H, rankrows(c11, ["Air pollution","Food security","Biodiversity loss/soil degradation","Waste disposal","Natural resource depletion","Water pollution/scarcity","Socioeconomic impact of climate change","Human rights in value chains"], 8))
c15 = ["RAZF_RANK_SI_ECONOMICOS","RAZF_RANK_SI_EFICIENTES","RAZF_RANK_SI_SEGUROS","RAZF_RANK_MEDIOAMBIENTE","RAZF_RANK_AYUDAS","RAZF_RANK_EMPLEO_LOCAL"]
tab("Table S2c. Q15 Reasons to use biofuels (ranking of 6).", H, rankrows(c15, ["Cheaper","More efficient","Safer","Better for the environment","Economic incentives","Local employment"], 6))
c16 = ["RAZC_RANK_NO_CAROS","RAZC_RANK_NO_MENOS_EFICIENTES","RAZC_RANK_NO_MENOS_SEGUROS","RAZC_RANK_NO_MOLESTIAS","RAZC_RANK_NO_CAMBIOS_INSTAL","RAZC_RANK_NO_NO_PROBADO","RAZC_RANK_NO_SIN_AYUDAS"]
tab("Table S2d. Q16 Reasons not to use biofuels (ranking of 7).", H, rankrows(c16, ["More expensive","Less efficient","Less safe","Nuisances (e.g., odours)","Changes to installation","Not sufficiently tested","No economic incentives"], 7))
# Figure S1
f, (a1, a2) = plt.subplots(1, 2, figsize=(6.8, 2.6))
tc = ["TRAT_RANK_COMPOSTAJE","TRAT_RANK_PIROLISIS","TRAT_RANK_VERTIDO","TRAT_RANK_ICINERACION"]; tl = ["Composting","Pyrolysis","Controlled landfill","Incineration"]
x = np.arange(4); w = 0.38
a1.bar(x-w/2, [(d[d.YEAR==2022][c]==1).sum()/d[d.YEAR==2022][c].notna().sum()*100 for c in tc], w, color="#7FA7C9", label="2022")
a1.bar(x+w/2, [(d[d.YEAR==2024][c]==1).sum()/d[d.YEAR==2024][c].notna().sum()*100 for c in tc], w, color="#1F4E79", label="2024")
a1.set_xticks(x); a1.set_xticklabels(tl, fontsize=7); a1.set_ylabel("% ranking first (Q12)"); a1.legend(frameon=False); a1.set_title("(a)", loc="left")
ec = ["ACUERDO_COMPOSTAJE","ACUERDO_PIROLISIS","ACUERDO_VERTIDO","ACUERDO_INCINERACION"]
a2.bar(x-w/2, [d[d.YEAR==2022][c].mean() for c in ec], w, color="#7FA7C9"); a2.bar(x+w/2, [d[d.YEAR==2024][c].mean() for c in ec], w, color="#1F4E79")
a2.set_xticks(x); a2.set_xticklabels(tl, fontsize=7); a2.set_ylabel("Mean agreement 'most effective' (Q13, 1–5)"); a2.set_ylim(1, 5); a2.set_title("(b)", loc="left")
f.tight_layout(); f.savefig(f"{out}/FigureS1.png", dpi=600); plt.close(f)
doc.add_paragraph("Figure S1. (a) Percentage ranking each waste treatment first among four options (Q12). (b) Mean agreement that each treatment is the most effective (Q13).")
doc.add_picture(f"{out}/FigureS1.png", width=Inches(6.2))
# Figure S2 heatmap
V = ["ACUERDO_BIOREF_MOLESTIAS_BENEFICIOS","ACUERDO_BIOREF_NO_CERCA","ACUERDO_BIOREF_SOSTENIBLES","ACUERDO_BIOREF_CONFIANZA","ACUERDO_BIOREF_PAGARIA_MAS","DISTANCIA_MIN_BIOREF","PROB","ACT_SOST","CONOC_SOST"]
VL = ["Benefits > nuisances","Not near home","Sustainable model","Trust","Pay more","Min. distance","Use biofuels","Sust. attitude","Perc. knowledge"]
C = d[V].corr(method="spearman").values
f, ax = plt.subplots(figsize=(5.6, 4.6)); im = ax.imshow(C, cmap="RdBu_r", vmin=-1, vmax=1)
ax.set_xticks(range(9)); ax.set_yticks(range(9)); ax.set_xticklabels(VL, rotation=45, ha="right", fontsize=7); ax.set_yticklabels(VL, fontsize=7)
for i in range(9):
    for j in range(9): ax.text(j, i, f"{C[i,j]:.2f}", ha="center", va="center", fontsize=6, color="white" if abs(C[i,j]) > 0.5 else "black")
f.colorbar(im, shrink=0.8, label="Spearman ρ"); f.tight_layout(); f.savefig(f"{out}/FigureS2.png", dpi=600); plt.close(f)
doc.add_paragraph("Figure S2. Spearman correlations among biorefinery perception variables, willingness to use biofuels and sustainability indices (pairwise deletion; n = 932–1016).")
doc.add_picture(f"{out}/FigureS2.png", width=Inches(5.6))
doc.save(f"{out}/S2_Supplementary_tables_figures.docx"); print("ok")
