#!/usr/bin/env python3
"""Reproduce the published documentary-register counts. Python standard library only."""
from __future__ import annotations
import csv
import json
import sys
from collections import Counter
from pathlib import Path

DATE = '2026-09-12'
HERE = Path(__file__).resolve().parent

def csv_rows(stem: str) -> list[dict[str, str]]:
    with (HERE / f'{stem}-{DATE}.csv').open(encoding='utf-8', newline='') as handle:
        return list(csv.DictReader(handle))

def require(condition: bool, message: str) -> None:
    if not condition:
        raise ValueError(message)

def main() -> None:
    products = csv_rows('dock-seal-vs-shelter-application-limits')
    codes = csv_rows('dock-weatherseal-code-ledger')
    counties = csv_rows('nc-dock-weatherseal-climate-scope-by-county')
    data = json.loads((HERE / f'dock-seal-vs-shelter-dataset-{DATE}.json').read_text(encoding='utf-8'))
    require(len(products) == 14, 'Expected 14 product documentation records.')
    require(len({p['record_id'] for p in products}) == len(products), 'Duplicate product record IDs.')
    named = [p for p in products if p['record_kind'] == 'named_family']
    classes = [p for p in products if p['record_kind'] == 'general_category']
    seal_raw = [p for p in products if p['is_seal_label'] == 'true']
    seal_named = [p for p in named if p['is_seal_label'] == 'true']
    matches = [p for p in seal_named if p['documented_configuration_width_in'] and float(p['documented_configuration_width_in']) >= 120]
    require((len(named),len(classes),len(seal_raw),len(seal_named),len(matches)) == (11,3,9,7,3), 'Product denominator or width count changed.')
    require({p['record_id'] for p in matches} == {'bg-full-access','bg-inflatable','ss0251'}, 'Matching product IDs changed.')
    require(len({p['manufacturer'] for p in products}) == 4, 'Manufacturer count changed.')
    for p in products:
        require(p['is_seal_label'] == str(p['manufacturer_label'].lower().startswith('seal')).lower(), f"Inconsistent label coding: {p['record_id']}")
    require(len(codes) == 17, 'Expected 17 code-ledger records.')
    require(Counter(c['publish_status'] for c in codes) == {'included':15,'excluded':2}, 'Code evidence/exclusion count changed.')
    require(all(not c['climate_zone_scope'] and not c['explicit_top_and_side_contact'] for c in codes if c['publish_status']=='excluded'), 'Excluded lead contains an operative conclusion.')
    require(len(counties) == len({c['county'] for c in counties}) == 100, 'County records missing or duplicated.')
    zone_counts = Counter(c['climate_zone_2018_NCECC_Table_C301_1'] for c in counties)
    require(zone_counts == {'3A':46,'4A':48,'5A':6}, 'County-zone distribution changed.')
    require(sum(c['piedmont_triad_county']=='true' for c in counties)==12, 'Expected 12 regional counties.')
    for c in counties:
        zone = c['climate_zone_2018_NCECC_Table_C301_1']
        require(c['within_ASHRAE_2016_clause_zone_scope'] == str(zone!='3A').lower(), f"Climate-scope coding error: {c['county']}")
        require(c['clause_climate_scopes_differ'] == str(zone=='3A').lower(), f"Scope difference error: {c['county']}")
        require(c['project_requirement_determined']=='false', 'County crosswalk must not assert project-specific legal applicability.')
    normalized_products = []
    for row in products:
        row = dict(row)
        row['documented_configuration_width_in'] = int(row['documented_configuration_width_in']) if row['documented_configuration_width_in'] else None
        normalized_products.append(row)
    require(normalized_products == data['products'], 'Product CSV and combined JSON disagree.')
    require(codes == data['code_ledger'], 'Code CSV and combined JSON disagree.')
    require(counties == data['counties'], 'County CSV and combined JSON disagree.')
    inventory = json.loads((HERE / f'source-inventory-{DATE}.json').read_text(encoding='utf-8'))
    require(inventory == data['sources'], 'Source inventory and combined JSON disagree.')
    source_ids = {s['id'] for s in inventory}
    for row in products + codes:
        require(all(s in source_ids for s in row['source_ids'].split(';') if s), 'Unresolved source reference in data.')
    summary = {
        'version':data['version'], 'product_records':len(products),
        'named_families':len(named), 'general_classes':len(classes),
        'raw_seal_label_records':len(seal_raw), 'named_seal_families':len(seal_named),
        'named_seal_families_with_configuration_at_least_120_in_wide':len(matches),
        'matching_product_ids':[p['record_id'] for p in matches],
        'code_ledger_records':len(codes), 'included_code_records':15, 'excluded_code_leads':2,
        'counties':len(counties), 'county_zone_counts':dict(sorted(zone_counts.items())),
        'county_scope_difference_count':sum(c['clause_climate_scopes_differ']=='true' for c in counties),
        'csv_json_consistency':'passed'
    }
    print(json.dumps(summary,indent=2))

if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, KeyError, json.JSONDecodeError) as exc:
        print(f'Verification failed: {exc}',file=sys.stderr)
        sys.exit(1)
