"""An original, standard-library-only training experiment for Starsea Notes.

Run: python model-step.py
The finite-difference check is independent of the analytic gradient formula.
"""
from math import isclose


def forward(x, y, w, b):
    prediction = w * x + b
    error = prediction - y
    return prediction, error, 0.5 * error ** 2


def gradients(x, y, w, b):
    _, error, _ = forward(x, y, w, b)
    return error * x, error


def update(x, y, w, b, rate):
    # Both gradients use the SAME, old parameter values.
    dw, db = gradients(x, y, w, b)
    return w - rate * dw, b - rate * db


def check_gradients():
    epsilon = 1e-6
    # Positive, negative and zero inputs catch sign and path mistakes.
    for x, y, w, b in [(2, 5, 3, 1), (-2, 1, 0.7, -0.3), (0, 5, 3, 1)]:
        dw, db = gradients(x, y, w, b)
        numeric_w = (forward(x, y, w + epsilon, b)[2]
                     - forward(x, y, w - epsilon, b)[2]) / (2 * epsilon)
        numeric_b = (forward(x, y, w, b + epsilon)[2]
                     - forward(x, y, w, b - epsilon)[2]) / (2 * epsilon)
        assert isclose(dw, numeric_w, rel_tol=1e-6, abs_tol=1e-7)
        assert isclose(db, numeric_b, rel_tol=1e-6, abs_tol=1e-7)


def fit_three_points():
    samples = [(0.0, 1.0), (1.0, 3.0), (2.0, 5.0)]
    w, b, rate = 0.0, 0.0, 0.1
    for _ in range(600):
        # Our batch loss is the MEAN of 0.5 * error**2.
        batch = [gradients(x, y, w, b) for x, y in samples]
        dw = sum(pair[0] for pair in batch) / len(samples)
        db = sum(pair[1] for pair in batch) / len(samples)
        w, b = w - rate * dw, b - rate * db
    assert isclose(w, 2.0, abs_tol=1e-6)
    assert isclose(b, 1.0, abs_tol=1e-6)
    return w, b


def main():
    x, y, w, b = 2.0, 5.0, 3.0, 1.0
    prediction, _, loss = forward(x, y, w, b)
    assert prediction == 7 and loss == 2
    print(f'forward: prediction={prediction:.4f} loss={loss:.4f}')
    check_gradients()
    dw, db = gradients(x, y, w, b)
    assert dw == 4 and db == 2
    print(f'gradient: dw={dw:.4f} db={db:.4f} (finite difference checked)')
    for rate, expected_loss in [(0.1, 0.5), (0.2, 0.0), (0.5, 4.5)]:
        new_w, new_b = update(x, y, w, b, rate)
        prediction, _, loss = forward(x, y, new_w, new_b)
        assert isclose(loss, expected_loss, abs_tol=1e-10)
        print(f'eta={rate}: prediction={prediction:.4f} loss={loss:.4f}')
    new_w, new_b = update(0, 5, 3, 1, 0.1)
    assert new_w == 3 and isclose(new_b, 1.4)  # zero input, zero weight gradient
    w, b = fit_three_points()
    print(f'batch: w={w:.4f} b={b:.4f} prediction(x=3)={3*w+b:.4f}')
    # Exact fitting of these synthetic points does not prove real-world generalization.
    print('All checks passed.')


if __name__ == '__main__':
    main()
