#!/usr/bin/env python3
"""Deterministic LIME-style neighborhood and weighted-surrogate toy."""

from __future__ import annotations

import math


QUERY = (1.0, 1.0)  # two interpretable word-presence indicators
WORDS = ("bright", "repair")
SIGMA = 0.5


def black_box(z: tuple[float, float]) -> float:
    """Hand-specified nonlinear score, not a fitted classifier."""
    z1, z2 = z
    return 0.10 + 0.45 * z1 + 0.25 * z2 + 0.10 * z1 * z2


def cosine_distance(query: tuple[float, float], z: tuple[float, float]) -> float:
    """Cosine distance; define an all-zero neighbor's distance as 1."""
    q_norm = math.sqrt(sum(value * value for value in query))
    z_norm = math.sqrt(sum(value * value for value in z))
    if z_norm == 0.0:
        return 1.0
    cosine = sum(a * b for a, b in zip(query, z)) / (q_norm * z_norm)
    return 1.0 - cosine


def solve_linear_system(matrix: list[list[float]], vector: list[float]) -> list[float]:
    """Solve a small square system with Gaussian elimination and pivoting."""
    size = len(vector)
    augmented = [row[:] + [vector[i]] for i, row in enumerate(matrix)]
    for column in range(size):
        pivot = max(range(column, size), key=lambda row: abs(augmented[row][column]))
        if abs(augmented[pivot][column]) < 1e-12:
            raise ValueError("weighted design matrix is rank deficient")
        augmented[column], augmented[pivot] = augmented[pivot], augmented[column]
        scale = augmented[column][column]
        augmented[column] = [value / scale for value in augmented[column]]
        for row in range(size):
            if row == column:
                continue
            factor = augmented[row][column]
            augmented[row] = [
                a - factor * b for a, b in zip(augmented[row], augmented[column])
            ]
    return [augmented[row][-1] for row in range(size)]


def main() -> None:
    # Enumerate every subset of the two present words: no random sampling.
    neighbors = [(1.0, 1.0), (1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]
    rows = []
    for z in neighbors:
        distance = cosine_distance(QUERY, z)
        weight = math.exp(-(distance * distance) / (SIGMA * SIGMA))
        rows.append((z, distance, weight, black_box(z)))

    # g(z') = beta0 + beta1*z1 + beta2*z2, fit by locality-weighted OLS.
    # This deliberately omits LIME's K-Lasso feature selection/sparsity step.
    design = [[1.0, z[0], z[1]] for z, _, _, _ in rows]
    targets = [prediction for _, _, _, prediction in rows]
    weights = [weight for _, _, weight, _ in rows]
    normal = [
        [sum(w * row[i] * row[j] for w, row in zip(weights, design)) for j in range(3)]
        for i in range(3)
    ]
    rhs = [
        sum(w * row[i] * y for w, row, y in zip(weights, design, targets))
        for i in range(3)
    ]
    beta = solve_linear_system(normal, rhs)

    residual = max(
        abs(sum(normal[i][j] * beta[j] for j in range(3)) - rhs[i])
        for i in range(3)
    )
    assert residual < 1e-10
    local_prediction = sum(beta[j] * [1.0, QUERY[0], QUERY[1]][j] for j in range(3))
    weighted_sse = sum(
        w * (y - sum(b * feature for b, feature in zip(beta, row))) ** 2
        for w, y, row in zip(weights, targets, design)
    )

    print("scope=hand-specified black box; deterministic exhaustive 2-word neighborhood")
    print(f"query_interpretable={QUERY}; words={WORDS}; sigma={SIGMA}")
    print("neighbor z1 z2 cosine_distance locality_weight black_box_score")
    for z, distance, weight, prediction in rows:
        print(f"{int(z[0])} {int(z[1])} {distance:.6f} {weight:.6f} {prediction:.6f}")
    print(f"surrogate=intercept + b1*{WORDS[0]} + b2*{WORDS[1]}")
    print(f"intercept={beta[0]:.6f}; b_{WORDS[0]}={beta[1]:.6f}; b_{WORDS[1]}={beta[2]:.6f}")
    print(f"black_box_at_query={black_box(QUERY):.6f}")
    print(f"surrogate_at_query={local_prediction:.6f}")
    print(f"weighted_squared_error={weighted_sse:.6f}")
    print(f"normal_equation_max_residual={residual:.3e}")
    print("limit=no trained model, corpus, randomized LIME sampling, feature selection, or stability study")


if __name__ == "__main__":
    main()
