"""Shared helpers for Irvine Used Cars open datasets (/root/carsite/freebies/data/<slug>/build_dataset.py)."""
import csv, json, os, subprocess, datetime

RAW = os.environ.get('DATA_RAW', '/root/carsite/freebies/data/_raw')
SITE = 'https://www.irvineautosales.com'
PUBLISHER = 'Irvine Used Cars'
LICENSE_OURS = 'CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/) - credit "Irvine Used Cars, irvineautosales.com"'
TODAY = datetime.date.today().isoformat()


def fetch(url, name, raw=RAW):
    """Download url into raw/name once (re-run with FORCE=1 to refresh)."""
    os.makedirs(raw, exist_ok=True)
    p = os.path.join(raw, name)
    if os.environ.get('FORCE') or not os.path.exists(p) or os.path.getsize(p) < 2000:
        subprocess.run(['curl', '-sSL', '--fail', '--max-time', '1800', '-o', p, url], check=True)
    return p


def ca_zip_county(raw=RAW):
    """ZIP (ZCTA 2020) -> California county name, by the largest land-area share (U.S. Census Bureau relationship file)."""
    p = fetch('https://www2.census.gov/geo/docs/maps-data/data/rel2020/zcta520/tab20_zcta520_county20_natl.txt',
              'zcta_county.txt', raw)
    best = {}
    with open(p, encoding='utf-8-sig') as f:
        for r in csv.DictReader(f, delimiter='|'):
            z, c = r['GEOID_ZCTA5_20'], r['GEOID_COUNTY_20']
            if not z or not c.startswith('06'):
                continue
            a = int(r['AREALAND_PART'] or 0)
            if z not in best or a > best[z][0]:
                best[z] = (a, r['NAMELSAD_COUNTY_20'].replace(' County', ''))
    return {z: v[1] for z, v in best.items()}


def write(outdir, base, cols, rows, meta):
    """Writes <base>.csv and <base>.json ({"metadata":..., "data":[...]}) into outdir."""
    os.makedirs(outdir, exist_ok=True)
    with open(os.path.join(outdir, base + '.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(cols)
        for r in rows:
            w.writerow([r.get(c, '') for c in cols])
    json.dump({'metadata': meta, 'data': [{c: r.get(c) for c in cols} for r in rows]},
              open(os.path.join(outdir, base + '.json'), 'w'), ensure_ascii=False, indent=0)


def save_stats(outdir, stats):
    json.dump(stats, open(os.path.join(outdir, 'stats.json'), 'w'), ensure_ascii=False, indent=1)
    for f in stats.get('facts', []):
        print('-', f)


def pct(a, b, nd=1):
    return round(100.0 * a / b, nd) if b else 0.0
