#!/usr/bin/env python3
"""03_reporting_checks.py
Post-estimation checks: pretrend, placebo placeholders, removal-symmetry tables and decision labels.
"""
import argparse
import pandas as pd
import numpy as np


def decision_label(att, ci_low, ci_high, pretrend_ok=True, robust=True, direction='positive'):
    if not pretrend_ok or not robust:
        return 'unidentified'
    if direction == 'positive':
        if ci_low > 0:
            return 'field-positive'
        if ci_high < 0:
            return 'field-negative'
    else:
        if ci_high < 0:
            return 'field-positive'
        if ci_low > 0:
            return 'field-negative'
    return 'field-neutral'


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--dynamic_att', required=True)
    ap.add_argument('--output', default='decision_summary.csv')
    args = ap.parse_args()
    d = pd.read_csv(args.dynamic_att)
    pre = d[(d.event_time >= -6) & (d.event_time <= -2)].copy()
    post = d[(d.event_time >= 1) & (d.event_time <= 3)].copy()
    pretrend_ok = bool(((pre.ci_low <= 0) & (pre.ci_high >= 0)).all()) if len(pre) else False
    att = post.att.mean() if len(post) else np.nan
    se = np.sqrt(np.nanmean(post.se ** 2)) if len(post) else np.nan
    ci_low, ci_high = att - 1.96*se, att + 1.96*se
    out = pd.DataFrame([{
        'window': '+1_to_+3',
        'mean_att': att,
        'ci_low_approx': ci_low,
        'ci_high_approx': ci_high,
        'pretrend_ok': pretrend_ok,
        'decision': decision_label(att, ci_low, ci_high, pretrend_ok=pretrend_ok)
    }])
    out.to_csv(args.output, index=False)
    print(out.to_string(index=False))

if __name__ == '__main__':
    main()
