"""Recompute numerical references from the provider files cited by the AI tasks.

Supply the exact raw files in the order shown by each task's dataset links.
Install NumPy, plus netCDF4 for NetCDF cases or openpyxl for ISRaD.
"""
import argparse
from collections import defaultdict
import csv
from contextlib import ExitStack
import hashlib
import json
from math import isfinite
from pathlib import Path
from zipfile import ZipFile

import numpy as np


def carbon_tracers(paths):
    """Compare held-station transient-tracer gradients and DIC:P contrasts."""
    from netCDF4 import Dataset

    variables = ('cfc_12', 'sulfur_hexifluoride', 'total_carbon', 'phosphate')
    with Dataset(paths[0]) as data:
        pressure = data['pressure'][:].filled(np.nan)
        values = {}
        for name in variables:
            value = data[name][:].filled(np.nan)
            value[data[name + '_qc'][:].filled(0) != 2] = np.nan
            values[name] = value
    layers = ((200, 500), (1000, 2000))
    contrasts = {name: [] for name in variables}
    for station, levels in enumerate(pressure):
        for name, value in values.items():
            samples = [value[station, (levels >= low) & (levels <= high)
                             & np.isfinite(value[station])] for low, high in layers]
            if min(map(len, samples)) >= 2:
                contrasts[name].append((station, np.median(samples[1]) - np.median(samples[0])))
    maps = {name: dict(rows) for name, rows in contrasts.items()}
    result = {}
    for response, driver, label, factor in [('sulfur_hexifluoride', 'cfc_12', 'tracer', None),
                                             ('total_carbon', 'phosphate', 'dic', 106)]:
        stations = sorted(maps[response].keys() & maps[driver].keys())
        actual = np.array([maps[response][station] for station in stations])
        x = np.array([maps[driver][station] for station in stations])
        assert len(stations) >= 10
        errors, baseline_errors = [], []
        for hold in np.array_split(np.arange(len(x)), 4):
            training = np.ones(len(x), bool)
            training[hold] = False
            baseline = np.median(actual[training])
            if factor is None:
                slope, intercept = np.polyfit(x[training], actual[training], 1)
                estimate = slope * x[hold] + intercept
            else:
                estimate = factor * x[hold]
            errors.extend(abs(estimate - actual[hold]))
            baseline_errors.extend(abs(baseline - actual[hold]))
        result[label] = {'paired_casts': len(stations), 'mae': float(np.mean(errors)),
                         'median_baseline_mae': float(np.mean(baseline_errors)),
                         'median_deep_minus_shallow': float(np.median(actual))}
    return result


def atomix(paths):
    """Measure agreement of separately recorded probes by deployment."""
    from netCDF4 import Dataset

    deployments = []
    for path in paths:
        with ZipFile(path) as archive:
            member = next(name for name in archive.namelist() if name.endswith('.nc'))
            with Dataset(member, memory=archive.read(member)) as data:
                spectra = data['L3_spectra']
                dissipation = data['L4_dissipation']
                assert np.array_equal(spectra['TIME'][:], dissipation['TIME'][:])
                a, b = dissipation['EPSI'][:2].filled(np.nan)
                flags = dissipation['EPSI_FLAGS'][:].filled(-1)
                if flags.ndim == 2:
                    flags = np.any(flags != 0, axis=0)
                else:
                    flags = flags != 0
                valid = (a > 0) & (b > 0)
                differences = np.log10(a[valid]) - np.log10(b[valid])
                clean = differences[~flags[valid]]
                flagged = differences[flags[valid]]
                assert len(clean) and len(flagged)
                deployments.append({'archive': path.name, 'windows': int(valid.sum()),
                                    'flagged': len(flagged),
                                    'unflagged_median_abs_dex': float(np.median(abs(clean))),
                                    'flagged_median_abs_dex': float(np.median(abs(flagged)))})
    return deployments


