#!/usr/bin/env python3
"""Rebuild the published register and derived findings from its checked input CSV.

Python 3.10+, standard library only. Run this file from any working directory.
The script is an arithmetic reproducer, not a scraper or independent verifier.
Empty inputs stay empty; excluded leads and the carrier benchmark are not facilities.
"""
from __future__ import annotations
import csv
import json
from collections import Counter
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from pathlib import Path

ROOT = Path(__file__).resolve().parent
VERIFIED = '2026-09-14'
VERSION = '1.1'
FT_IN_METRES = Decimal('0.3048')
SQFT_PER_ACRE = Decimal('43560')

def number(value: str, name: str) -> Decimal | None:
    if value == '':
        return None
    try:
        result = Decimal(value)
    except InvalidOperation as exc:
        raise ValueError(f'Invalid {name}: {value!r}') from exc
    if not result.is_finite() or result <= 0:
        raise ValueError(f'{name} must be positive, not {value!r}')
    return result

def rounded(value: Decimal | None, places: int) -> str:
    if value is None:
        return ''
    return str(value.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP))

def main() -> None:
    path = ROOT / 'cross-dock-facility-inputs.csv'
    with path.open(encoding='utf-8', newline='') as f:
        inputs = list(csv.DictReader(f))
    if len({row['record_id'] for row in inputs}) != len(inputs):
        raise ValueError('Duplicate record identifiers')
    outputs: list[dict[str, str]] = []
    unrounded: dict[str, dict[str, Decimal | None]] = {}
    for row in inputs:
        r = dict(row)
        if r['record_kind'] not in {'documented_facility','excluded_source_lead','historical_network_benchmark'}:
            raise ValueError(f'Unknown record kind: {r["record_kind"]}')
        for key in ('building_sqft','sqft_per_door','doors_per_acre','price_per_door_usd','published_area_to_site_area_pct','trailer_spaces_per_door'):
            r[key] = ''
        if r['record_kind'] == 'documented_facility':
            doors = number(r['doors'], 'doors')
            area = number(r['published_area'], 'published_area')
            acres = number(r['site_acres'], 'site_acres')
            price = number(r['documented_individual_price_usd'], 'documented_individual_price_usd')
            trailers = number(r['trailer_spaces'], 'trailer_spaces')
            if doors is not None and doors != doors.to_integral_value():
                raise ValueError('An exact door count must be an integer')
            if area is not None:
                if r['area_unit'] == 'm2':
                    sqft = area / FT_IN_METRES ** 2
                elif r['area_unit'] == 'ft2':
                    sqft = area
                else:
                    raise ValueError('An area requires ft2 or m2 units')
            else:
                sqft = None
            per_door = sqft / doors if sqft is not None and doors is not None else None
            r['building_sqft'] = rounded(sqft, 6) if r['area_unit']=='m2' else (str(sqft) if sqft is not None else '')
            r['sqft_per_door'] = rounded(per_door, 1)
            r['doors_per_acre'] = rounded(doors / acres if doors is not None and acres is not None else None, 2)
            r['price_per_door_usd'] = rounded(price / doors if price is not None and doors is not None else None, 2)
            r['published_area_to_site_area_pct'] = rounded(sqft / (acres * SQFT_PER_ACRE) * 100 if sqft is not None and acres is not None else None, 2)
            r['trailer_spaces_per_door'] = rounded(trailers / doors if trailers is not None and doors is not None else None, 2)
            unrounded[r['record_id']]={'sqft_per_door':per_door,'building_sqft':sqft}
        elif any(r[k] for k in ('doors','published_area','site_acres','documented_individual_price_usd','trailer_spaces')):
            raise ValueError('Excluded leads and carrier benchmarks cannot carry point-value facility measurements')
        outputs.append(r)
    csv_path=ROOT/'cross-dock-facility-register.csv'
    with csv_path.open('w', encoding='utf-8', newline='') as f:
        w=csv.DictWriter(f,fieldnames=list(outputs[0]));w.writeheader();w.writerows(outputs)
    counts=Counter(r['record_kind'] for r in outputs)
    comparison = unrounded['F18']['sqft_per_door'] / unrounded['F01']['sqft_per_door']
    findings={
        'record_counts':dict(counts),
        'all_register_entries':len(outputs),
        'documented_facilities_with_area_and_exact_door_count':sum(bool(r['sqft_per_door']) for r in outputs),
        'core5_to_crowley_published_area_per_door_ratio':rounded(comparison,2),
        'comparison_formula':'(1219021 / 224) / (30000 / 55)',
        'rosedale_equipped_docks_share_of_total_dock_doors_pct':rounded(Decimal(63)/Decimal(98)*100,1),
        'warnings':[
            'Purposive compilation, not a representative sample, current inventory or market trend series.',
            'Published building/property areas and dock denominator labels are not necessarily identical measurement concepts.',
            'No individual sale price is established in this release. No price-per-door distribution is calculated.',
            'The floor-area/site-area percentage is not a measured building footprint or verified zoning lot-coverage value.',
            'No optimal or actual facility shape is inferred from the historical geometry model.'
        ]
    }
    for filename,data in [('cross-dock-facility-register.json',{'version':VERSION,'source_checked':VERIFIED,'findings':findings,'records':outputs}),('cross-dock-derived-findings.json',findings)]:
        (ROOT/filename).write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
    print(json.dumps(findings,ensure_ascii=False,indent=2))

if __name__=='__main__':
    main()
