"""Parameter transforms and normalized timing likelihood with explicit priors."""

import math
from chopping_model import predict


def physical(state):
    return [math.exp(state[0]), math.exp(state[1]), *state[2:8], math.exp(state[8])]


def log_probability(state, records, grid, chopping, eccentricity_scale):
    if not (
        math.log(0.05) < state[0] < math.log(60)
        and math.log(5) < state[1] < math.log(600)
        and abs(state[2]) < 0.15
        and abs(state[3]) < 0.15
        and 1634.5 < state[4] < 1636.8
        and 1698.5 < state[5] < 1699.5
        and 65.9 < state[6] < 66.2
        and 125.7 < state[7] < 126.0
        and math.log(1e-5) < state[8] < math.log(0.2)
    ):
        return -math.inf
    parameters = physical(state)
    try:
        times = predict(parameters, records, grid, chopping)
    except ValueError:
        return -math.inf
    jitter = parameters[8]
    likelihood = 0
    for row, model in zip(records, times):
        variance = row["sigma_days"] ** 2 + jitter * jitter
        likelihood -= 0.5 * (
            (row["observed_reduced_bjd"] - model) ** 2 / variance
            + math.log(2 * math.pi * variance)
        )
    prior = -(state[2] ** 2 + state[3] ** 2) / (2 * eccentricity_scale**2)
    prior -= 0.5 * (jitter / (30 / 1440)) ** 2
    return likelihood + prior + state[0] + state[1] + state[8]
