"""
Analysis Script 01: Descriptive Statistics Table

Creates a 4-column descriptive table:
- All observations
- Treated x Post
- Treated x Pre
- Untreated (Control)

Output: analysis/output/tables/descriptive_table.tex
"""

import pandas as pd
from pathlib import Path

# Set project root
ROOT = Path(__file__).parent.parent.parent

# Define paths
input_file = ROOT / "build/output/analysis_panel.csv"
output_file = ROOT / "analysis/output/tables/descriptive_table.tex"

# Read analysis panel
panel = pd.read_csv(input_file)

# Create group column
panel['group'] = 'Untreated'
panel.loc[panel['adoption_year'].notna() & (panel['post_treated'] == 1),
          'group'] = 'Treated x Post'
panel.loc[panel['adoption_year'].notna() & (panel['post_treated'] == 0),
          'group'] = 'Treated x Pre'

# Variables for the table
vars = ['fatal_crashes', 'serious_crashes', 'total_crashes',
        'fatal_share', 'population', 'median_income', 'pct_urban']

# Compute means and SDs by group
stats = (panel.groupby('group')[vars]
         .agg(['mean', 'std'])
         .round(2))

# Export to LaTeX
output_file.parent.mkdir(parents=True, exist_ok=True)
stats.T.to_latex(output_file,
                 caption="Descriptive Statistics",
                 label="tab:desc")

print(f"Saved descriptive_table.tex")
