"""Original sample-order diagnostic using a uniform seeded permutation without replacement; not DQN training or an Atari reproduction.
Run with Python 3.10+; standard library only. Writes results.json in the current directory.
"""
from random import Random

# Transition identity is retained so ordering cannot change the dataset.
buffer = [{"id": i, "regime": "A" if i < 6 else "B"}
          for i in range(12)]
sequential = list(buffer)
replay_order = Random(7).sample(buffer, len(buffer))

def adjacent_matches(transitions):
    return sum(left["regime"] == right["regime"]
               for left, right in zip(transitions, transitions[1:]))

sequential_matches = adjacent_matches(sequential)
replay_matches = adjacent_matches(replay_order)
assert sorted(t["id"] for t in replay_order) == list(range(12))
assert sum(t["regime"] == "A" for t in replay_order) == 6
assert sequential_matches == 10
assert replay_matches < sequential_matches
print(f"sequential same-regime pairs={sequential_matches}/11")
print(f"replay same-regime pairs={replay_matches}/11")
print("Both orders contain the same 12 transitions.")
expected_fraction = 5 / 11
assert 0 < expected_fraction < 1
print(f"expected shuffled same-regime fraction={expected_fraction:.3f}")

# Extended experiment: deterministic parameter sweep and invariants.
from itertools import combinations
from collections import Counter
histogram=Counter()
for a_positions in combinations(range(12),6):
    a_set=set(a_positions)
    labels=['A' if i in a_set else 'B' for i in range(12)]
    matches=sum(a==b for a,b in zip(labels,labels[1:]))
    histogram[matches]+=1
count=sum(histogram.values())
expected_matches=sum(k*v for k,v in histogram.items())/count
assert count==924 and abs(expected_matches-5)<1e-12
assert histogram[10]==2
composition=[]
for a_count in range(13):
    b_count=12-a_count
    fraction=(a_count*(a_count-1)+b_count*(b_count-1))/(12*11)
    composition.append(dict(regime_a=a_count,regime_b=b_count,expected_adjacent_fraction=fraction))
data=dict(exact_histogram=[dict(matches=k,count=histogram[k],probability=histogram[k]/count) for k in sorted(histogram)],
          all_balanced_label_orders=count,expected_matches=expected_matches,sequential_matches=10,
          seeded_matches=replay_matches,seeded_order=[t['regime'] for t in replay_order],
          composition_sweep=composition)
print(f"Exact balanced-buffer enumeration: {count} label orders; expected adjacent matches={expected_matches:.1f}/11")
print(f"Probability of matching the sequential extreme = 2/924 = {2/count:.6f}")

import json
from pathlib import Path
Path("results.json").write_text(json.dumps(data,indent=2,allow_nan=False)+"\n",encoding="utf-8")
