"""NHTSA safety recalls and owner complaints per make / model / model year (2012-2024 light-vehicle brands).
Sources (NHTSA ODI flat files, updated daily): https://static.nhtsa.gov/odi/ffdd/rcl/FLAT_RCL_POST_2010.zip
and https://static.nhtsa.gov/odi/ffdd/cmpl/FLAT_CMPL.zip (layouts: RCL.txt, CMPL.txt in the same folders).
Only counts are published - no complaint text, VINs, names or locations.  Run: python3 build_dataset.py"""
import os, sys, subprocess, 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')
MAKES = {'ACURA', 'ALFA ROMEO', 'AUDI', 'BMW', 'BUICK', 'CADILLAC', 'CHEVROLET', 'CHRYSLER', 'DODGE', 'FIAT', 'FORD', 'GENESIS', 'GMC',
         'HONDA', 'HYUNDAI', 'INFINITI', 'JAGUAR', 'JEEP', 'KIA', 'LAND ROVER', 'LEXUS', 'LINCOLN', 'LUCID', 'MASERATI', 'MAZDA',
         'MERCEDES-BENZ', 'MINI', 'MITSUBISHI', 'NISSAN', 'POLESTAR', 'PORSCHE', 'RAM', 'RIVIAN', 'SCION', 'SMART', 'SUBARU', 'TESLA',
         'TOYOTA', 'VOLKSWAGEN', 'VOLVO'}
Y0, Y1 = 2012, 2024


def lines(zpath):
    p = subprocess.Popen(['unzip', '-p', zpath], stdout=subprocess.PIPE)
    for b in p.stdout:
        yield b.decode('latin-1').rstrip('\r\n').split('\t')
    p.wait()


def key(make, model, year):
    make, model = make.strip().upper(), ' '.join(model.strip().upper().split())
    try:
        y = int(year)
    except ValueError:
        return None
    if make not in MAKES or not (Y0 <= y <= Y1) or not model:
        return None
    return (make, model, y)


def top(c):
    return c.most_common(1)[0][0] if c else ''


agg = collections.defaultdict(lambda: {'camps': set(), 'dnd': set(), 'park': set(), 'rcomp': collections.Counter(),
                                       'odi': set(), 'crash': 0, 'fire': 0, 'inj': 0, 'death': 0, 'ccomp': collections.Counter()})
camp_comp = collections.Counter()
# --- recalls (one row per campaign x make/model/year x component)
rz = fetch('https://static.nhtsa.gov/odi/ffdd/rcl/FLAT_RCL_POST_2010.zip', 'rcl.zip')
seen_cc = set()
for f in lines(rz):
    if len(f) < 17 or f[10].strip() != 'V':
        continue
    k = key(f[2], f[3], f[4])
    if not k:
        continue
    a, camp = agg[k], f[1].strip()
    comp = f[6].split(':')[0].strip()
    if (camp, k, comp) not in seen_cc:
        seen_cc.add((camp, k, comp)); a['rcomp'][comp] += 1
    a['camps'].add(camp)
    if len(f) > 27 and f[27].strip().upper() in ('Y', 'YES'):
        a['dnd'].add(camp)
    if len(f) > 28 and f[28].strip().upper() in ('Y', 'YES'):
        a['park'].add(camp)
    if (camp, comp) not in seen_cc:
        seen_cc.add((camp, comp)); camp_comp[comp] += 1
del seen_cc
# --- complaints (one row per complaint x product x component)
cz = fetch('https://static.nhtsa.gov/odi/ffdd/cmpl/FLAT_CMPL.zip', 'cmpl.zip')
seen = set()
for f in lines(cz):
    if len(f) < 46 or f[45].strip() not in ('V', ''):
        continue
    k = key(f[3], f[4], f[5])
    if not k:
        continue
    a, odi = agg[k], f[1].strip()
    a['ccomp'][f[11].split(':')[0].strip()] += 1
    if odi in a['odi']:
        continue
    a['odi'].add(odi)
    a['crash'] += f[6] == 'Y'; a['fire'] += f[8] == 'Y'
    a['inj'] += int(f[9] or 0) if f[9].strip().isdigit() else 0
    a['death'] += int(f[10] or 0) if f[10].strip().isdigit() else 0

rows = []
for (mk, md, y), a in agg.items():
    rows.append({'make': mk, 'model': md, 'model_year': y, 'recall_campaigns': len(a['camps']), 'do_not_drive_campaigns': len(a['dnd']),
                 'park_outside_campaigns': len(a['park']), 'top_recall_component': top(a['rcomp']), 'complaints': len(a['odi']),
                 'complaints_with_crash': a['crash'], 'complaints_with_fire': a['fire'], 'injuries_reported': a['inj'], 'deaths_reported': a['death'],
                 'top_complaint_component': top(a['ccomp'])})
