"""Independent bounded checks from the R5L definitions, without importing a producer.

Circuits are connected components of the graph whose vertices are support EDGES,
paired at their endpoints. Invariants sum over all eight labelled images. This
multiplies each distinct-support orbit sum by its fixed stabilizer size, hence
preserves signature equality. Inputs/results were known before this audit.
"""
from collections import Counter, defaultdict
from itertools import combinations
from pathlib import Path
import hashlib
import json


def require(value, message):
    if not value:
        raise RuntimeError(message)


def permutations(n):
    # Cartesian index i=x*n+y, independently defined reflections/transpose.
    ops = []
    for transpose in (False, True):
        for flip_x in (False, True):
            for flip_y in (False, True):
                mapping=[]
                for i in range(n*n):
                    x,y=divmod(i,n)
                    if transpose: x,y=y,x
                    if flip_x: x=n-1-x
                    if flip_y: y=n-1-y
                    mapping.append(x*n+y)
                ops.append(mapping)
    return ops


def images(mask, maps):
    bits=[i for i in range(len(maps[0])) if mask>>i&1]
    return tuple(sum(1<<p[i] for i in bits) for p in maps)


def feature_masks(n, maps):
    families=[]
    for degree in (1,2,3):
        reps=set()
        for subset in combinations(range(n*n), degree):
            orbit=[sum(1<<p[i] for i in subset) for p in maps]
            reps.add(min(orbit))
        families.append(sorted(reps))
    return families


def circuit_model(n):
    endpoints=[]
    incident=defaultdict(list)
    for row in range(n+1):
        for col in range(n+1):
            if (row+col)%2: continue
            vertices=[(row,col),(row,col+1),(row+1,col+1),(row+1,col)]
            square=(row,col)
            for a,b in zip(vertices,vertices[1:]+vertices[:1]):
                edge=len(endpoints)
                endpoints.append((a,b))
                incident[a].append((edge,b,square))
                incident[b].append((edge,a,square))
    fixed=[]
    variable=[]
    for point,halves in incident.items():
        if len(halves)==2:
            fixed.append((halves[0][0],halves[1][0]))
            continue
        require(len(halves)==4,'Invalid vertex valence')
        row,col=point
        bit=(row-1)*n+col-1
        closed=[]; opened=[]
        for j,a in enumerate(halves):
            for b in halves[j+1:]:
                if a[2]==b[2]: closed.append((a[0],b[0]))
                if a[1][0]+b[1][0]==2*row and a[1][1]+b[1][1]==2*col:
                    opened.append((a[0],b[0]))
        require(len(closed)==len(opened)==2,'Invalid gate pairing')
        variable.append((bit,closed,opened))
    require(len(endpoints)==2*n*n+4*n+4,'Support size')
    return len(endpoints),fixed,variable


def lengths(mask, model):
    size,fixed,variable=model
    parent=list(range(size))
    def root(i):
        while parent[i]!=i:
            parent[i]=parent[parent[i]]; i=parent[i]
        return i
    def union(a,b):
        ra,rb=root(a),root(b)
        if ra!=rb: parent[rb]=ra
    for a,b in fixed: union(a,b)
    for bit,closed,opened in variable:
        for a,b in (opened if mask>>bit&1 else closed): union(a,b)
    return sorted(Counter(root(i) for i in range(size)).values())


def census4():
    n=4; maps=permutations(n); feats=feature_masks(n,maps); model=circuit_model(n)
    require(list(map(len,feats))==[3,21,77],'Feature counts')
    by_degree=[defaultdict(list) for _ in range(3)]
    seen=set(); known_lengths={}
    for mask in range(1<<(n*n)):
        if mask in seen: continue
        eight=images(mask,maps)
        seen.update(eight)
        known_lengths[mask]=lengths(mask,model)
        signature=[]
        for d,masks in enumerate(feats):
            signature.extend(sum((image&card)==card for image in eight) for card in masks)
            by_degree[d][bytes(signature)].append(mask)
    summaries=[]
    for fibers in by_degree:
        mixed=[]
        mixed_count = 0
        for members in fibers.values():
            kinds={len(known_lengths[m])==1 for m in members}
            if len(kinds)>1: mixed.append(members)
            mixed_count += len({len(known_lengths[m]) for m in members}) > 1
        summaries.append({'fibers':len(fibers),'size_histogram':dict(sorted(Counter(map(len,fibers.values())).items())),
                          'mixed_monolinearity_fibers':len(mixed),
                          'mixed_circuit_count_fibers':mixed_count})
    collisions=[{'masks':[hex(m) for m in group],'circuit_lengths':[known_lengths[m] for m in group]}
                for group in by_degree[2].values() if len(group)>1]
    require(len(seen)==65536 and len(known_lengths)==8548,'Exhaustive N4 domain')
    require(summaries[2]['size_histogram']=={1:8544,2:2},'Cubic collision spectrum')
    require(summaries[1]['mixed_monolinearity_fibers']==2,'Quadratic mixed fibers')
    require(summaries[2]['mixed_monolinearity_fibers']==0,'Cubic mixed fibers')
    require(summaries[2]['mixed_circuit_count_fibers']==0,'N4 circuit count differs within a cubic fibre')
    require(all(group['circuit_lengths']==[[4,4,8,12,24]]*2 for group in collisions),
            'Unexpected N4 cubic collision circuit lengths')
    return {'states':len(seen),'orbits':len(known_lengths),'feature_counts':list(map(len,feats)),
            'degrees':summaries,'cubic_collisions':collisions}


