#!/usr/bin/env python3
"""Reproduce this compilation's arithmetic from saved, source-linked inputs.

Usage: python compute-warehouse-energy-derived.py [path/to/warehouse-energy-inputs.json]
Uses only Python's standard library and performs no network operations.
Published EIA estimates are retained: this does not reconstruct their microdata.
Outputs JSON to stdout; source discrepancies caused by rounding are preserved.
"""
from __future__ import annotations
import json
import math
import sys
from pathlib import Path
from typing import Any


def ratio(numerator: float, denominator: float) -> float:
    if not isinstance(numerator, (int, float)) or not isinstance(denominator, (int, float)):
        raise ValueError('Ratios require numeric, non-suppressed values.')
    if denominator == 0:
        raise ValueError('Ratio denominator must not be zero.')
    return numerator / denominator


def calculate(data: dict[str, Any]) -> dict[str, Any]:
    rows = data['benchmark_rows']
    if len(rows) != 6:
        raise ValueError('Expected four warehouse leaf categories and two rollups.')
    total = rows[0][4]
    count_total, floor_total, energy_total = total[:3]
    btu_per_kwh = data['btu_per_kwh']
    if btu_per_kwh != 3412:
        raise ValueError('Unexpected electricity conversion; review the source before using it.')
    comparisons = []
    for i, (rid, name, kind, parent, major, electric, gas) in enumerate(rows):
        pb = data['published_per_building']
        out = {
            'row_id': rid,
            'building_type': name,
            'row_kind': kind,
            'building_share_percent': 100 * ratio(major[0], count_total),
            'floorspace_share_percent': 100 * ratio(major[1], floor_total),
            'major_fuel_energy_share_percent': 100 * ratio(major[2], energy_total),
            'electricity_using_floorspace_share_percent': 100 * ratio(electric[1], major[1]),
            'gas_using_floorspace_share_percent': (
                100 * ratio(gas[1], major[1]) if isinstance(gas[1], (int, float)) else 'Q'
            ),
            'gross_mean_divided_by_building_median': ratio(major[3], major[5]),
            'published_average_building_sqft': pb['area_thousand_sqft'][i] * 1000,
            'published_energy_per_building_million_btu': pb['energy_million_btu'][i],
            'published_energy_per_building_ratio_to_nonrefrigerated_warehouse': ratio(
                pb['energy_million_btu'][i], pb['energy_million_btu'][2]),
            'rounded_total_electricity_share_arithmetic_percent_NOT_OFFICIAL_SHARE': (
                100 * electric[2] * btu_per_kwh / 1000 / major[2]),
            'rounding_note': 'Per-building values are EIA published inputs, not quotients of rounded counts. Fuel-share arithmetic from coarse totals is a rounding diagnostic, not an official EIA share.',
        }
        comparisons.append(out)
    leaves = [r for r in rows if r[2] == 'leaf']
    end_uses = []
    for name, energy, conditional in data['end_use_rows']:
        end_uses.append({
            'end_use': name,
            'eia_modeled_energy_trillion_btu': energy,
            'derived_energy_share_percent': 100 * ratio(energy, energy_total),
            'derived_gross_intensity_kbtu_sqft_year': 1000 * ratio(energy, floor_total),
            'eia_published_conditional_intensity_kbtu_sqft_year': conditional,
        })
    region_recalculations = [
        {'division': r[0], 'published_gross_intensity': r[3],
         'rounded_input_recalculation': 1000 * ratio(r[1], r[2]),
         'recalculation_minus_published': 1000 * ratio(r[1], r[2]) - r[3]}
        for r in data['regional_rows']
    ]
    hist = data['historical']
    historical_change = {
        k: 100 * (ratio(hist['2018'][k], hist['2012'][k]) - 1)
        for k in hist['2012']
    }
    leaf_energy = sum(r[4][2] for r in leaves)
    leaf_floor = sum(r[4][1] for r in leaves)
    leaf_count = sum(r[4][0] for r in leaves)
    region_floor = sum(r[2] for r in data['regional_rows'])
    region_energy = sum(r[1] for r in data['regional_rows'])
    end_energy = sum(r[1] for r in data['end_use_rows'])
    converted_electricity = rows[0][5][2] * btu_per_kwh / 1000
    refrigerated_rounded_pb = rows[5][4][2] / rows[5][4][0] * 1000
    ref_electric_intensity_ratio = 100 * rows[5][5][3] * btu_per_kwh / 1000 / rows[5][4][3]
    assert leaf_energy == 528 and leaf_floor == 17482 and leaf_count == 1003
    assert region_floor == 17483 and region_energy == 529 and end_energy == 529
    assert math.isclose(converted_electricity, 324.14)
    assert len([s for r in data['regional_rows'] for s in r[8].split('|')]) == 51
    checks = {
        '1_component_sums': {
            'leaf_energy_trillion_btu': leaf_energy, 'published_total_energy': energy_total,
            'leaf_floor_million_sqft': leaf_floor, 'published_total_floor': floor_total,
            'leaf_count_thousand': leaf_count, 'published_total_count': count_total,
            'interpretation': 'Displayed inputs are independently rounded; retain small discrepancies.',
        },
        '2_electricity_conversion': {
            'converted_95_billion_kwh_to_trillion_btu': converted_electricity,
            'published_profile_electricity_trillion_btu': 325,
            'absolute_difference_percent_of_profile': 100 * abs(converted_electricity - 325) / 325,
            'interpretation': 'Rounded-source consistency check, not a replacement of either value.',
        },
        '3_intensity_and_per_building': {
            'implied_total_floor_million_sqft': 1000 * energy_total / total[3],
            'published_total_floor_million_sqft': floor_total,
            'refrigerated_naive_rounded_energy_per_building_million_btu': refrigerated_rounded_pb,
            'refrigerated_published_energy_per_building_million_btu': 10144,
            'refrigerated_naive_rounded_average_floor_sqft': 327 / 3 * 1000,
            'refrigerated_published_average_floor_sqft': 94800,
            'interpretation': 'Use the issuer\'s published per-building measures, not naive rounded quotients.',
        },
        '4_regional_and_end_use_sums': {
            'regional_floor_million_sqft': region_floor,
            'regional_energy_trillion_btu': region_energy,
            'modeled_end_use_components_trillion_btu': end_energy,
            'published_national_total_energy_trillion_btu': energy_total,
            'max_absolute_regional_intensity_rounding_difference': max(abs(r['recalculation_minus_published']) for r in region_recalculations),
        },
        '5_cross_agency_category_ordering': {
            'eia_nonrefrigerated_warehouse_median': 18.8,
            'epa_combined_warehouse_distribution_median': 22.7,
            'eia_distribution_median': 27.6,
            'combined_reference_between_subgroups': 18.8 < 22.7 < 27.6,
            'interpretation': 'Ordering only; NOT evidence of shared observation year or a validation of combined medians.',
        },
    }
    derived = {
        'distribution_to_nonrefrigerated_average_size_ratio': 47.8 / 12.9,
        'warehouse_to_all_commercial_gross_intensity_percent': 100 * 30.2 / 70.4,
        'refrigerated_to_nonrefrigerated_gross_intensity_ratio': 107.0 / 26.1,
        'heating_plus_lighting_percent': 100 * (208 + 80) / 528,
        'heating_rounded_share_times_whole_category_intensity': 0.39 * 30.2,
        'conditional_heating_to_derived_gross_heating_ratio': 15.8 / (208 * 1000 / 17483),
        'east_north_central_above_national_percent': 100 * (35.6 / 30.2 - 1),
        'refrigerated_electric_intensity_ratio_percent_ROUNDING_DIAGNOSTIC': ref_electric_intensity_ratio,
        'epa_warehouse_source_median_to_site_median_ratio_NOT_BUILDING_CONVERSION': 52.9 / 22.7,
        'epa_refrigerated_source_median_to_site_median_ratio_NOT_BUILDING_CONVERSION': 235.6 / 84.1,
        'epa_refrigerated_median_below_eia_percent': 100 * (113.5 - 84.1) / 113.5,
        'eia_refrigerated_median_above_epa_percent': 100 * (113.5 - 84.1) / 84.1,
        'warehouse_floor_not_using_electricity_percent': 100 * (1 - 16335 / 17483),
        'illustrative_50000_sqft_at_5_8_kwh_sqft_NOT_A_MEASUREMENT': 50000 * 5.8,
    }
    return {'version': data['version'], 'last_verified': data['verified_on'],
            'building_comparisons': comparisons, 'modeled_end_use_calculations': end_uses,
            'regional_rounding_checks': region_recalculations, 'historical_percent_changes': historical_change,
            'other_derived_arithmetic': derived, 'five_reconciliation_checks': checks,
            'validation': 'passed',
            'warning': 'Arithmetic on rounded, sample-survey estimates does not create new measurement precision or ratio confidence intervals.'}


def main() -> int:
    path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name('warehouse-energy-inputs.json')
    try:
        with path.open(encoding='utf-8') as handle:
            data = json.load(handle)
        result = calculate(data)
    except (OSError, ValueError, KeyError, TypeError, AssertionError) as exc:
        print(f'Input or validation error: {exc}', file=sys.stderr)
        return 1
    print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
