# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check regeneration and show that representative porting mistakes fail."""

import math
import sys
from functools import partial
from itertools import permutations
from pathlib import Path
from types import SimpleNamespace

ROOT = Path(__file__).parents[1]
sys.path.insert(0, str(ROOT / "reference"))
sys.path.insert(0, str(ROOT / "checks"))
import nmfk
import check_port
import make_cases


def update_h(v, w, h, *, kl):
    estimate = nmfk._matmul(w, h)
    if kl:
        ratio = [
            [x / (y + 1e-15) for x, y in zip(row, fitted, strict=True)]
            for row, fitted in zip(v, estimate, strict=True)
        ]
        sums = [math.fsum(column) for column in nmfk._transpose(w)]
        numerator = nmfk._matmul(nmfk._transpose(w), ratio)
        denominator = [[s] * len(h[0]) for s in sums]
    else:
        numerator = nmfk._matmul(nmfk._transpose(w), v)
        denominator = nmfk._matmul(nmfk._transpose(w), estimate)
    return [
        [value * n / (d + 1e-15) for value, n, d in zip(row, num, den, strict=True)]
        for row, num, den in zip(h, numerator, denominator, strict=True)
    ]


def update_w(v, w, h, *, kl):
    transpose = nmfk._transpose
    return transpose(update_h(transpose(v), transpose(h), transpose(w), kl=kl))


def alternate_step(v, w, h, *, w_first=False, rescale=True, kl=False):
    if w_first:
        w = update_w(v, w, h, kl=kl)
        h = update_h(v, w, h, kl=kl)
    else:
        h = update_h(v, w, h, kl=kl)
        w = update_w(v, w, h, kl=kl)
    if rescale:
        nmfk._normalize_columns(w, h)
    return [w, h]


def greedy_clustering(run_bases):
    clusters = [[basis] for basis in run_bases[0]]
    assignments = [list(range(len(clusters)))]
    for run in run_bases[1:]:
        centroids = [nmfk._mean(cluster) for cluster in clusters]
        row = [-1] * len(clusters)
        for basis_index, basis in enumerate(run):
            closest = min(range(len(clusters)), key=lambda i: nmfk._cosine_distance(centroids[i], basis))
            clusters[closest].append(basis)
            row[closest] = basis_index
        assignments.append(row)
    return [clusters, assignments]


def frozen_centroid_clustering(run_bases):
    first_run = run_bases[0]
    clusters = [[basis] for basis in first_run]
    assignments = [list(range(len(first_run)))]
    for run in run_bases[1:]:
        row = list(nmfk._assignment(first_run, run))
        assignments.append(row)
        for cluster, index in zip(clusters, row, strict=True):
            cluster.append(run[index])
    return [clusters, assignments]


def inverse_assignment_layout(run_bases):
    clusters, assignments = nmfk.equal_size_cluster(run_bases)
    return [clusters, [[row.index(i) for i in range(len(row))] for row in assignments]]


def last_assignment_tie(run_bases):
    first, second = run_bases
    assignment = min(
        reversed(list(permutations(range(len(second))))),
        key=lambda order: sum(nmfk._cosine_distance(a, second[j]) for a, j in zip(first, order, strict=True)),
    )
    return [[[a, second[j]] for a, j in zip(first, assignment, strict=True)],
            [list(range(len(first))), list(assignment)]]


def alternate_silhouette(clusters, *, distance, pool_other_clusters=False):
    if len(clusters) == 1:
        return 1.0
    scores = []
    for cluster_index, cluster in enumerate(clusters):
        other_clusters = [other for j, other in enumerate(clusters) if j != cluster_index]
        if pool_other_clusters:
            other_clusters = [[point for other in other_clusters for point in other]]
        for i, point in enumerate(cluster):
            others = [p for j, p in enumerate(cluster) if i != j]
            a = math.fsum(distance(point, p) for p in others) / len(others) if others else 0.0
            b = min(
                math.fsum(distance(point, p) for p in other) / len(other)
                for other in other_clusters
            )
            scores.append((b - a) / max(a, b) if max(a, b) else 0.0)
    return math.fsum(scores) / len(scores)