def dust_cutoffs(paths):
    """Recompute annual coarse dust optical-depth increments from two grids."""
    from netCDF4 import Dataset

    fine_path, wide_path = paths
    with Dataset(fine_path) as fine, Dataset(wide_path) as wide:
        latitude = fine['lat'][:].filled(np.nan)
        longitude = fine['lon'][:].filled(np.nan)
        if not (np.array_equal(wide['lat'][:], latitude) and
                np.array_equal(wide['lon'][:], longitude)):
            raise ValueError('The two DustCOMM grids must share coordinates')
        quantiles = {name: (fine[name][:].filled(np.nan), wide[name][:].filled(np.nan))
                     for name in ('Median', 'Neg1sigma', 'Pos1sigman')}
    lat, lon = np.meshgrid(latitude, longitude, indexing='ij')
    weights = np.cos(np.deg2rad(lat))
    regions = {'sahara': (15, 35, -15, 35),
               'tropical_atlantic': (10, 25, -55, -20),
               'arabian_sea': (5, 25, 50, 75)}
    output = {}
    for region, (south, north, west, east) in regions.items():
        area = (lat >= south) & (lat < north) & (lon >= west) & (lon < east)
        record = {}
        for label, (narrow, broad) in quantiles.items():
            eligible = area & np.isfinite(narrow) & np.isfinite(broad)
            if not np.any(eligible):
                raise ValueError(f'No joint observations in {region}')
            delta = broad[eligible] - narrow[eligible]
            w = weights[eligible]
            record[label] = {'eligible_cells': int(eligible.sum()),
                             'pm10_daod': float(np.average(narrow[eligible], weights=w)),
                             'pm20_daod': float(np.average(broad[eligible], weights=w)),
                             'increment': float(np.average(delta, weights=w)),
                             'positive_fraction': float(np.mean(delta > 0))}
        output[region] = record
    return output


def deep_c_budget(paths):
    """Check published positive-down net radiation on a common grid."""
    from netCDF4 import Dataset, num2date

    with ExitStack() as stack:
        asr, olr, net = [stack.enter_context(Dataset(path)) for path in paths]
        for name in ('time', 'lat', 'lon'):
            axis = asr[name][:]
            if not np.array_equal(axis, olr[name][:]) or not np.array_equal(axis, net[name][:]):
                raise ValueError(f'DEEP-C files disagree on {name}')
        if {asr['ASR'].units, olr['OLR'].units, net['NET'].units} != {'W/m2'}:
            raise ValueError('Expected unscaled W/m2 fluxes')
        if len({asr['time'].units, olr['time'].units, net['time'].units}) != 1:
            raise ValueError('Expected the same time units')
        dates = num2date(asr['time'][:], asr['time'].units)
        weights = np.broadcast_to(np.cos(np.deg2rad(asr['lat'][:]))[:, None],
                                  (len(asr['lat']), len(asr['lon'])))
        rows = []
        for i, date in enumerate(dates):
            sw, lw, target = [dataset[var][i].astype(float).filled(np.nan)
                              for dataset, var in ((asr, 'ASR'), (olr, 'OLR'), (net, 'NET'))]
            eligible = np.isfinite(sw) & np.isfinite(lw) & np.isfinite(target)
            error = sw[eligible] + lw[eligible] - target[eligible]
            if not error.size:
                raise ValueError(f'No jointly available radiation fields in {date}')
            w = weights[eligible]
            rows.append({'year': date.year, 'month': date.month, 'eligible_cells': int(eligible.sum()),
                         'area_fraction': float(w.sum() / weights.sum()),
                         'mean_signed_residual_w_m2': float(np.average(error, weights=w)),
                         'mean_absolute_residual_w_m2': float(np.average(abs(error), weights=w)),
                         'zero_net_baseline_mae_w_m2': float(np.average(abs(target[eligible]), weights=w))})
    return rows