DATA_PINS = {
    'seed_certificate.json': '397cd16bb5982c45c4b790f0e636fae148fbbf85587ef6c18b77e57a63450c80',
    'N6.json': '7f51f5c5783f40c7f7df728a00122f37228d9ece7e4a28b7a9977a8cbb4ad58a',
}


def load(name):
    raw = (Path(__file__).resolve().parent / name).read_bytes()
    require(hashlib.sha256(raw).hexdigest() == DATA_PINS[name], 'Input bytes differ: '+name)
    return json.loads(raw)


def mask_of(rows, n):
    require(len(rows) == n and all(len(row) == n and all(value in '01' for value in row)
                                 for row in rows), 'Invalid interior bit matrix')
    return sum(int(bit) << i for i, bit in enumerate(''.join(rows)))


def signature(mask, n, families):
    eight = images(mask, permutations(n))
    return tuple(tuple(sum((image & support) == support for image in eight) for support in family)
                 for family in families)


def trace(mask, n):
    # An explicit dart traversal, separate from the edge-component count.
    # The local transition comes from the active squares and the gate bits.
    adjacency = defaultdict(dict)
    for row in range(n + 1):
        for col in range(n + 1):
            if (row + col) % 2:
                continue
            cell = ((row,col), (row,col+1), (row+1,col+1), (row+1,col))
            for index, vertex in enumerate(cell):
                before, after = cell[index-1], cell[(index+1)%4]
                adjacency[vertex].update({before:after, after:before})

    unseen = {(a,b) for a, neighbours in adjacency.items() for b in neighbours}
    require(len(unseen) == 2*(2*n*n + 4*n + 4), 'Dart support size')
    words = []
    while unseen:
        start = min(unseen)
        a, b = start
        word = []
        while True:
            require((a,b) in unseen and (b,a) in unseen, 'Circuit repeats an edge')
            unseen.remove((a,b))
            unseen.remove((b,a))
            word.append((a,b))
            r, c = b
            opened = 1 <= r <= n and 1 <= c <= n and mask >> ((r-1)*n+c-1) & 1
            next_vertex = (2*r-a[0], 2*c-a[1]) if opened else adjacency[b][a]
            a, b = b, next_vertex
            if (a,b) == start:
                break
        words.append(word)
    return words


def canonical_vertices(vertices):
    vertices = tuple(map(tuple, vertices))
    require(bool(vertices), 'Empty circuit word')
    return min(branch[i:] + branch[:i] for branch in (vertices, vertices[::-1])
               for i in range(len(branch)))


