"""
Build Script 01: Collapse Crash Data

Reads individual crash-level data, filters out minor crashes,
and collapses to state-year level.
"""

import pandas as pd
from pathlib import Path

ROOT = Path(__file__).parent.parent.parent

input_file = ROOT / "build/input/crash_data.csv"
output_file = ROOT / "build/output/crashes_state_year.csv"

# Read crash data
crashes = pd.read_csv(input_file)

# Filter: keep only fatal and serious crashes
crashes = crashes[crashes['severity'] != 'minor']

# Collapse to state-year-severity level (long format)
crashes_long = (crashes.groupby(['state_fips', 'year', 'severity'])
                .size().reset_index(name='n_crashes'))

# Reshape (pivot) from long to wide: one column per severity type
crashes_sy = crashes_long.pivot_table(
    index=['state_fips', 'year'], columns='severity',
    values='n_crashes', fill_value=0
).reset_index()
crashes_sy.columns.name = None
crashes_sy = crashes_sy.rename(columns={'fatal': 'fatal_crashes',
                                         'serious': 'serious_crashes'})

# Compute total and fatal share
crashes_sy['total_crashes'] = crashes_sy['fatal_crashes'] + crashes_sy['serious_crashes']
crashes_sy['fatal_share'] = crashes_sy['fatal_crashes'] / crashes_sy['total_crashes']

# Save intermediate file
output_file.parent.mkdir(parents=True, exist_ok=True)
crashes_sy.to_csv(output_file, index=False)
print(f"Saved crashes_state_year.csv: {len(crashes_sy)} rows")
