"""Fuel economy and CO2 of model-year 2012-2024 cars, SUVs and trucks - the used-car market - from EPA/DOE fueleconomy.gov.
Source file: https://www.fueleconomy.gov/feg/epadata/vehicles.csv.zip (all EPA-tested vehicles since 1984).
Run: python3 build_dataset.py  (raw download cached in $DATA_RAW, FORCE=1 to refresh)"""
import csv, os, sys, statistics, zipfile, collections
sys.path[:0] = [os.path.dirname(os.path.abspath(__file__)), '/root/carsite/freebies/data/_lib']  # common.py: next to this file or in _lib
from common import fetch, write, save_stats, pct, LICENSE_OURS, TODAY

OUT = os.path.dirname(os.path.abspath(__file__))
RETRIEVED = os.environ.get('RETRIEVED', '2026-11-28')
z = fetch('https://www.fueleconomy.gov/feg/epadata/vehicles.csv.zip', 'vehicles.csv.zip')
with zipfile.ZipFile(z) as zf:
    raw = list(csv.DictReader(zf.read('vehicles.csv').decode('utf-8', 'replace').splitlines()))

ATV = {'': 'Gasoline', 'Hybrid': 'Hybrid', 'Plug-in Hybrid': 'Plug-in hybrid', 'EV': 'Electric', 'Diesel': 'Diesel',
       'FFV': 'Flex-fuel (gasoline/E85)', 'FCV': 'Hydrogen fuel cell', 'CNG': 'CNG', 'Bifuel (CNG)': 'Bi-fuel CNG'}


def f(x):
    try:
        v = float(x)
        return int(v) if v == int(v) else round(v, 1)
    except (TypeError, ValueError):
        return None


rows = []
for x in raw:
    y = int(x['year'])
    if not 2012 <= y <= 2024:
        continue
    pt = ATV.get(x['atvType'], x['atvType'])
    rows.append({
        'epa_id': int(x['id']), 'year': y, 'make': x['make'], 'model': x['model'], 'base_model': x['baseModel'],
        'vehicle_class': x['VClass'], 'powertrain': pt, 'fuel_type': x['fuelType'], 'drive': x['drive'], 'transmission': x['trany'],
        'cylinders': f(x['cylinders']), 'displacement_l': f(x['displ']), 'turbo': 'Y' if x['tCharger'] in ('T', 'TRUE', 'True') else '',
        'mpg_city': f(x['city08']), 'mpg_highway': f(x['highway08']), 'mpg_combined': f(x['comb08']),
        'kwh_per_100mi': f(x['combE']) if pt in ('Electric', 'Plug-in hybrid') and f(x['combE']) else None,
        'electric_range_mi': (f(x['range']) if pt == 'Electric' else f(x['rangeA']) if pt == 'Plug-in hybrid' else None) or None,
        'co2_tailpipe_g_per_mi': round(float(x['co2TailpipeGpm'])) if f(x['co2TailpipeGpm']) is not None else None,
        'annual_fuel_cost_usd_epa': f(x['fuelCost08']), 'ghg_score_1_10': f(x['ghgScore']) if f(x['ghgScore']) and f(x['ghgScore']) > 0 else None,
    })
rows.sort(key=lambda r: (r['year'], r['make'], r['model'], r['epa_id']))
cols = list(rows[0].keys())
meta = {'title': 'Fuel economy and CO2 of model-year 2012-2024 vehicles (EPA fueleconomy.gov)', 'rows': len(rows),
        'source': 'U.S. EPA and U.S. DOE, fueleconomy.gov - vehicles.csv (https://www.fueleconomy.gov/feg/download.shtml)',
        'source_file_last_modified': '2026-11-20', 'retrieved': RETRIEVED, 'built': TODAY, 'license': LICENSE_OURS,
        'source_license': 'U.S. federal government work (EPA/DOE), public domain in the U.S.',
        'notes': 'One row per EPA-tested configuration (engine/transmission/drive), not per sales volume. mpg_combined for EVs/PHEVs is MPGe '
                 '(PHEV: gasoline-mode mpg in mpg_* columns; electric range in electric_range_mi). annual_fuel_cost_usd_epa uses EPA\'s current price and 15,000-mile assumptions.'}
write(OUT, 'used-car-fuel-economy-2012-2024', cols, rows, meta)