def check_seeds(data):
    n = 4
    maps = permutations(n)
    families = feature_masks(n, maps)
    model = circuit_model(n)
    targets = data['targets']
    codes = ('ADFD', 'AFBD', 'AEF7', 'AF77')
    require(set(targets) == set(codes), 'R5L fixed seed identities')
    results = {}
    signatures = []
    for code, count in zip(codes, (1,3,1,3)):
        row = targets[code]
        matrix = row['matrix']
        require(len(matrix) == 6 and all(len(line) == 6 for line in matrix), 'R5L matrix shape')
        interior = [''.join(map(str, line[1:-1])) for line in matrix[1:-1]]
        mask = mask_of(interior, n)
        sig = signature(mask, n, families)
        signatures.append(sig)
        actual = trace(mask, n)
        actual_words = sorted(canonical_vertices([edge[0] for edge in word]) for word in actual)
        prior_words = sorted(canonical_vertices(circuit['vertices']) for circuit in row['circuits'])
        require(actual_words == prior_words, 'R5L seed circuit words differ: '+code)
        observed = sorted(map(len, actual))
        require(observed == sorted(row['circuit_lengths']) == lengths(mask, model) and
                len(observed) == row['circuit_count'] == count, 'R5L seed circuit lengths differ: '+code)
        occupied_counts = [sum(all(mask >> site & 1 for site in support)
                               for support in feature['support_orbit']) for feature in data['features']]
        require(len(occupied_counts) == 24 and occupied_counts == row['feature_values'],
                'Stored exact R5L seed observables differ: '+code)
        results[code] = {'interior':interior, 'circuit_lengths':observed}
    separators = []
    for a,b in ((0,1),(2,3)):
        require(signatures[a][:2] == signatures[b][:2], 'R5L pair quadratic signatures differ')
        separators.append({i for i,(x,y) in enumerate(zip(signatures[a][2], signatures[b][2])) if x != y})
    require(list(map(len,separators)) == [4,4] and separators[0].isdisjoint(separators[1]),
            'R5L atomic cubic separators differ')
    masks = [{families[2][index] for index in group} for group in separators]
    supports = [[[i//n+1,i%n+1] for i in range(n*n) if card >> i & 1]
                for group in masks for card in sorted(group)]
    return {'seeds':results, 'full_quadratic_pairs_equal':True, 'cubic_separators_each':[4,4],
            'common_atomic_cubic_separators':0, 'cubic_separating_supports': [supports[:4],supports[4:]]}


def check_n6(data):
    n = 6
    maps = permutations(n)
    a,b = (mask_of(rows, n) for rows in data['matrices'])
    require([hex(a),hex(b)] == data['masks_row_major_top_left_lsb'] == ['0xee556aef7','0xee5666ef7'],
            'N6 fixed masks')
    require(a.bit_count() == b.bit_count() == 24 and b not in images(a, maps), 'N6 occupancy and distinct orbits')
    families = feature_masks(n, maps)
    require(list(map(len,families)) == [6,93,920], 'N6 complete coordinate universe')
    require(signature(a,n,families) == signature(b,n,families), 'N6 full cubic signature')
    for degree, expected in enumerate(data['degree_summary'], 1):
        # Distinct-support convention, independently from the labelled-image sum.
        decks = []
        for mask in (a,b):
            occupied = [1 << i for i in range(n*n) if mask >> i & 1]
            decks.append(Counter(min(images(sum(support),maps)) for support in combinations(occupied,degree)))
        require(decks[0] == decks[1] and expected == {
            'degree':degree, 'coordinates':len(families[degree-1]),
            'nonzero_coordinates':len(decks[0]), 'total_multiplicity':sum(decks[0].values()),
        }, 'N6 distinct-support signature')
    words = [trace(mask,n) for mask in (a,b)]
    require(json.loads(json.dumps(words)) == data['words'], 'N6 complete words differ')
    observed = [sorted(map(len,word)) for word in words]
    require(observed == [lengths(mask,circuit_model(n)) for mask in (a,b)] ==
            data['lengths'] == [[100],[24,36,40]], 'N6 circuit lengths')
    card = data['quartic_separator']['support']
    require(card == [[1,3],[2,2],[2,5],[3,4]], 'N6 prescribed quartic support differs')
    card_mask = sum(1 << ((r-1)*n+c-1) for r,c in card)
    octet = set(images(card_mask,maps))
    counts = [sum(mask & support == support for support in octet) for mask in (a,b)]
    require(counts == data['quartic_separator']['counts'] == [1,0], 'N6 quartic separator')
    return {'masks':[hex(a),hex(b)], 'full_cubic_equal':True, 'distinct_d4_orbits':True,
            'degree_summary':data['degree_summary'], 'circuit_lengths':observed,
            'quartic_separator':{'support':card, 'counts':counts}}


def reject(fn, message):
    try:
        fn()
    except RuntimeError as exc:
        require(str(exc).startswith(message), 'Mutation rejected for an unintended reason')
    else:
        raise RuntimeError('Invalid input accepted: '+message)


def main():
    seeds, n6 = load('seed_certificate.json'), load('N6.json')
    output = {'status':'PASS','scope':'R5L four seeds, N4 exhaustive D4 fibres, N6 one fixed pair',
              'input_sha256':DATA_PINS, 'R5L':check_seeds(seeds), 'N4':census4(), 'N6':check_n6(n6)}
    seeds['targets']['ADFD']['circuits'][0]['vertices'][0][0] += 1
    n6['quartic_separator']['counts'][1] = 1
    reject(lambda:check_seeds(seeds), 'R5L seed circuit words differ')
    reject(lambda:check_n6(n6), 'N6 quartic separator')
    output['negative_controls'] = ['R5L changed seed circuit vertex rejected', 'N6 changed separator count rejected']
    print(json.dumps(output, indent=2, sort_keys=True))


if __name__ == '__main__':
    main()

