#!/usr/bin/env python3
"""Reproduce exports from the checked-in JSON; does not fetch or verify live sources."""
from __future__ import annotations
import argparse
import csv
import json
from pathlib import Path
from typing import Any

VERSION = '1.1'
DATE = '2026-09-15'
NAME = f'security-seal-types-dataset-v{VERSION}-{DATE}.json'
TABLES = {
    'seal_type_register': 'seal-type-register',
    'authority_ledger': 'seal-authority-ledger',
    'published_taxonomy_audit': 'published-taxonomy-audit',
    'manufacturer_comparison': 'manufacturer-seal-comparison',
    'published_threshold_claims': 'published-threshold-claims',
    'sources': 'source-register',
}

def derived(data: dict[str, Any]) -> dict[str, Any]:
    records = data['published_taxonomy_audit']
    included = [r for r in records if r['included_in_count_analysis']]
    counts = [len(r['selected_labels']) for r in included]
    for r in included:
        if r['type_count_claimed'] != len(r['selected_labels']):
            raise ValueError(f"List count mismatch: {r['source_id']}")
    for key in TABLES:
        if not isinstance(data.get(key), list):
            raise ValueError(f'Missing or invalid table: {key}')
    types = data['seal_type_register']
    auth = data['authority_ledger']
    models = data['manufacturer_comparison']
    return {
        'iso_17712_defined_type_count': sum(r['family'] == 'Mechanical (ISO 17712)' for r in types),
        'customs_editorial_color_use_entry_count': sum(r['family'].startswith('U.S. Customs') for r in types),
        'electronic_family_entry_count': sum(r['family'].startswith('Electronic') for r in types),
        'register_row_count': len(types),
        'authority_record_count_including_excluded': len(auth),
        'authority_included_record_count': sum(r['publish_status'] == 'Included' for r in auth),
        'authority_excluded_record_count': sum(r['publish_status'] == 'Excluded' for r in auth),
        'taxonomy_attempted_source_count': len(records),
        'taxonomy_included_source_count': len(included),
        'taxonomy_excluded_source_count': len(records) - len(included),
        'selected_list_count_min': min(counts),
        'selected_list_count_max': max(counts),
        'selected_list_counts': counts,
        'additional_list_counts': {r['source_id']: [len(q['labels']) for q in r['other_lists']] for r in included if r['other_lists']},
        'model_count': len(models),
        'model_declared_class_count': len({r['publisher_declared_classification'] for r in models}),
        'supplier_S_threshold_claim_ratio': max(r['claimed_S_minimum_kN'] for r in data['published_threshold_claims']) / min(r['claimed_S_minimum_kN'] for r in data['published_threshold_claims']),
        'strength_test_samples': data['calculation_inputs']['strength_classification']['tests'] * data['calculation_inputs']['strength_classification']['samples_per_test'],
        'cargo_vs_general_first_degree_value_ratio': data['calculation_inputs']['florida_first_degree_value_thresholds']['cargo_USD'] / data['calculation_inputs']['florida_first_degree_value_thresholds']['general_value_paragraph_USD'],
        'between_selected_S_and_H_model_diameters_mm': next(r['cable_diameter_mm'] for r in models if r['model_id'] == 'FG-325M') - next(r['cable_diameter_mm'] for r in models if r['model_id'] == 'FG-250M'),
        'no_market_prevalence_or_certification_inference': True,
    }

def serial_cell(value: Any) -> Any:
    if value is None:
        return ''
    if isinstance(value, (dict, list)):
        return json.dumps(value, ensure_ascii=False, separators=(',', ':'))
    if isinstance(value, bool):
        return 'true' if value else 'false'
    return value

def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source', type=Path, default=Path(__file__).with_name(NAME))
    parser.add_argument('--out-dir', type=Path, default=None)
    args = parser.parse_args()
    try:
        data = json.loads(args.source.read_text(encoding='utf-8'))
        data['derived'] = derived(data)
        out = args.out_dir or args.source.parent
        out.mkdir(parents=True, exist_ok=True)
        (out / NAME).write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
        for key, stem in TABLES.items():
            rows = data[key]
            fields = list(dict.fromkeys(k for row in rows for k in row))
            with (out / f'{stem}-v{VERSION}-{DATE}.csv').open('w', encoding='utf-8', newline='') as f:
                writer = csv.DictWriter(f, fieldnames=fields)
                writer.writeheader()
                writer.writerows({k: serial_cell(row.get(k)) for k in fields} for row in rows)
        print(json.dumps(data['derived'], indent=2))
    except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
        parser.exit(1, f'Export failed: {exc}\n')

if __name__ == '__main__':
    main()
