"""Anant Mishra, AM-RP-002: synthetic aggregate arithmetic, not a field audit."""
import json
from pathlib import Path

FIELDS = ('opening_stock_g', 'incoming_g', 'other_inflow_g', 'material_output_g',
          'residue_output_g', 'other_outflow_g', 'closing_stock_g')


def reconcile(account, tolerance_g):
    """Strict integer-gram contract. Preserve unknowns and signed differences.

    No ingestion, measurement verification, cohort tracing or recovery rate.
    Caller must justify the physical/time boundary, other flows and tolerance.
    """
    if type(tolerance_g) is not int or tolerance_g < 0:
        raise ValueError('tolerance must be a nonnegative integer number of grams')
    if not isinstance(account, dict) or set(account) != set(FIELDS) | {'unit'}:
        raise ValueError('exact declared quantity fields and unit required')
    if account['unit'] != 'g':
        raise ValueError('unit must be g; no implicit conversion')
    for name in FIELDS:
        value = account[name]
        if value is not None and (type(value) is not int or value < 0):
            raise ValueError('quantities must be nonnegative integers or explicit null')
    missing = [name for name in FIELDS if account[name] is None]
    if missing:
        return dict(status='incomplete', unit='g', available_g=None,
                    accounted_g=None, discrepancy_g=None, tolerance_g=tolerance_g,
                    missing_fields=missing)
    available = account['opening_stock_g'] + account['incoming_g'] + account['other_inflow_g']
    accounted = account['material_output_g'] + account['residue_output_g'] + account['other_outflow_g'] + account['closing_stock_g']
    discrepancy = available - accounted
    status = 'balanced' if discrepancy == 0 else 'within_tolerance' if abs(discrepancy) <= tolerance_g else 'unreconciled'
    return dict(status=status, unit='g', available_g=available,
                accounted_g=accounted, discrepancy_g=discrepancy,
                tolerance_g=tolerance_g, missing_fields=[])


if __name__ == '__main__':
    fixture = json.loads(Path(__file__).with_name('synthetic-material-accounts.json').read_text())
    print(json.dumps({'status': 'synthetic_software_reference_only', 'cases': {
        row['id']: reconcile(row['account'], fixture['tolerance_g'])
        for row in fixture['cases']}}, indent=2))
