"""Fit constrained grey-opacity kilonova models to the fixed GW170817 photometry.

Run from this folder:

    python fit_two_component.py            # writes fit-outputs.json
    python fit_two_component.py --check    # recomputes and compares with the saved file

Models (every component: mass M, velocity v, opacity kappa, temperature floor Tc):
  two-component        blue kappa = 0.5 fixed, red kappa free (Villar et al. 2017, Table 2 row 1)
  red-kappa-10         as above with red kappa fixed at 10 cm^2/g (lanthanide-rich prior)
  one-component        a single grey component with free kappa
  no-floor             the two-component model with both floors pinned at 300 K

The likelihood follows Villar et al. 2017, Section 3.2, eq. 6: Gaussian errors with an
extra scatter sigma added in quadrature. As printed, eq. 6 normalises with
-ln(2 pi sigma_i^2) inside the sum and -(n/2) ln(2 pi sigma^2) outside it; we use the
normalised Gaussian with variance sigma_i^2 + sigma^2 in both places, which is what the
quadrature sum implies. Villar et al. sample the posterior with MOSFiT and compare models
with WAIC; this script maximises the likelihood, compares models with BIC and uses
detections only (no upper limits). Each fit alternates a bounded least-squares step at
fixed sigma with a one-dimensional maximisation over sigma.
"""
import argparse
import csv
import hashlib
import json
import math
import platform
import sys
from pathlib import Path

import numpy as np
import scipy
from scipy.optimize import least_squares, minimize_scalar

from kilonova_model import diffusion_time_days, model_magnitudes

HERE = Path(__file__).resolve().parent
INPUTS = json.loads((HERE / 'tutorial-inputs.json').read_text())
PARAMETER_NAMES = ['blueMass', 'blueVelocity', 'blueFloor', 'redMass', 'redVelocity', 'redFloor', 'redOpacity']
LOWER = [0.001, 0.05, 300.0, 0.001, 0.05, 300.0, 0.5]
UPPER = [0.10, 0.40, 8000.0, 0.10, 0.40, 8000.0, 30.0]


def load_photometry():
    raw = (HERE / INPUTS['photometry']['file']).read_bytes()
    digest = hashlib.sha256(raw).hexdigest()
    if digest != INPUTS['photometry']['sha256']:
        raise SystemExit(f'Photometry digest {digest} differs from tutorial-inputs.json')
    rows = list(csv.DictReader(raw.decode().splitlines()))
    times = np.array([float(row['days_since_merger']) for row in rows])
    bands = [row['band'] for row in rows]
    magnitudes = np.array([float(row['ab_mag']) for row in rows])
    errors = np.array([float(row['ab_mag_error']) for row in rows])
    return times, bands, magnitudes, errors


TIMES, BANDS, MAGNITUDES, ERRORS = load_photometry()


def predicted_magnitudes(components, ebv=None):
    ebv = INPUTS['extinction']['ebvSfd'] if ebv is None else ebv
    coefficients = INPUTS['extinction']['coefficients']
    model, _, _ = model_magnitudes(TIMES, components, INPUTS['bandWavelengthsAngstrom'], INPUTS['distanceMpc'])
    return np.array([model[band][index] + coefficients[band] * ebv for index, band in enumerate(BANDS)])


def two_component(x):
    return [(x[0], x[1], INPUTS['fixedModel']['blueOpacity'], x[2]), (x[3], x[4], x[6], x[5])]


def negative_log_likelihood(residuals, scatter):
    variance = ERRORS ** 2 + scatter ** 2
    return 0.5 * float(np.sum(residuals ** 2 / variance + np.log(2 * math.pi * variance)))


def fit(unpack, start, free, ebv=None, rounds=4):
    """Fit the parameters flagged in `free`; the rest stay at `start`."""
    start = np.array(start, dtype=float)
    free = np.array(free, dtype=bool)
    lower, upper = np.array(LOWER)[free], np.array(UPPER)[free]
    scatter = 0.25
    x = start.copy()

    def full(values):
        result = start.copy()
        result[free] = values
        return result

    for _ in range(rounds):
        whitened = lambda values: (predicted_magnitudes(unpack(full(values)), ebv) - MAGNITUDES) / np.sqrt(ERRORS ** 2 + scatter ** 2)
        solution = least_squares(whitened, np.clip(x[free], lower, upper), bounds=(lower, upper), x_scale='jac')
        x = full(solution.x)
        residuals = predicted_magnitudes(unpack(x), ebv) - MAGNITUDES
        scatter = minimize_scalar(lambda value: negative_log_likelihood(residuals, value), bounds=(1e-3, 2.0), method='bounded').x
    residuals = predicted_magnitudes(unpack(x), ebv) - MAGNITUDES
    jacobian = solution.jac / 1.0  # d(whitened residual)/d(free parameter) at the optimum
    return x, scatter, residuals, jacobian


