"""EV charging stations in California, summarized by city and by Orange County ZIP code.
Source: U.S. DOE Alternative Fuels Data Center (AFDC) Station Locator, via the NLR (formerly NREL) developer API.
Run: AFDC_KEY=DEMO_KEY python3 build_dataset.py   (raw download cached in $DATA_RAW, FORCE=1 to refresh)"""
import json, 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__))
KEY = os.environ.get('AFDC_KEY', 'DEMO_KEY')
URL = f'https://developer.nlr.gov/api/alt-fuel-stations/v1.json?api_key={KEY}&state=CA&fuel_type=ELEC&limit=all'
p = fetch(URL, 'afdc_ca_elec.json')
RETRIEVED = os.environ.get('RETRIEVED', '2026-11-28')
st = json.load(open(p))['fuel_stations']
zc = ca_zip_county()
CONN = [('J1772', 'j1772'), ('J1772COMBO', 'ccs1'), ('TESLA', 'nacs_tesla'), ('CHADEMO', 'chademo')]


def city_name(s):
    return ' '.join((s.get('city') or '').strip().split()).title()


def empty():
    return {'stations': 0, 'public_stations': 0, 'level1_ports': 0, 'level2_ports': 0, 'dc_fast_ports': 0,
            'stations_with_dc_fast': 0, **{f'stations_{k}': 0 for _, k in CONN}, 'networks': collections.Counter(),
            'opened_2025_or_later': 0}


def add(a, s):
    a['stations'] += 1
    a['public_stations'] += s['access_code'] == 'public'
    a['level1_ports'] += s.get('ev_level1_evse_num') or 0
    a['level2_ports'] += s.get('ev_level2_evse_num') or 0
    a['dc_fast_ports'] += s.get('ev_dc_fast_num') or 0
    a['stations_with_dc_fast'] += bool(s.get('ev_dc_fast_num'))
    ct = set(s.get('ev_connector_types') or [])
    for c, k in CONN:
        a[f'stations_{k}'] += c in ct
    a['networks'][s.get('ev_network') or 'Unknown'] += 1
    a['opened_2025_or_later'] += bool(s.get('open_date') and s['open_date'] >= '2025-01-01')


live = [s for s in st if s['status_code'] == 'E']  # E = available (P planned, T temporarily unavailable excluded)
by_city, by_zip = {}, {}
for s in live:
    z = (s.get('zip') or '')[:5]
    county = zc.get(z, '')
    key = (city_name(s), county)
    add(by_city.setdefault(key, empty()), s)
    if county == 'Orange':
        add(by_zip.setdefault((z, city_name(s)), empty()), s)


def fin(a):
    a['total_ports'] = a['level1_ports'] + a['level2_ports'] + a['dc_fast_ports']
    a['top_network'] = a['networks'].most_common(1)[0][0]
    del a['networks']
    return a


cols_tail = ['stations', 'public_stations', 'total_ports', 'level1_ports', 'level2_ports', 'dc_fast_ports', 'stations_with_dc_fast',
             'stations_j1772', 'stations_ccs1', 'stations_nacs_tesla', 'stations_chademo', 'opened_2025_or_later', 'top_network']
rows = [{'city': c, 'county': co, **fin(a)} for (c, co), a in by_city.items()]
rows.sort(key=lambda r: (-r['total_ports'], r['city']))
meta_common = {'source': 'U.S. Department of Energy, Alternative Fuels Data Center (AFDC) Station Locator - https://afdc.energy.gov/stations/ '
                         '(API: developer.nlr.gov alt-fuel-stations v1, state=CA, fuel_type=ELEC)',
               'retrieved': RETRIEVED, 'built': TODAY, 'license': LICENSE_OURS,
               'source_license': 'U.S. federal government data (DOE/AFDC), public; cite the AFDC Station Locator',
               'notes': 'Only stations with status "available" (E). County from ZIP via U.S. Census 2020 ZCTA-county relationship file (largest land share). '
                        'Connector columns count STATIONS offering that connector, not ports.'}
