import sys
sys.stdout.reconfigure(encoding='utf-8')
import pandas as pd
import numpy as np
import os

base_dir = r'c:\Users\NASPC\Documents\Du án tại SG tháng 8\Project_Code_and_Results\4_Logistic_Regression'

file_donation = os.path.join(base_dir, 'Logistic_Results_Donation_Firth.csv')
file_decision = os.path.join(base_dir, 'Logistic_Results_Decision_Final.csv')

def process_results(filepath, model_name="M₁"):
    df = pd.read_csv(filepath, index_col=0)
    
    # Check if we have S.E. or std err
    se_col = 'S.E.' if 'S.E.' in df.columns else ('std err' if 'std err' in df.columns else None)
    if not se_col:
        # For some files it might be 'SE'
        if 'SE' in df.columns: se_col = 'SE'
    
    # Recreate necessary metrics for JASP format
    estimate = df['Beta (B)']
    se = df[se_col] if se_col else 0
    odds_ratio = df['Odds Ratio EXP(B)']
    p_val = df['P-value']
    
    # Calculate Z and Wald
    z_stat = estimate / se
    wald = z_stat ** 2
    lower = np.exp(estimate - 1.96 * se)
    upper = np.exp(estimate + 1.96 * se)
    
    # Rename index to match JASP
    # JASP formats: e.g. "Gender_2" -> "Gender (2)", "const" -> "(Intercept)"
    def map_name(name):
        if name == 'const': return '(Intercept)'
        if '_' in name:
            parts = name.split('_')
            return f"{parts[0]} ({parts[1]})"
        return name
    
    new_index = [map_name(str(i)) for i in df.index]
    
    # Build the target dataframe
    out_df = pd.DataFrame({
        'Model': [model_name] + [np.nan] * (len(df) - 1),
        '': new_index,
        'Estimate': estimate.values,
        'Standard Error': se.values if se_col else [np.nan]*len(df),
        'Odds Ratio': odds_ratio.values,
        'z': z_stat.values,
        'Wald Statistic': wald.values,
        'df': [1] * len(df),
        'p': p_val.values,
        'Lower bound': lower.values,
        'Upper bound': upper.values
    })
    
    # Format p-values < .00001
    out_df['p'] = out_df['p'].apply(lambda x: '< .00001' if pd.notnull(x) and x < 0.00001 else (round(x, 5) if pd.notnull(x) else x))
    out_df = out_df.round(5)
    return out_df

out_path = r'c:\Users\NASPC\Documents\Du án tại SG tháng 8\Project_Code_and_Results\4_Logistic_Regression\KẾT_QUẢ_FINAL_JASP_LAYOUT.xlsx'

with pd.ExcelWriter(out_path, engine='openpyxl') as writer:
    if os.path.exists(file_donation):
        df_don = process_results(file_donation, "M₁")
        df_don.to_excel(writer, sheet_name='Donation_New', index=False)
    
    if os.path.exists(file_decision):
        df_dec = process_results(file_decision, "M₁")
        df_dec.to_excel(writer, sheet_name='Decision_New', index=False)

print(f"Exported successfully to {out_path}")