def summary(name, x, scatter, residuals, free_count, components):
    nll = negative_log_likelihood(residuals, scatter)
    parameters = len(free_count) if isinstance(free_count, list) else free_count
    return {
        'model': name,
        'parameters': {key: round(float(value), 5) for key, value in zip(PARAMETER_NAMES, x)},
        'scatter': round(float(scatter), 4),
        'rmsResidual': round(float(np.sqrt(np.mean(residuals ** 2))), 4),
        'negativeLogLikelihood': round(nll, 2),
        'freeParameters': parameters + 1,
        'bic': round(2 * nll + (parameters + 1) * math.log(len(MAGNITUDES)), 2),
        'diffusionDays': [round(diffusion_time_days(c[0], c[1], c[2]), 4) for c in components],
        'bandRms': {band: round(float(np.sqrt(np.mean(residuals[[b == band for b in BANDS]] ** 2))), 4) for band in INPUTS['bandWavelengthsAngstrom']},
        'lateKResidualMean': round(float(np.mean(residuals[[(b == 'K' and t > 10) for b, t in zip(BANDS, TIMES)]])), 4),
    }


def covariance_from_jacobian(jacobian):
    information = jacobian.T @ jacobian
    return np.linalg.inv(information)


def degeneracy_grid(best, second_mode, scatter):
    """Red mass against red velocity with every other parameter re-fitted at fixed scatter."""
    masses = np.round(np.linspace(0.03, 0.08, 11), 4)
    velocities = np.round(np.linspace(0.10, 0.22, 13), 4)
    free = [True, True, True, False, False, True, True]
    rows = []
    previous_row = None
    for mass in masses:
        row, solutions = [], []
        for column, velocity in enumerate(velocities):
            candidates = [best.copy(), np.array(second_mode, dtype=float)] + ([previous_row[column].copy()] if previous_row else []) + ([solutions[-1].copy()] if solutions else [])
            outcomes = []
            for start in candidates:
                start[3], start[4] = mass, velocity
                x, _, residuals, _ = fit(two_component, start, free, rounds=1)
                outcomes.append((negative_log_likelihood(residuals, scatter), x))
            value, x = min(outcomes, key=lambda item: item[0])
            row.append(round(value, 2))
            solutions.append(x)
        rows.append(row)
        previous_row = solutions
    return {'redMass': masses.tolist(), 'redVelocity': velocities.tolist(), 'negativeLogLikelihood': rows,
            'note': 'Profile over the other five parameters at the best-fit scatter. Constant diffusion time means M/v constant at fixed kappa.'}


