"""Retrospective LP2 intact-word permutation audit. Run beside the master text."""
from collections import Counter, defaultdict
from hashlib import sha256
from pathlib import Path
import json

import numpy as np

from lexical_words import tokenize_words
from lp_core import lp, pages
from word_core import replace_values

ROOT = Path(__file__).resolve().parent
RUNS = 9999
SCOPES = (("section_length", 1073301), ("section_start_page_length", 1073302))
SOURCE = "%".join(lp[:56])


def geometry(words):
    wtext = [tuple(w["values"]) for w in words]
    vocab = sorted(set(wtext))
    index = {w: i for i, w in enumerate(vocab)}
    ids = np.array([index[w] for w in wtext], dtype=np.int32)
    first = np.array([w[0] for w in vocab])
    last = np.array([w[-1] for w in vocab])
    joins = np.array([i for i, (x, y) in enumerate(zip(words, words[1:]))
                      if x["section"] == y["section"]])
    pairs = np.array([i for i in joins
                      if words[i]["paragraph"] == words[i+1]["paragraph"]
                      and len(wtext[i])+len(wtext[i+1]) >= 6])
    inside = sum(a == b for w in wtext for a, b in zip(w, w[1:]))
    return ids, first, last, joins, pairs, inside, len(vocab)


def partition(words, scope):
    pools = defaultdict(list)
    groups = []
    for i, w in enumerate(words):
        label = (w["section"], len(w["values"]))
        if scope == "section_start_page_length":
            label = (*label, w["page"])
        pools[label].append(i)
        groups.append(label)
    return pools, groups


def exact_join_mean(info, pools, groups):
    ids, first, last, joins, *_ = info
    # Account for draws without replacement when two slots have the same label.
    ends, starts, same = {}, {}, {}
    for label, idx in pools.items():
        a, b = last[ids[idx]], first[ids[idx]]
        ends[label] = np.bincount(a, minlength=29)
        starts[label] = np.bincount(b, minlength=29)
        same[label] = int(np.sum(a == b))
    expected = 0.0
    for i in joins:
        a, b = groups[i], groups[i+1]
        numer = int(ends[a] @ starts[b])
        denom = len(pools[a])*len(pools[b])
        if a == b:
            numer -= same[a]
            denom -= len(pools[a])
        expected += numer/denom
    return expected


def known_controls():
    records = json.loads((ROOT/"mechanism_coverage_results.json").read_text())["known_method_groups"]
    plain = {g["name"]: g["values"] for g in json.loads(
        (ROOT/"increment_calibration_sources.json").read_text())["groups"]}
    result = {}
    for g in records:
        name = g["name"]
        cipher = "%".join(pages[i] for i in g["parsed_page_indices"])
        rows = {}
        for label, source in (("cipher", cipher), ("plain", replace_values(cipher, plain[name]))):
            words = tokenize_words(source)
            info = geometry(words)
            ids, first, last, joins, _, inside, _ = info
            rows[label] = {
                "joins": len(joins),
                "inside_word_repeats": inside,
                "observed_joined_repeats": int(np.sum(last[ids[joins]] == first[ids[joins+1]])),
                "exact_join_expectations": {scope: exact_join_mean(info, *partition(words, scope))
                                            for scope, _ in SCOPES}
            }
        assert rows["cipher"]["joins"] == rows["plain"]["joins"]
        result[name] = rows
    return result


def known_phrase_local(words, info, positions):
    ids, _, _, _, pairs, *_ = info
    out = {}
    for scope, _ in SCOPES:
        pools, groups = partition(words, scope)
        details = []
        assert groups[positions[0]] != groups[positions[1]]
        product = 1.0
        for i in positions:
            assert groups[i] == groups[i+1]
            pool = pools[groups[i]]
            n = len(pool)
            assert list(ids[pool]).count(ids[i]) == list(ids[pool]).count(ids[i+1]) == 1
            assert ids[i] != ids[i+1]
            idx = set(pool)
            eligible = sum(j in idx and j+1 in idx for j in pairs)
            product *= eligible/(n*(n-1))
            details.append({"pool_slots": n, "eligible_ordered_joins": eligible})
        out[scope] = {"placement_probability": product, "pools": details}
    return out