rows.sort(key=lambda r: (r['make'], r['model'], r['model_year']))
cols = list(rows[0].keys())
meta = {'title': 'NHTSA recalls and complaints by make, model and model year (2012-2024)', 'rows': len(rows),
        'source': 'U.S. DOT National Highway Traffic Safety Administration (NHTSA), Office of Defects Investigation flat files: '
                  'FLAT_RCL_POST_2010 (recalls) and FLAT_CMPL (complaints) - https://www.nhtsa.gov/nhtsa-datasets-and-apis',
        'retrieved': RETRIEVED, 'built': TODAY, 'license': LICENSE_OURS,
        'source_license': 'U.S. federal government work (NHTSA), public domain in the U.S.',
        'notes': 'Counts are NOT adjusted for how many vehicles were sold - popular models get more complaints. Complaints are unverified owner reports. '
                 'A recall campaign is counted once per make/model/year it covers. Model names as NHTSA spells them (e.g. F-150, CR-V). '
                 f'Brands: {", ".join(sorted(MAKES))}.'}
write(OUT, 'nhtsa-recalls-complaints-by-model-2012-2024', cols, rows, meta)

S = lambda k, rs=rows: sum(r[k] for r in rs)
allc = set()
for a in agg.values():
    allc |= a['camps']
dnd_all = set().union(*[a['dnd'] for a in agg.values()])
byyear = collections.Counter()
for (mk, md, y), a in agg.items():
    byyear[y] += len(a['odi'])
comp_c = collections.Counter()
for a in agg.values():
    comp_c.update(a['ccomp'])
mostc = sorted(rows, key=lambda r: -r['complaints'])[:5]
zero = sum(1 for r in rows if r['recall_campaigns'] == 0)
facts = [
    f'{len(rows):,} make/model/model-year combinations from {len(MAKES)} brands, model years {Y0}-{Y1}.',
    f'They are covered by {len(allc):,} distinct NHTSA recall campaigns; {len(dnd_all)} of those carry a "Do Not Drive" advisory.',
    f'{S("complaints"):,} owner complaints were filed with NHTSA for these vehicles; {pct(S("complaints_with_crash"), S("complaints"))}% mention a crash and {pct(S("complaints_with_fire"), S("complaints"))}% a fire.',
    'Most-mentioned components in complaints (all models): ' + ', '.join(f'{c.title()} ({pct(n, sum(comp_c.values()))}%)' for c, n in comp_c.most_common(4)) + '.',
    'Most complaints for a single model year (not adjusted for sales): ' + '; '.join(f'{r["model_year"]} {r["make"].title()} {r["model"].title()} ({r["complaints"]:,})' for r in mostc) + '.',
    f'{zero:,} combinations ({pct(zero, len(rows))}%) have no recall campaign on record.',
]
POP = [('TOYOTA', 'CAMRY'), ('HONDA', 'CIVIC'), ('TOYOTA', 'COROLLA'), ('HONDA', 'ACCORD'), ('TOYOTA', 'RAV4'), ('HONDA', 'CR-V'), ('FORD', 'F-150'),
       ('TESLA', 'MODEL 3'), ('TESLA', 'MODEL Y'), ('NISSAN', 'ALTIMA'), ('CHEVROLET', 'MALIBU'), ('HYUNDAI', 'ELANTRA'), ('JEEP', 'GRAND CHEROKEE'),
       ('SUBARU', 'OUTBACK'), ('KIA', 'OPTIMA'), ('MAZDA', 'CX-5'), ('CHEVROLET', 'EQUINOX'), ('JEEP', 'WRANGLER')]
idx = {(r['make'], r['model'], r['model_year']): r for r in rows}
prev = []
for mk, md in POP:
    for y in (2016, 2019):
        r = idx.get((mk, md, y))
        if r:
            prev.append([y, mk.title(), md, r['recall_campaigns'], r['complaints'], r['top_complaint_component'].title()])
save_stats(OUT, {'base': 'nhtsa-recalls-complaints-by-model-2012-2024', 'rows': len(rows), 'cols': cols, 'facts': facts,
                 'key': [['Model/year rows', f'{len(rows):,}'], ['Recall campaigns', f'{len(allc):,}'], ['Complaints', f'{S("complaints"):,}'],
                         ['Do Not Drive recalls', str(len(dnd_all))]],
                 'preview_title': 'Preview: common used models (model years 2016 and 2019)',
                 'preview': {'cols': ['model_year', 'make', 'model', 'recall_campaigns', 'complaints', 'top_complaint_component'], 'rows': prev}})
