"""California light-duty vehicles by fuel type and ZIP code (DMV registrations as of 12/31/2025), with change since 1/1/2021.
Source: California DMV "Vehicle Fuel Type Count by Zip Code" on data.ca.gov
https://data.ca.gov/dataset/vehicle-fuel-type-count-by-zip-code  Run: python3 build_dataset.py"""
import csv, os, sys, 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, ca_zip_county, pct, LICENSE_OURS, TODAY

OUT = os.path.dirname(os.path.abspath(__file__))
RETRIEVED = os.environ.get('RETRIEVED', '2026-11-28')
U = 'https://data.ca.gov/dataset/15179472-adeb-4df6-920a-20640d02b08c/resource/'
NEW = fetch(U + 'b459d957-5d94-4b10-999d-770419870364/download/vehicle-fuel-type-counts-2025-v3.csv', 'dmv_fuel_2026.csv')
OLD = fetch(U + '888bbb6c-09b4-469c-82e6-1b2a47439736/download/vehicle-fuel-type-count-by-zip-code-2021.csv', 'dmv_fuel_2021.csv')
FUEL = {'Gasoline': 'gasoline', 'Hybrid Gasoline': 'hybrid', 'Plug-in Hybrid': 'plug_in_hybrid', 'Battery Electric': 'battery_electric',
        'Diesel and Diesel Hybrid': 'diesel', 'Flex-Fuel': 'flex_fuel', 'Hydrogen Fuel Cell': 'hydrogen', 'plug-in hydrogen': 'hydrogen',
        'Natural Gas': 'natural_gas', 'Other': 'other'}
zc = ca_zip_county()


def load(p):
    z = collections.defaultdict(collections.Counter)
    with open(p, encoding='utf-8-sig') as f:
        for r in csv.DictReader(f):
            if r['Duty'] != 'Light':
                continue
            zp = (r.get('ZIP Code') or r.get('Zip Code') or '').strip()
            if len(zp) != 5 or not zp.isdigit():
                continue
            n = int(float(r['Vehicles']))
            z[zp][FUEL.get(r['Fuel'], 'other')] += n
            z[zp]['total'] += n
            if r['Model Year'] in ('<2012', '2012', '2013', '2014', '2015'):
                z[zp]['my_2015_or_older'] += n
            make = r['Make'].strip().upper()
            if r['Fuel'] == 'Battery Electric' and make == 'TESLA':
                z[zp]['bev_tesla'] += n
    return z


new, old = load(NEW), load(OLD)
F = ['gasoline', 'hybrid', 'plug_in_hybrid', 'battery_electric', 'diesel', 'flex_fuel', 'hydrogen', 'natural_gas', 'other']
rows = []
for zp, c in new.items():
    if zp not in zc or c['total'] < 1:
        continue  # keep California ZCTAs only (drops PO-box-only and out-of-state ZIPs)
    o = old.get(zp, collections.Counter())
    zev = c['battery_electric'] + c['plug_in_hybrid'] + c['hydrogen']
    r = {'zip': zp, 'county': zc[zp], 'light_duty_vehicles': c['total'], **{k: c[k] for k in F},
         'zev_share_pct': pct(zev, c['total']), 'battery_electric_share_pct': pct(c['battery_electric'], c['total']),
         'hybrid_share_pct': pct(c['hybrid'], c['total']), 'tesla_share_of_bev_pct': pct(c['bev_tesla'], c['battery_electric']),
         'model_year_2015_or_older_pct': pct(c['my_2015_or_older'], c['total']),
         'light_duty_vehicles_2021': o['total'] or None, 'battery_electric_2021': o['battery_electric'] if o else None,
         'battery_electric_change_since_2021': (c['battery_electric'] - o['battery_electric']) if o else None}
    rows.append(r)
rows.sort(key=lambda r: r['zip'])
cols = list(rows[0].keys())
meta = {'title': 'California light-duty vehicles by fuel type and ZIP code (DMV, as of December 31, 2025)', 'rows': len(rows),
        'source': 'California Department of Motor Vehicles, "Vehicle Fuel Type Count by Zip Code" (data.ca.gov). '
                  'Resource "1/1/2026" (rows dated 12/31/2025) and resource "1/1/2021" for the 2021 comparison columns.',
        'source_as_of': '2025-12-31', 'comparison_as_of': '2021-01-01', 'retrieved': RETRIEVED, 'built': TODAY, 'license': LICENSE_OURS,
        'source_license': 'California open data published by the DMV on data.ca.gov (no specific license stated on the dataset page; '
                          'State of California open data terms apply)',
        'notes': 'Light-duty vehicles only. ZEV = battery electric + plug-in hybrid + hydrogen fuel cell (DMV fuel categories). '
                 'County assigned from ZIP via U.S. Census 2020 ZCTA-county file (largest land share). DMV groups model years before 2012 as "<2012".'}
write(OUT, 'california-vehicles-by-fuel-type-zip-2025-12', cols, rows, meta)