write(OUT, 'california-ev-charging-by-city-2026-11', ['city', 'county'] + cols_tail, rows,
      {'title': 'California EV charging stations by city (AFDC, November 2026)', 'rows': len(rows), **meta_common})
zrows = [{'zip': z, 'city': c, **fin(a)} for (z, c), a in by_zip.items()]
zrows.sort(key=lambda r: (r['zip'], r['city']))
write(OUT, 'orange-county-ev-charging-by-zip-2026-11', ['zip', 'city'] + cols_tail, zrows,
      {'title': 'Orange County, CA EV charging stations by ZIP code (AFDC, November 2026)', 'rows': len(zrows), **meta_common})

# ---- facts
T = lambda k, rs: sum(r[k] for r in rs)
oc = [r for r in rows if r['county'] == 'Orange']
L2, DC, ALL = T('level2_ports', rows), T('dc_fast_ports', rows), T('total_ports', rows)
ocdc = sorted(oc, key=lambda r: -r['dc_fast_ports'])
irv = next((r for r in rows if r['city'] == 'Irvine' and r['county'] == 'Orange'), None)
cnt_tot = collections.Counter(s['status_code'] for s in st)
dcst = [s for s in live if s.get('ev_dc_fast_num')]
dc_nacs = sum('TESLA' in (s.get('ev_connector_types') or []) for s in dcst)
dc_ccs = sum('J1772COMBO' in (s.get('ev_connector_types') or []) for s in dcst)
new = sum(r['opened_2025_or_later'] for r in rows)
facts = [
    f'AFDC lists {len(live):,} available public and private EV charging stations in California with {ALL:,} charging ports '
    f'({L2:,} Level 2, {DC:,} DC fast, {T("level1_ports", rows):,} Level 1); {cnt_tot.get("P", 0)} more are planned and {cnt_tot.get("T", 0)} temporarily unavailable.',
    f'Level 2 is {pct(L2, ALL)}% of all ports; DC fast is {pct(DC, ALL)}%.',
    f'Of {len(dcst):,} California stations with DC fast charging, {dc_ccs:,} ({pct(dc_ccs, len(dcst))}%) offer CCS1 and {dc_nacs:,} ({pct(dc_nacs, len(dcst))}%) offer the Tesla/NACS plug.',
    f'Orange County has {T("stations", oc):,} stations and {T("total_ports", oc):,} ports ({T("dc_fast_ports", oc):,} DC fast) - {pct(T("total_ports", oc), ALL)}% of the state\'s ports.',
]
if irv:
    rank = [r['city'] for r in rows].index('Irvine') + 1
    facts.append(f'Irvine alone has {irv["stations"]:,} stations and {irv["total_ports"]:,} ports ({irv["dc_fast_ports"]} DC fast), ranking #{rank} among California cities by total ports.')
facts.append(f'{new:,} of the available stations ({pct(new, len(live))}%) list an open date in 2025 or later.')
facts.append('OC cities with the most DC fast ports: ' + ', '.join(f'{r["city"]} ({r["dc_fast_ports"]})' for r in ocdc[:5]) + '.')
save_stats(OUT, {'base': 'california-ev-charging-by-city-2026-11', 'extra_base': 'orange-county-ev-charging-by-zip-2026-11',
                 'rows': len(rows), 'rows_extra': len(zrows), 'cols': ['city', 'county'] + cols_tail, 'cols_extra': ['zip', 'city'] + cols_tail,
                 'facts': facts,
                 'key': [['Stations (CA)', f'{len(live):,}'], ['Charging ports', f'{ALL:,}'], ['DC fast ports', f'{DC:,}'], ['OC ports', f'{T("total_ports", oc):,}']],
                 'preview_title': 'Preview: Orange County cities by charging ports',
                 'preview': {'cols': ['city', 'stations', 'level2_ports', 'dc_fast_ports', 'stations_ccs1', 'stations_nacs_tesla', 'top_network'],
                             'rows': [[r['city'], r['stations'], r['level2_ports'], r['dc_fast_ports'], r['stations_ccs1'], r['stations_nacs_tesla'], r['top_network']] for r in oc]}})