def test_permutations(words, info, scope, seed, n):
    ids, first, last, joins, pairs, _, n_vocab = info
    pools, groups = partition(words, scope)
    rng = np.random.default_rng(seed)
    expected = exact_join_mean(info, pools, groups)
    phrase_count = 0
    join_hist = Counter()
    preserved = False
    # The code for one ordered word pair is injective, even across different word lengths.
    for start in range(0, n, 128):
        shape = min(128, n-start), len(ids)
        variants = np.broadcast_to(ids, shape).copy()
        for idx in pools.values():
            if len(idx) > 1:
                variants[:, idx] = rng.permuted(variants[:, idx], axis=1)
        if not preserved:
            assert all(np.all(np.sort(variants[:, idx], axis=1) == np.sort(ids[idx]))
                       for idx in pools.values())
            preserved = True
        p = np.sort(variants[:, pairs]*n_vocab + variants[:, pairs+1], axis=1)
        phrase_count += int(np.any(p[:, 1:] == p[:, :-1], axis=1).sum())
        counts = np.sum(last[variants[:, joins]] == first[variants[:, joins+1]], axis=1)
        join_hist.update(map(int, counts))
    assert sum(join_hist.values()) == n
    observed = int(np.sum(last[ids[joins]] == first[ids[joins+1]]))
    join_mean = sum(k*v for k,v in join_hist.items()) / n
    expanded = np.repeat(list(join_hist), list(join_hist.values()))
    return {
        "seed": seed, "runs": n, "pools": len(pools),
        "movable_slots": sum(len(idx) for idx in pools.values() if len(set(ids[idx])) > 1),
        "runs_with_colliding_pair": phrase_count,
        "joined_repeats_exact_mean": expected, "joined_repeats_simulated_mean": join_mean,
        "joined_repeats_central_95pct": np.quantile(expanded, [.025,.975]).tolist(),
        "runs_with_no_more_joined_repeats_than_observed": sum(v for k,v in join_hist.items() if k<=observed),
        "joined_repeats_histogram": dict(sorted(join_hist.items())),
    }


def main():
    words = tokenize_words(SOURCE)
    info = geometry(words)
    ids, first, last, joins, pairs, inside, _ = info
    hit = defaultdict(list)
    for i in pairs:
        hit[tuple(ids[i:i+2])].append(int(i))
    collisions = [[{"lp2_page": words[j]["page"], "page_rune_offset": words[j]["page_rune_offset"],
                    "section": words[j]["section"]} for j in idx]
                  for idx in hit.values() if len(idx)>1]
    assert len(words) == 2896 and len(pairs) == 2484
    assert collisions == [[{"lp2_page": 27, "page_rune_offset": 28, "section": 6},
                           {"lp2_page": 55, "page_rune_offset": 70, "section": 8}]]
    joined = int(np.sum(last[ids[joins]] == first[ids[joins+1]]))
    assert inside + joined == 86
    result = {
        "source_sha256": sha256((ROOT/"liber-primus__transcription--master.txt").read_bytes()).hexdigest(),
        "words": len(words), "words_within_section_joins": len(joins),
        "eligible_phrase_windows": len(pairs), "colliding_phrase_locations": collisions,
        "observed_inside_word_repeats": inside, "observed_at_word_join_repeats": joined,
    }
    result["known_phrase_local_diagnostic"] = known_phrase_local(
        words, info, next(idx for idx in hit.values() if len(idx)>1))
    result["known_solved_groups"] = known_controls()
    result["nulls"] = {name: test_permutations(words, info, name, seed, RUNS) for name,seed in SCOPES}
    (ROOT/"lp_word_inventory_audit.json").write_text(json.dumps(result, indent=2)+"\n")
    for name,row in result["nulls"].items():
        print(name, {k:v for k,v in row.items() if k != "joined_repeats_histogram"}, flush=True)


if __name__ == "__main__":
    main()
