"""Replay: python -B equivalent_313.py EVIDENCE_DIR OUTPUT.json"""
import gzip, hashlib, itertools, json, sys
from pathlib import Path

def main(d):
    sys.path.insert(0,str(d))
    from lexicon_293 import gp, LET
    from graph_304 import test
    from shortkey_303 import inp
    raw=(d/'lexicon_293_slice.json.gz').read_bytes()
    words=json.loads(gzip.decompress(raw))['length3']
    lex={gp(w) for w in words if gp(w)[0]==gp(w)[2]!=gp(w)[1]}
    assert len(lex)==51
    def edge(w): return w[:2]
    def reciprocal(E):
        return sorted((a,b) for a,b in E if a<b and (b,a) in E)
    def labels(w): return ' '.join(LET[i] for i in w)
    def swap(pairs):
        key=list(range(29))
        for a,b in pairs:
            a,b=LET.index(a),LET.index(b)
            key[a],key[b]=key[b],key[a]
        return tuple(key)
    def apply(key,w):return tuple(key[i] for i in w)
    def inv(key):return tuple(key.index(i) for i in range(29))
    def en(keys,readings,cut):
        assert all(sorted(k)==list(range(29)) for k in keys)
        return [apply(inv(keys[i>=cut]),gp(w)) for i,w in enumerate(readings)]
    k1=swap([('A','F'),('G','N'),('H','R')]); s=swap([('G','H')])
    k2=apply(s,k1)
    fixed='aha aga gag hah aha aga'.split()
    changed='aha aga gag gag aga aha'.split()
    hidden=gp('hah')
    assert hidden not in lex and all(gp(w) in lex for w in changed)
    ct=en([k1,k1],fixed,3)
    assert ct==en([k1,k2],changed,3)
    assert [labels(w) for w in ct]==['F R F','F N F','N F N','R F R','F R F','F N F']
    assert all(apply(k1,w)==gp(p) for w,p in zip(ct,fixed))
    assert all(apply(k2 if i>=3 else k1,w)==gp(changed[i]) for i,w in enumerate(ct))
    def maps(ww,dictionary):
        # Exhaust every injection of the observed symbols into all 29 values.
        # Each partial injection extends to at least one full permutation.
        v=sorted({a for w in ww for a in w})
        pairs={(v.index(a),v.index(b)) for a,b,_ in ww}
        edges={edge(w) for w in dictionary}
        return sum(all((p[i],p[j]) in edges for i,j in pairs)
                   for p in itertools.permutations(range(29),len(v)))
    def test_cuts(dictionary):
        E={edge(w) for w in dictionary}
        def result(words):
            count=maps(words,dictionary); check=test({edge(w) for w in words},E)
            assert check['status']==('yes' if count else 'no')
            return count
        rows=[dict(after=i,left=result(ct[:i]),right=result(ct[i:])) for i in range(1,len(ct))]
        return dict(pooled=result(ct),cut_counts=rows,
                    successful_cuts=[r['after'] for r in rows if r['left'] and r['right']])
    E={edge(w) for w in lex}; augmented=lex|{hidden}
    pooled=test_cuts(lex); repaired=test_cuts(augmented)
    assert pooled['pooled']==0 and pooled['successful_cuts']==[3]
    assert repaired['pooled']>0 and len(repaired['successful_cuts'])==5
    erows,_,_,_=inp(d)
    actual={edge(row[-1]) for row in erows}
    assert not reciprocal(actual) and len(actual)==30
    actual_check=test(actual,{edge(w) for w in augmented})
    assert actual_check['status']=='no'
    def reciprocals(es):return [labels(p) for p in reciprocal(es)]
    assert reciprocals(E)==['G A']
    return dict(
      description='Constructed word panels; no manuscript decryption. Keys map ciphertext rune to plaintext rune.',
      archived_slice_sha256=hashlib.sha256(raw).hexdigest(), alphabet=LET, dictionary_edges=len(E),
      source_for_missing_form='https://dictionary.cambridge.org/dictionary/english/hah',
      missing='hah',unchanged_plaintext=fixed,changed_plaintext=changed,ciphertext=[labels(w) for w in ct],
      key_before=list(k1),unchanged_key_after=list(k1),changed_key_after=list(k2),
      changed_cipher_inputs=[LET[i] for i in range(29) if k1[i]!=k2[i]],
      reciprocal_pairs_reference=reciprocals(E),reciprocal_pairs_panel=reciprocals({edge(w) for w in ct}),
      original_reference=pooled,with_hah=repaired,
      actual_manuscript=dict(distinct_forms=len(actual),reciprocal_pairs=reciprocals(actual),
                       pooled_with_hah=actual_check['status'],degree_only_hall=actual_check['initial_hall']))
if __name__=='__main__':
    r=main(Path(sys.argv[1]).resolve())
    Path(sys.argv[2]).write_text(json.dumps(r,sort_keys=True,indent=2)+'\n')