def shifted_correlation(a, b, max_shift, *, circular=False, centered=True, prefer_positive=False):
    def score(shift):
        if circular:
            left = a
            right = [b[(i + shift) % len(b)] for i in range(len(a))]
        else:
            indices = range(max(0, -shift), min(len(a), len(b) - shift))
            left = [a[i] for i in indices]
            right = [b[i + shift] for i in indices]
        return nmfk._pearson(left, right) if centered else 1 - nmfk._cosine_distance(left, right)

    shift, corr = max(
        ((s, score(s)) for s in range(-max_shift, max_shift + 1)),
        key=lambda pair: (pair[1], -abs(pair[0]), pair[0] if prefer_positive else -pair[0]),
    )
    return [shift, corr]


def nonfinite_update(v, w, h):
    updated_w, updated_h = nmfk.multiplicative_step(v, w, h)
    updated_h[-1][-1] = float("nan")
    return [updated_w, updated_h]


def verify_regeneration():
    stored = check_port.load_cases()
    generated = make_cases.generate()
    assert {k: v for k, v in stored.items() if k != "cases"} == {
        k: v for k, v in generated.items() if k != "cases"
    }
    for saved, actual in zip(stored["cases"], generated["cases"], strict=True):
        assert {k: v for k, v in saved.items() if k != "expected"} == {
            k: v for k, v in actual.items() if k != "expected"
        }
        diff = check_port._diff(actual["expected"], saved["expected"])
        assert math.isfinite(diff) and diff <= saved["tol"], (saved["name"], diff, saved["tol"])
    assert check_port.run_checks(nmfk, out=lambda *_: None) == 0
    return {case["name"]: case for case in stored["cases"]}


def verify_broken_ports(cases):
    mutants = [
        ("W before H", "Frobenius update on positive mixed data", partial(alternate_step, w_first=True)),
        ("omitted column rescaling", "Frobenius update on positive mixed data", partial(alternate_step, rescale=False)),
        ("KL updates", "Frobenius update on positive mixed data", partial(alternate_step, kl=True)),
        ("nonfinite update output", "Frobenius update on positive mixed data", nonfinite_update),
        ("squared relative error", "nonzero relative reconstruction error",
         lambda v, w, h: nmfk.relative_reconstruction_error(v, w, h) ** 2),
        ("unnormalized error", "nonzero relative reconstruction error",
         lambda v, w, h: nmfk.relative_reconstruction_error(v, w, h) * nmfk._frobenius(v)),
        ("greedy unconstrained clustering", "one-to-one assignment across three runs", greedy_clustering),
        ("frozen first-run centroids", "fourth run uses updated centroids", frozen_centroid_clustering),
        ("inverted assignment layout", "one-to-one assignment across three runs", inverse_assignment_layout),
        ("last assignment on a tie", "lexicographic assignment tie", last_assignment_tie),
        ("Euclidean silhouette", "cosine silhouette on imperfect clusters",
         partial(alternate_silhouette, distance=math.dist)),
        ("pooled distance to other clusters", "silhouette uses the nearest of three clusters",
         partial(alternate_silhouette, distance=nmfk._cosine_distance, pool_other_clusters=True)),
        ("singleton silhouette forced to zero", "singleton uses zero within-cluster distance",
         lambda clusters: nmfk.silhouette_score(clusters) - sum(len(c) == 1 for c in clusters)
         / sum(map(len, clusters))),
        ("uncentered cosine", "centered correlation on overlapping slices", partial(shifted_correlation, centered=False)),
        ("circular shifts", "centered correlation on overlapping slices", partial(shifted_correlation, circular=True)),
        ("reversed shift sign", "positive one-bin shift",
         lambda a, b, limit: nmfk.best_shift_correlation(b, a, limit)),
        ("positive shift on a sign tie", "shift tie favors smaller signed shift",
         partial(shifted_correlation, prefer_positive=True)),
    ]
    operations = {case["operation"] for case in cases.values()}
    reference = {operation: getattr(nmfk, operation) for operation in operations}
    for name, case_name, broken in mutants:
        case = cases[case_name]
        # A wrong numerical result or shape must trigger the failure.
        result = broken(*case["args"])
        assert check_port._diff(result, case["expected"]) > case["tol"], (name, case_name)
        port = SimpleNamespace(**(reference | {case["operation"]: broken}))
        lines = []
        assert check_port.run_checks(port, out=lines.append) > 0, name
        assert any(line.startswith(f"FAIL case {case_name} (") for line in lines), name
        print(f"PASS {case_name} rejects {name}")
    return len(mutants)


if __name__ == "__main__":
    cases = verify_regeneration()
    print(f"PASS all {len(cases)} portable cases regenerate within tolerance and accept the reference")
    print(f"PASS rejected {verify_broken_ports(cases)} broken ports")