# county summary
cs = collections.defaultdict(collections.Counter)
for r in rows:
    for k in F + ['light_duty_vehicles']:
        cs[r['county']][k] += r[k]
    cs[r['county']]['bev21'] += r['battery_electric_2021'] or 0
    cs[r['county']]['tot21'] += r['light_duty_vehicles_2021'] or 0
crow = []
for co, c in cs.items():
    zev = c['battery_electric'] + c['plug_in_hybrid'] + c['hydrogen']
    crow.append({'county': co, 'light_duty_vehicles': c['light_duty_vehicles'], **{k: c[k] for k in F},
                 'zev_share_pct': pct(zev, c['light_duty_vehicles']), 'battery_electric_share_pct': pct(c['battery_electric'], c['light_duty_vehicles']),
                 'battery_electric_2021': c['bev21'], 'battery_electric_growth_pct_since_2021': pct(c['battery_electric'] - c['bev21'], c['bev21'])})
crow.sort(key=lambda r: -r['zev_share_pct'])
ccols = list(crow[0].keys())
write(OUT, 'california-vehicles-by-fuel-type-county-2025-12', ccols, crow, {**meta, 'title': meta['title'].replace('ZIP code', 'county'), 'rows': len(crow)})

tot = sum(r['light_duty_vehicles'] for r in rows)
bev = sum(r['battery_electric'] for r in rows); phev = sum(r['plug_in_hybrid'] for r in rows); hyb = sum(r['hybrid'] for r in rows)
bev21 = sum(r['battery_electric_2021'] or 0 for r in rows)
oc = [r for r in rows if r['county'] == 'Orange']
occ = next(r for r in crow if r['county'] == 'Orange')
octop = sorted([r for r in oc if r['light_duty_vehicles'] >= 5000], key=lambda r: -r['battery_electric_share_pct'])
irv = [r for r in oc if r['zip'] in ('92602', '92603', '92604', '92606', '92612', '92614', '92617', '92618', '92620')]
irv_t = sum(r['light_duty_vehicles'] for r in irv); irv_b = sum(r['battery_electric'] for r in irv)
rank = [r['county'] for r in crow].index('Orange') + 1
old_n = sum(r['model_year_2015_or_older_pct'] * r['light_duty_vehicles'] / 100 for r in rows)
facts = [
    f'California had {tot:,} light-duty vehicles registered in {len(rows):,} ZIP codes as of December 31, 2025; {bev:,} ({pct(bev, tot)}%) are battery electric, '
    f'{phev:,} ({pct(phev, tot)}%) plug-in hybrids and {hyb:,} ({pct(hyb, tot)}%) conventional hybrids.',
    f'Battery-electric registrations grew from {bev21:,} (Jan 1, 2021) to {bev:,} - about {round(bev / bev21, 1)}x in five years (same ZIP codes).',
    f'Orange County: {occ["light_duty_vehicles"]:,} light-duty vehicles, {occ["battery_electric_share_pct"]}% battery electric and {occ["zev_share_pct"]}% ZEV overall - #{rank} of {len(crow)} counties by ZEV share.',
    f'Irvine ZIP codes (92602, 92603, 92604, 92606, 92612, 92614, 92617, 92618, 92620): {irv_b:,} battery EVs out of {irv_t:,} light-duty vehicles ({pct(irv_b, irv_t)}%).',
    'OC ZIP codes with the highest battery-EV share (5,000+ vehicles): ' + ', '.join(f'{r["zip"]} ({r["battery_electric_share_pct"]}%)' for r in octop[:5]) + '.',
    f'{pct(old_n, tot)}% of California light-duty vehicles are model year 2015 or older.',
]
prev = sorted(oc, key=lambda r: -r['battery_electric_share_pct'])
save_stats(OUT, {'base': 'california-vehicles-by-fuel-type-zip-2025-12', 'extra_base': 'california-vehicles-by-fuel-type-county-2025-12',
                 'rows': len(rows), 'rows_extra': len(crow), 'cols': cols, 'cols_extra': ccols, 'facts': facts,
                 'key': [['CA light-duty vehicles', f'{tot:,}'], ['Battery EVs', f'{bev:,}'], ['OC BEV share', f'{occ["battery_electric_share_pct"]}%'], ['ZIP codes', f'{len(rows):,}']],
                 'preview_title': 'Preview: Orange County ZIP codes by battery-EV share',
                 'preview': {'cols': ['zip', 'light_duty_vehicles', 'battery_electric', 'plug_in_hybrid', 'hybrid', 'battery_electric_share_pct', 'battery_electric_change_since_2021'],
                             'rows': [[r['zip'], f"{r['light_duty_vehicles']:,}", f"{r['battery_electric']:,}", f"{r['plug_in_hybrid']:,}", f"{r['hybrid']:,}", f"{r['battery_electric_share_pct']}%",
                                       '' if r['battery_electric_change_since_2021'] is None else f"{r['battery_electric_change_since_2021']:+,}"] for r in prev]}})