def boona_support(paths):
    """Compute nominal drillhole offsets and two support-weighting summaries."""
    features = json.loads(paths[0].read_text())['features']
    offsets = []
    for feature in features:
        hole = feature['properties']
        dip, azimuth = np.deg2rad([hole['dip'], hole['collar_azimuth']])
        length = hole['end_depth']
        horizontal = length * np.cos(dip)
        offsets.append({'hole_id': hole['holeid'],
                        'east_offset_m': float(horizontal * np.sin(azimuth)),
                        'north_offset_m': float(horizontal * np.cos(azimuth)),
                        'down_offset_m': float(-length * np.sin(dip)),
                        'sample_count': hole['num_samples'],
                        'arsenic_summary_ppm': hole['as_ppm']})
    if len({hole['hole_id'] for hole in offsets}) != len(offsets):
        raise ValueError('Expected unique hole IDs')
    support = np.array([hole['sample_count'] for hole in offsets], dtype=float)
    values = np.array([hole['arsenic_summary_ppm'] for hole in offsets], dtype=float)
    if not np.all(np.isfinite(values) & (support > 0)):
        raise ValueError('Arsenic summaries and positive hole sample counts are required')
    holdouts = {}
    for i, hole in enumerate(offsets):
        keep = np.arange(len(offsets)) != i
        holdouts[hole['hole_id']] = float(np.average(values[keep], weights=support[keep]))
    return {'holes': offsets,
            'equal_hole_ppm': float(np.mean(values)),
            'weighted_hole_ppm': float(np.average(values, weights=support)),
            'leave_one_out_weighted_ppm': holdouts}


def alkalinity_export(paths):
    """Reconcile weighted and unweighted monthly climatological exports."""
    groups = {}
    excluded = 0
    with paths[0].open(newline='') as data:
        for row in csv.DictReader(data):
            station, month = row['site_no'], int(row['stream_month'])
            discharge, concentration, weighted, target = map(
                float, (row['discharge_l_d'], row['alk'], row['alk_discharge_weight'], row['alk_flux']))
            obs = discharge, concentration, weighted, target
            if not all(np.isfinite(obs)) or discharge <= 0 or target == 0 or not 1 <= month <= 12:
                excluded += 1
                continue
            stations = groups.setdefault(station, {})
            if month in stations:
                raise ValueError(f'Duplicate {station}/{month}')
            stations[month] = (discharge * weighted, discharge * concentration, target)
    rows = []
    for station, months in sorted(groups.items()):
        if len(months) != 12:
            continue
        weighted, ordinary, target = np.array([months[i] for i in range(1, 13)]).T
        rows.append({'station': station, 'max_weighted_error': float(max(abs(weighted - target))),
                     'mean_unweighted_error': float(np.mean(abs(ordinary - target))),
                     'mean_unweighted_fractional_error': float(np.mean(abs(ordinary / target - 1)))})
    return {'excluded_rows': excluded, 'complete_stations': rows}


def israd_gradients(paths):
    """Reconstruct paired-depth bulk carbon and Δ14C contrasts from ISRaD v1."""
    from openpyxl import load_workbook

    (path,) = paths
    groups = defaultdict(lambda: ([], []))
    with path.open('rb') as source:
        checksum = hashlib.file_digest(source, 'sha256').hexdigest()
        if checksum != 'c13fee546c03388fb4b6ca37bf6e3443ef7da4337b89811a303609b9f53da9b1':
            raise ValueError('Expected the ISRaD v1 workbook released on 2019-03-27')
        source.seek(0)
        workbook = load_workbook(source, read_only=True, data_only=True)
        try:
            layers = workbook['layer']
            layers.reset_dimensions()
            rows = layers.values
            headings = list(next(rows))
            fields = ('entry_name', 'site_name', 'pro_name', 'lyr_name',
                      'lyr_top', 'lyr_bot', 'lyr_c_org', 'lyr_14c')
            indices = [headings.index(field) for field in fields]
            for row in rows:
                study, site, profile, layer, top, bottom, carbon, isotope = (row[i] for i in indices)
                if not all((study, site, profile, layer)):
                    continue
                if not all(type(value) in (int, float) and isfinite(value)
                           for value in (top, bottom, carbon, isotope)):
                    continue
                if top > bottom:
                    continue
                midpoint = (top + bottom) / 2
                if 0 <= midpoint <= 20:
                    groups[study, site, profile][0].append((carbon, isotope))
                elif 30 <= midpoint <= 100:
                    groups[study, site, profile][1].append((carbon, isotope))
        finally:
            workbook.close()

    profiles = []
    for (study, site, profile), (shallow, deep) in sorted(groups.items()):
        if not shallow or not deep:
            continue
        carbon_change, isotope_change = np.median(deep, axis=0) - np.median(shallow, axis=0)
        profiles.append({'study': study, 'site': site, 'profile': profile,
                         'carbon_change_pct': float(carbon_change),
                         'delta14c_change_per_mil': float(isotope_change),
                         'discordant': bool(carbon_change < 0 <= isotope_change)})
    return profiles


