"""Show two distinct anchor outputs satisfying the same 81-word conditions.

Only replay saved witnesses; no SAT solver or additional search.
"""
from pathlib import Path
import hashlib
import json

ROOT=Path(__file__).resolve().parent
READ=lambda name:json.loads((ROOT/name).read_text())
SHA=lambda name:hashlib.sha256((ROOT/name).read_bytes()).hexdigest()


def audit():
    data=READ('independent_phrase_inputs.json');results=READ('independent_phrase_results.json')
    query=next(q for q in data['queries'] if q['id']=='AIO_prior_red_exemptions')
    originals={q['id']:q for q in data['queries']}
    assert query['constraint_count']==81 and len(query['couplings'])==6
    rows=[]
    for result in results['rows']:
        assert result['status']=='sat';source=originals[result['id']]
        assert [s['cipher'] for s in source['sections']]==[s['cipher'] for s in query['sections']]
        decoded={};total=0
        for section,path in zip(query['sections'],result['capacity_witness']['sections']):
            assert section['id']==path['section'] and path['initial_phase']==0
            key=path['key'];assert len(key)==13 and all(type(k)==int and 0<=k<29 for k in key)
            skip=set(path['skipped_F_offsets']);assert len(skip)==len(path['skipped_F_offsets'])
            assert all(0<=p<len(section['cipher']) and section['cipher'][p]==0 for p in skip)
            phase=0;output=[];encoded=[]
            for i,cipher in enumerate(section['cipher']):
                if i in skip:value=0;encoded.append(value)
                else:
                    value=(cipher-key[phase])%29;encoded.append((value+key[phase])%29)
                    phase=(phase+1)%13
                output.append(value)
            assert encoded==section['cipher'] and phase==path['end_phase']
            assert hashlib.sha256(bytes(output)).hexdigest()==path['full_output_sha256']
            assert all(output[int(p)] in allowed for p,allowed in section['constraints'].items())
            decoded[section['id']]=output;total+=len(output)
        assert total==12947
        anchor=[]
        for left,right in query['couplings']:
            a=decoded[left['section']][left['offset']];b=decoded[right['section']][right['offset']]
            assert a==b;anchor.append(a)
        rows.append({'witness_from_query':result['id'],'valid_for_same_81_word_query':True,
            'runes_replayed':total,'all_81_memberships_and_six_equalities_satisfied':True,
            'anchor_ordinal_values':anchor,'not_a_translation':True})
    assert len(rows)==2 and rows[0]['anchor_ordinal_values']!=rows[1]['anchor_ordinal_values']
    out={'session':96,'results_sha256':SHA('independent_phrase_results.json'),
        'inputs_sha256':SHA('independent_phrase_inputs.json'),'audit_driver_sha256':SHA('independent_phrase_ambiguity.py'),
        'rows':rows,'same_81_word_premise_has_at_least_two_distinct_anchor_outputs':True,
        'solver_calls':0,'no_statement_of_total_solution_count':True}
    target=ROOT/'independent_phrase_ambiguity.json'
    if target.exists():assert READ(target.name)==out,'Preserve differing audit outcomes.'
    else:target.write_text(json.dumps(out,indent=2)+'\n')
    print(json.dumps({'same_query':'AIO_prior_red_exemptions','distinct_feasible_anchor_outputs':2,
        'additional_solver_calls':0,'not_plaintext_recovery':True}))


if __name__=='__main__':audit()
