"""California vehicle sales & use tax rates by city and county (CDTFA, effective 2026-10-01).
Input: /root/carsite/tools/data/ca-rates.json (parsed from the CDTFA rate table by the site's tools build).
Run: python3 build_dataset.py"""
import json, os, sys, statistics, 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 write, save_stats, LICENSE_OURS, TODAY

OUT = os.path.dirname(os.path.abspath(__file__))
BASE = 'california-vehicle-sales-tax-rates-2026-10'
SRC = 'https://cdtfa.ca.gov/taxes-and-fees/sales-use-tax-rates.htm'
rs = json.load(open('/root/carsite/tools/data/ca-rates.json'))
rows = [{'location': r['location'], 'county': r['county'], 'type': r['type'], 'rate_percent': r['rate'],
         'effective_date': '2026-10-01', 'tax_on_10000_usd': round(r['rate'] * 100, 2)} for r in rs]
cols = ['location', 'county', 'type', 'rate_percent', 'effective_date', 'tax_on_10000_usd']
meta = {'title': 'California vehicle sales and use tax rates by city and county (effective October 1, 2026)',
        'source': 'California Department of Tax and Fee Administration (CDTFA), California City & County Sales & Use Tax Rates - ' + SRC,
        'source_effective_date': '2026-10-01', 'retrieved': '2026-11-28', 'built': TODAY, 'license': LICENSE_OURS,
        'source_license': 'California state government public information (CDTFA)', 'rows': len(rows)}
write(OUT, BASE, cols, rows, meta)

cities = [r for r in rows if r['type'] == 'City']
vals = [r['rate_percent'] for r in rows]
mx = max(vals); mn = min(vals)
top = sorted([r for r in rows if r['rate_percent'] == mx], key=lambda r: r['location'])
base_n = sum(1 for r in rows if r['rate_percent'] == mn)
oc = [r for r in rows if r['county'] == 'Orange']
oc_rates = collections.Counter(r['rate_percent'] for r in oc)
oc_hi = sorted([r for r in oc if r['rate_percent'] == max(oc_rates)], key=lambda r: r['location'])
la = [r['rate_percent'] for r in rows if r['county'] == 'Los Angeles']
gap = round((mx - mn) * 300, 2)  # on a $30,000 car
facts = [
    f'The dataset covers {len(rows)} places: {len(cities)} cities/towns and {len(rows) - len(cities)} other entries (unincorporated county areas).',
    f'Rates range from {mn}% (the statewide base, used in {base_n} places) to {mx}% ({", ".join(r["location"] for r in top[:6])}{" and others" if len(top) > 6 else ""}).',
    f'On a $30,000 used car the difference between the lowest and highest rate is ${gap:,.0f} in tax.',
    f'The median rate across all places is {statistics.median(vals)}%.',
    f'In Orange County {len(oc)} places are listed; {oc_rates.most_common(1)[0][1]} of them use {oc_rates.most_common(1)[0][0]}%, and the highest OC rate is {max(oc_rates)}% ({", ".join(r["location"] for r in oc_hi)}).',
    f'Los Angeles County places range from {min(la)}% to {max(la)}%.',
]
prev = sorted(oc, key=lambda r: (-r['rate_percent'], r['location']))
save_stats(OUT, {'base': BASE, 'rows': len(rows), 'cols': cols, 'facts': facts,
                 'key': [['Places', str(len(rows))], ['Lowest rate', f'{mn}%'], ['Highest rate', f'{mx}%'], ['Median', f'{statistics.median(vals)}%']],
                 'preview_title': 'Preview: Orange County rates (highest first)',
                 'preview': {'cols': ['location', 'type', 'rate_percent', 'tax_on_10000_usd'], 'rows': [[r['location'], r['type'], f"{r['rate_percent']}%", f"${r['tax_on_10000_usd']:,.2f}"] for r in prev]}})