med = lambda xs: statistics.median(xs) if xs else None
gas = lambda y: [r['mpg_combined'] for r in rows if r['year'] == y and r['powertrain'] == 'Gasoline' and r['mpg_combined']]
co2 = lambda y: [r['co2_tailpipe_g_per_mi'] for r in rows if r['year'] == y and r['powertrain'] == 'Gasoline' and r['co2_tailpipe_g_per_mi']]
share = lambda y, pts: pct(sum(1 for r in rows if r['year'] == y and r['powertrain'] in pts), sum(1 for r in rows if r['year'] == y))
hyb = sorted([r for r in rows if r['powertrain'] == 'Hybrid'], key=lambda r: (-r['mpg_combined'], r['year']))
seen, besth = set(), []
for r in hyb:
    k = (r['make'], r['base_model'])
    if k not in seen:
        seen.add(k); besth.append(r)
pick = [r for r in rows if 'Pickup' in r['vehicle_class'] and r['powertrain'] == 'Gasoline']
pk = lambda y: med([r['mpg_combined'] for r in pick if r['year'] == y])
turbo = lambda y: pct(sum(1 for r in rows if r['year'] == y and r['powertrain'] == 'Gasoline' and r['turbo']),
                      sum(1 for r in rows if r['year'] == y and r['powertrain'] == 'Gasoline'))
facts = [
    f'{len(rows):,} EPA-tested configurations of model years 2012-2024 from {len(set(r["make"] for r in rows))} makes.',
    f'The median gasoline-only configuration went from {med(gas(2012))} mpg combined in 2012 to {med(gas(2024))} mpg in 2024; median tailpipe CO2 from {med(co2(2012))} to {med(co2(2024))} g/mile.',
    f'Hybrids, plug-in hybrids and EVs were {share(2012, ("Hybrid", "Plug-in hybrid", "Electric"))}% of tested configurations in 2012 and {share(2024, ("Hybrid", "Plug-in hybrid", "Electric"))}% in 2024.',
    f'Turbocharged engines: {turbo(2012)}% of gasoline-only configurations in 2012 vs {turbo(2024)}% in 2024.',
    'Highest-mpg hybrids (non-plug-in) of these years: ' + '; '.join(f'{r["year"]} {r["make"]} {r["model"]} {r["mpg_combined"]} mpg' for r in besth[:5]) + '.',
    f'Median gasoline pickup: {pk(2012)} mpg combined in 2012 vs {pk(2024)} mpg in 2024.',
]
POP = [('Toyota', 'Camry'), ('Honda', 'Civic'), ('Toyota', 'Corolla'), ('Honda', 'Accord'), ('Toyota', 'RAV4'), ('Honda', 'CR-V'),
       ('Toyota', 'Prius'), ('Ford', 'F150 Pickup 2WD'), ('Nissan', 'Altima'), ('Chevrolet', 'Malibu'), ('Mazda', '3'),
       ('Hyundai', 'Elantra'), ('Toyota', 'Tacoma 2WD'), ('Jeep', 'Wrangler 4WD'), ('Subaru', 'Outback'), ('Toyota', 'Highlander'), ('BMW', '3 Series')]
prev = []
for mk, bm in POP:
    for y in (2015, 2019, 2022):
        rs = [r for r in rows if r['make'] == mk and (r['base_model'] == bm or r['model'] == bm) and r['year'] == y and r['mpg_combined']]
        if rs:
            prev.append([y, mk, rs[0]['base_model'] or bm, len(rs), min(r['mpg_combined'] for r in rs), max(r['mpg_combined'] for r in rs)])
save_stats(OUT, {'base': 'used-car-fuel-economy-2012-2024', 'rows': len(rows), 'cols': cols, 'facts': facts,
                 'key': [['Configurations', f'{len(rows):,}'], ['Model years', '2012-2024'], ['Makes', str(len(set(r["make"] for r in rows)))],
                         ['Median gas mpg 2024', str(med(gas(2024)))]],
                 'preview_title': 'Preview: combined mpg range of common used models (all EPA configurations of that year, hybrids included)',
                 'preview': {'cols': ['year', 'make', 'base_model', 'configs', 'mpg_combined_min', 'mpg_combined_max'], 'rows': prev}})
