"""Inspect the original full-batch program's first update, without altering it.

The selected pair's data-gradient contribution includes the 1/32 mean weight.
The actual step sums all 32 contributions plus the single global regularizer.
This is a numeric walkthrough, not a different single-pair SGD experiment.
"""
import json

import numpy as np

from bpr_and_topk import (
    LEARNING_RATE, REGULARIZATION, initialize, loss_and_gradient, training_triples,
)


def lists(values):
    return {key: value.tolist() for key, value in values.items()}


def main():
    old = initialize()
    triples = training_triples()
    objective, pair_loss, differences, full_gradient = loss_and_gradient(old, triples)
    user, positive, unobserved = map(int, triples[0])
    difference = float(differences[0])
    derivative = -float(np.exp(-np.logaddexp(0, difference)))
    coefficient = derivative / len(triples)
    contribution = {
        "user0": (coefficient * (old["items"][positive] - old["items"][unobserved])).tolist(),
        "item0": (coefficient * old["users"][user]).tolist(),
        "item2": (-coefficient * old["users"][user]).tolist(),
        "item_bias0": coefficient,
        "item_bias2": -coefficient,
    }
    new = {key: value - LEARNING_RATE * full_gradient[key] for key, value in old.items()}
    new_objective, new_pair_loss, new_differences, _ = loss_and_gradient(new, triples)
    assert len(triples) == 32
    assert sum(v.size for v in old.values()) == 26
    assert new_objective < objective
    print(json.dumps({
        "scope": "Static extraction of original seed7 parameters and its first full-batch update; not a new training run or single-pair SGD result.",
        "selected_triple": [user, positive, unobserved],
        "learning_rate": LEARNING_RATE,
        "triple_count": len(triples),
        "parameter_count": sum(v.size for v in old.values()),
        "regularization_coefficient_in_mean_objective": REGULARIZATION,
        "selected_pair": {
            "old_difference": difference,
            "raw_loss_derivative_wrt_difference": derivative,
            "mean_weighted_derivative": coefficient,
            "data_gradient_contribution_only": contribution,
            "actual_difference_after_full_update": float(new_differences[0]),
        },
        "old_parameters": lists(old),
        "full_gradient_all_pairs_plus_regularizer_once": lists(full_gradient),
        "new_parameters_after_one_original_full_step": lists(new),
        "objective_before_after": [objective, new_objective],
        "mean_pair_loss_before_after": [pair_loss, new_pair_loss],
        "limits": [
            "The pair contribution is not the full gradient for shared vectors.",
            "All parameters in each gradient are old values; they are updated simultaneously.",
            "The first-step change of this pair is observed here, not guaranteed for every pair at every step.",
            "The original 2000-update run and its historical output are not changed.",
        ],
    }, indent=2))


if __name__ == "__main__":
    main()