def score_israd_gradients(reference, submission):
    key_fields = ('study', 'site', 'profile')
    measures = ('carbon_change_pct', 'delta14c_change_per_mil')
    with_labels = {*key_fields, *measures, 'discordant'}
    if not isinstance(submission, list):
        raise ValueError('Expected a list of study, site and profile rows')
    claimed = {}
    for row in submission:
        if not isinstance(row, dict) or row.keys() != with_labels:
            raise ValueError('Every row must have the reference profile fields')
        key = tuple(row[field] for field in key_fields)
        if not all(isinstance(value, str) for value in key) or key in claimed:
            raise ValueError(f'Invalid or duplicated profile identity {key}')
        claimed[key] = row
    expected = {tuple(row[field] for field in key_fields): row for row in reference}
    if expected.keys() != claimed.keys():
        raise ValueError('Submission must contain each eligible profile exactly once')

    def scores(keys):
        errors = {field: [] for field in measures}
        expected_positive = submitted_positive = true_positive = 0
        for key in keys:
            actual, row = expected[key], claimed[key]
            for field in measures:
                difference = reference_residuals(actual[field], row[field], f'{key}/{field}')
                errors[field].append(abs(difference))
            if type(row['discordant']) is not bool:
                raise ValueError(f'{key}: discordant must be a boolean')
            expected_positive += actual['discordant']
            submitted_positive += row['discordant']
            true_positive += actual['discordant'] and row['discordant']
        total_positive = expected_positive + submitted_positive
        return {'profiles': len(keys), 'discordant_profiles': expected_positive,
                **{field + '_mae': float(np.mean(values)) for field, values in errors.items()},
                'discordance_f1': 2 * true_positive / total_positive if total_positive else 0.0,
                'always_codirectional_baseline_f1': 0.0}

    by_study = defaultdict(list)
    for key in expected:
        by_study[key[0]].append(key)
    return {'overall': scores(list(expected)),
            'by_study': {study: scores(keys) for study, keys in sorted(by_study.items())}}


CASES = {'carbon-tracers': carbon_tracers, 'atomix': atomix,
         'dust-cutoffs': dust_cutoffs, 'deep-c-budget': deep_c_budget,
         'boona-support': boona_support, 'alkalinity-export': alkalinity_export,
         'israd-gradients': israd_gradients}


def reference_residuals(reference, submitted, name='score'):
    """Compare each numeric measure and preserve the reference schema."""
    if isinstance(reference, dict):
        if not isinstance(submitted, dict) or reference.keys() != submitted.keys():
            raise ValueError(f'Missing or unexpected fields at {name}')
        return {key: reference_residuals(value, submitted[key], f'{name}.{key}')
                for key, value in reference.items()}
    if isinstance(reference, list):
        if not isinstance(submitted, list) or len(reference) != len(submitted):
            raise ValueError(f'Missing or unexpected rows at {name}')
        return [reference_residuals(value, claimed, f'{name}[{i}]')
                for i, (value, claimed) in enumerate(zip(reference, submitted))]
    if isinstance(reference, (float, int)) and not isinstance(reference, bool):
        if type(submitted) not in (float, int) or not isfinite(submitted):
            raise ValueError(f'Expected a finite number at {name}')
        return submitted - reference
    if reference != submitted:
        raise ValueError(f'Identity mismatch at {name}')
    return reference


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('case', choices=CASES)
    parser.add_argument('files', type=Path, nargs='+')
    parser.add_argument('--submission', type=Path, help='Compare a submission with the computed reference.')
    args = parser.parse_args()
    try:
        result = CASES[args.case](args.files)
        if args.submission:
            submission = json.loads(args.submission.read_text())
            if args.case == 'israd-gradients':
                result = score_israd_gradients(result, submission)
            else:
                result = {'residuals': reference_residuals(result, submission)}
    except ValueError as error:
        parser.error(str(error))
    print(json.dumps(result, indent=2, allow_nan=False))