def run():
    published = INPUTS['publishedComparison']
    published_x = [published[key] for key in PARAMETER_NAMES]
    results = {}

    # The likelihood has several local optima. Start from the published values and
    # from 16 fixed pseudo-random points, then keep the lowest negative log-likelihood.
    generator = np.random.default_rng(170817)
    starts = [published_x] + [[generator.uniform(0.005, 0.06), generator.uniform(0.15, 0.35), generator.uniform(2000, 6000),
                               generator.uniform(0.01, 0.09), generator.uniform(0.07, 0.3), generator.uniform(500, 3000),
                               generator.uniform(1, 15)] for _ in range(16)]
    optima = []
    for start in starts:
        x, scatter, residuals, jacobian = fit(two_component, start, [True] * 7)
        optima.append((negative_log_likelihood(residuals, scatter), x, scatter, residuals, jacobian))
    optima.sort(key=lambda item: item[0])
    distinct = []
    for item in optima:
        if all(abs(item[0] - other[0]) > 0.5 for other in distinct):
            distinct.append(item)
    _, x, scatter, residuals, jacobian = distinct[0]
    best_two = x
    second_mode = distinct[1][1] if len(distinct) > 1 else best_two
    covariance = covariance_from_jacobian(jacobian)
    errors = np.sqrt(np.diag(covariance))
    correlation = covariance / np.outer(errors, errors)
    results['two-component'] = summary('two-component', x, scatter, residuals, 7, two_component(x))
    results['two-component']['linearErrors'] = {key: round(float(value), 5) for key, value in zip(PARAMETER_NAMES, errors)}
    results['two-component']['atBounds'] = [key for key, value, low, high in zip(PARAMETER_NAMES, x, LOWER, UPPER) if abs(value - low) < 1e-3 * (high - low) or abs(value - high) < 1e-3 * (high - low)]
    results['two-component']['localOptima'] = [{'negativeLogLikelihood': round(item[0], 2), 'scatter': round(float(item[2]), 4),
                                                'parameters': {key: round(float(value), 4) for key, value in zip(PARAMETER_NAMES, item[1])},
                                                'starts': sum(1 for other in optima if abs(other[0] - item[0]) <= 0.5)} for item in distinct]
    results['two-component']['correlation'] = {
        'redMass-redVelocity': round(float(correlation[3, 4]), 3),
        'redMass-redOpacity': round(float(correlation[3, 6]), 3),
        'blueMass-blueVelocity': round(float(correlation[0, 1]), 3),
    }

    fixed = list(best_two)
    fixed[6] = 10.0
    x, scatter_red, residuals, _ = fit(two_component, fixed, [True] * 6 + [False])
    results['red-kappa-10'] = summary('red-kappa-10', x, scatter_red, residuals, 6, two_component(x))

    one = lambda values: [(values[3], values[4], values[6], values[5])]
    x, scatter_one, residuals, _ = fit(one, [0.0, 0.0, 0.0, 0.05, 0.2, 2500.0, 2.0], [False, False, False, True, True, True, True])
    results['one-component'] = summary('one-component', x, scatter_one, residuals, 4, one(x))

    floorless = list(best_two)
    floorless[2] = floorless[5] = 300.0
    x, scatter_floor, residuals, _ = fit(two_component, floorless, [True, True, False, True, True, False, True])
    results['no-floor'] = summary('no-floor', x, scatter_floor, residuals, 5, two_component(x))

    x, scatter_ebv, residuals, _ = fit(two_component, best_two, [True] * 7, ebv=INPUTS['extinction']['ebvSchlaflyFinkbeiner'])
    results['two-component-low-extinction'] = summary('two-component-low-extinction', x, scatter_ebv, residuals, 7, two_component(x))
    results['two-component-low-extinction']['note'] = 'Table 6 coefficients multiplied by the recalibrated E(B-V) = 0.1056 instead of E(B-V)_SFD; under-corrects extinction by 14%.'

    published_residuals = predicted_magnitudes(two_component(published_x)) - MAGNITUDES
    published_scatter = minimize_scalar(lambda value: negative_log_likelihood(published_residuals, value), bounds=(1e-3, 2.0), method='bounded').x
    results['villar-2017-printed-parameters'] = summary('villar-2017-printed-parameters', published_x, published_scatter, published_residuals, 0, two_component(published_x))

    printed_formula_failures = {
        'missingArnettPrefactor': 'Villar et al. eq. 3 prints the kernel t/td instead of 2t/td^2, so the printed integral has units of energy. It equals L times td/2; for the red component that is a factor %.2f with time in days and %.3g with time in seconds, so the result depends on the time unit chosen.' % (diffusion_time_days(best_two[3], best_two[4], best_two[6]) / 2, diffusion_time_days(best_two[3], best_two[4], best_two[6]) * 86400 / 2),
        'squaredStefanBoltzmann': 'With sigma_SB squared inside the fourth root (eqs. 4-5), the photosphere temperature is divided by sigma_SB^(1/4) = %.4f in CGS, so about 4000 K becomes %.0f K. The receded-radius branch of eq. 5 prints sigma_SB unsquared, so the two branches would not meet at T = Tc.' % (5.670374419e-5 ** 0.25, 4000 / 5.670374419e-5 ** 0.25),
    }

    return {
        'description': 'Fits of grey-opacity kilonova models to the fixed GW170817 photometry. Synthetic model output compared with real observations; no radiative transfer.',
        'software': {'python': platform.python_version(), 'numpy': np.__version__, 'scipy': scipy.__version__},
        'inputs': {'photometrySha256': INPUTS['photometry']['sha256'], 'rows': int(len(MAGNITUDES)), 'distanceMpc': INPUTS['distanceMpc'], 'ebvSfd': INPUTS['extinction']['ebvSfd']},
        'fits': results,
        'degeneracy': degeneracy_grid(best_two, second_mode, results['two-component']['scatter']),
        'printedFormulaFailures': printed_formula_failures,
    }


def compare(saved, fresh, path='root', tolerance=2e-3):
    if isinstance(saved, dict):
        for key in saved:
            if key == 'software':
                continue
            compare(saved[key], fresh[key], f'{path}.{key}', tolerance)
    elif isinstance(saved, list):
        assert len(saved) == len(fresh), path
        for index, (a, b) in enumerate(zip(saved, fresh)):
            compare(a, b, f'{path}[{index}]', tolerance)
    elif isinstance(saved, float):
        assert abs(saved - fresh) <= tolerance * max(1.0, abs(saved)), f'{path}: saved {saved}, recomputed {fresh}'
    else:
        assert saved == fresh, f'{path}: saved {saved!r}, recomputed {fresh!r}'


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--check', action='store_true')
    arguments = parser.parse_args()
    output = HERE / 'fit-outputs.json'
    result = run()
    if arguments.check:
        compare(json.loads(output.read_text()), json.loads(json.dumps(result)))
        print('fit-outputs.json reproduced within tolerance')
        return
    output.write_text(json.dumps(result, indent=1) + '\n')
    best = result['fits']['two-component']
    print(json.dumps({key: best[key] for key in ('parameters', 'scatter', 'rmsResidual', 'correlation')}, indent=1))


if __name__ == '__main__':
    sys.exit(main())
