"""Reproduce or verify the GC021-AI01 volcanic carbon ledger."""
from argparse import ArgumentParser
from hashlib import file_digest
from math import isclose, isfinite
from pathlib import Path
import json


ROOT = Path(__file__).resolve().parents[1]
TASK_ID = 'GC021-AI01'


def positive(value):
    return type(value) in (int, float) and isfinite(value) and value > 0


def reconstruct(path):
    from openpyxl import load_workbook

    topic = json.loads((ROOT / 'content/GC021.json').read_text())
    task = next(row for row in topic['tasks'] if row['id'] == TASK_ID)
    expected = task['data_audit']['evidence'][0]['sha256']
    with path.open('rb') as stream:
        if file_digest(stream, 'sha256').hexdigest() != expected:
            raise ValueError('Workbook checksum differs from the audited supplement')

    rows, arcs = {}, {}
    book = load_workbook(path, read_only=True, data_only=True)
    try:
        for source_row, values in enumerate(book.active.iter_rows(min_row=12, values_only=True), 12):
            arc, volcano, so2, ratio, measured_reference, summary = (values[k] for k in (0, 1, 6, 14, 20, 23))
            if not isinstance(arc, str) or not isinstance(volcano, str) or not positive(summary):
                continue
            measured = reconstructed = residual = None
            if positive(so2) and positive(ratio):
                reconstructed = so2 * ratio * 44 / 64
                if positive(measured_reference):
                    measured = measured_reference
                    residual = reconstructed - measured
            rows[str(source_row)] = {
                'arc': arc,
                'volcano': volcano,
                'published_summary_kt_per_year': summary,
                'reconstructed_co2_kt_per_year': reconstructed,
                'published_measured_ratio_co2_kt_per_year': measured,
                'residual_kt_per_year': residual,
            }
            totals = arcs.setdefault(arc, {'published_kt_per_year': 0.0, 'measured_kt_per_year': 0.0})
            totals['published_kt_per_year'] += summary
            if reconstructed is not None:
                totals['measured_kt_per_year'] += reconstructed
    finally:
        book.close()

    for totals in arcs.values():
        totals['measured_share'] = totals['measured_kt_per_year'] / totals['published_kt_per_year']
    return {'rows': rows, 'arcs': arcs}


def check(reference, submission):
    disagreements = []
    if not isinstance(submission, dict):
        raise ValueError('Submit a JSON object containing rows and arcs')
    for group in ('rows', 'arcs'):
        actual = submission.get(group)
        expected = reference[group]
        if not isinstance(actual, dict) or actual.keys() != expected.keys():
            raise ValueError(f'Submit the complete {group} ledger with stable keys')
        for key, fields in expected.items():
            candidate = actual[key]
            if not isinstance(candidate, dict) or candidate.keys() != fields.keys():
                raise ValueError(f'{group} entry {key} has missing or unexpected fields')
            for field, value in fields.items():
                found = candidate[field]
                if type(value) in (int, float):
                    matches = type(found) in (int, float) and isclose(value, found, rel_tol=0, abs_tol=1e-6)
                else:
                    matches = found == value
                if not matches:
                    disagreements.append({'group': group, 'key': key, 'field': field})
    return disagreements


def main():
    cli = ArgumentParser(description=__doc__)
    cli.add_argument('workbook', type=Path)
    cli.add_argument('--submission', type=Path, help='Compare a separately produced JSON ledger')
    args = cli.parse_args()

    try:
        reference = reconstruct(args.workbook)
        result = {'task': TASK_ID}
        if args.submission:
            result['mismatches'] = check(reference, json.loads(args.submission.read_text()))
        else:
            result.update(reference)
    except (ImportError, OSError, ValueError) as error:
        cli.error(str(error))
    print(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False))
    return bool(result.get('mismatches'))


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