"""Generate conditional certificates and check them independently by obligation search."""
from collections import deque
from functools import lru_cache
from math import gcd, factorial, prod
from collections import Counter
from itertools import combinations
from pathlib import Path
import argparse,json
from couverture10 import P,domains
from geometrie41 import check,decode,moves
HERE=Path(__file__).resolve().parent

def clauses(row,paths):
    return [[x] for x in row['interior']]+paths

def sat(row,paths):
    from reductions11 import attack
    return attack(clauses(row,paths),domains(row['u'],row['v']))

def specialized(row,paths):
    ops=domains(row['u'],row['v'])
    cs=[frozenset((i,x%p) for x in path for i,p in enumerate(P) if x%p in ops[i]) for path in clauses(row,paths)]
    # Absorption preserves the conjunction of obligations (one choice per wheel).
    unique=[]
    for c in sorted(set(cs),key=lambda c:(len(c),sorted(c))):
        if not any(t<=c for t in unique):unique.append(c)
    visited=0
    def search(todo,used):
        nonlocal visited
        visited+=1
        if not todo:return True
        pivot=min((tuple((i,r) for i,r in unique[t] if i not in used) for t in todo),key=len)
        for i,r in sorted(pivot):
            if search([t for t in todo if (i,r) not in unique[t]],used|{i}):return True
        return False
    return search(list(range(len(unique))),set()),visited

def generate(row, *, resume=None, on_path=None, max_additions=80, oracle=sat):
    u,v=row['u'],row['v'];ranks={decode(8,r):r for r in range(factorial(8)) if gcd(r,210)==1};trans=moves()
    @lru_cache(None)
    def neighbors(x):
        w=decode(8,x)
        return sorted(value for m in trans if (value:=ranks.get(tuple(w[i] for i in m))) is not None)
    paths=list(resume['paths']) if resume else [[x] for x in row['midpoints'] if x not in row['interior']]
    history=list(resume['refutations']) if resume else []
    while True:
        phase=oracle(row,paths)
        if phase is None:return dict(paths=paths,refutations=history,first=sat(row,[]))
        if max_additions is not None and len(history)>=max_additions:
            raise RuntimeError(f'{max_additions} additions exhausted')
        parents={u:None};queue=deque([u])
        while queue and v not in parents:
            a=queue.popleft()
            for b in neighbors(a):
                if b not in parents and all(b%p!=r for p,r in zip(P,phase)):
                    queue.append(b);parents[b]=a
        if v not in parents:raise ValueError(('disconnected',phase))
        path=[];x=parents[v]
        while x!=u:path.append(x);x=parents[x]
        paths.append(path[::-1]);history.append(phase)
        if on_path is not None:
            on_path(dict(paths=paths,refutations=history))

def verify(row,cert,reader='special'):
    u,v=row['u'],row['v'];paths=cert['paths'];ops=domains(u,v)
    assert 0 <= u < v < factorial(8)
    for path in paths:
        assert path and all(0 <= x < factorial(8) and x not in (u,v) for x in path)
        assert len(path) == len(set(path))
    assert row['interior']==[x for x in range(u+1,v) if gcd(x,210)==1]
    def alive(path,ph):return all(x%p!=r for x in path for p,r in zip(P,ph))
    def allowed(ph):return len(ph)==len(P) and all(x in a for x,a in zip(ph,ops)) and all(not alive([x],ph) for x in row['interior'])
    assert allowed(cert['first'])
    start=len(paths)-len(cert['refutations'])
    assert paths[:start]==[[x] for x in row['midpoints'] if x not in row['interior']]
    for j,ph in enumerate(cert['refutations'],start):
        assert allowed(ph) and not any(alive(pa,ph) for pa in paths[:j]) and alive(paths[j],ph)
    geom=check(dict(families=[[u,v,paths]],bridges=[]))
    if reader=='sat':
        assert sat(row,paths) is None
        return dict(paths=len(paths),edges=geom['internal_edges'])
    possible,nodes=specialized(row,paths)
    assert not possible
    return dict(paths=len(paths),edges=geom['internal_edges'],nodes=nodes)

def admissible_count(row):
    middle=row['interior'];u,v=row['u'],row['v']
    count=0
    for j in range(len(middle)+1):
        for subset in combinations(middle,j):
            count+=(-1)**j*prod(p-len({x%p for x in (u,v,*subset)}) for p in P)
    states=Counter({0:1})
    for p,domain in zip(P,domains(u,v)):
        signatures=Counter(sum(1<<i for i,x in enumerate(middle) if x%p==r) for r in domain)
        nxt=Counter()
        for mask,n in states.items():
            for m,k in signatures.items():nxt[mask|m]+=n*k
        states=nxt
    assert states[2**len(middle)-1]==count and count>0
    return count

def transfer(rows,data):
    a,b=rows['A'],rows['B'];shift=b['u']-a['u'];assert b['v']==a['v']+shift
    bad=[];possible=moves()
    for i,path in enumerate(data['A']['paths']):
        translated=[a['u']+shift,*[x+shift for x in path],a['v']+shift]
        for x,y in zip(translated,translated[1:]):
            if max(x,y)>=factorial(8) or tuple(decode(8,x).index(v) for v in decode(8,y)) not in possible:
                bad.append([i,x,y]);break
    return dict(shift=shift,paths=len(data['A']['paths']),failed=len(bad),first_bad=bad[:1])

if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('--generate',choices=list('ABC'));parser.add_argument('--sat',choices=list('ABC'));parser.add_argument('--special',choices=list('ABC'))
    parser.add_argument('--certificate',type=Path,default=HERE/'certificats12.json',help='certificate file used by --sat or --special');args=parser.parse_args()
    rows=json.loads((HERE/'choix12.json').read_bytes())
    if args.generate:result=generate(rows[args.generate])
    else:
        data=json.loads(args.certificate.read_bytes())
        selected=args.sat or args.special
        if selected=='B' and selected not in data and args.certificate==HERE/'certificats12.json':
            data.update(json.loads((HERE/'certificat-libre-B.json').read_bytes()))
        if selected and selected not in data:
            parser.error(f'family {selected} is absent from this certificate')
        if args.sat:result=verify(rows[args.sat],data[args.sat],'sat')
        elif args.special:result=verify(rows[args.special],data[args.special])
        else:result=dict(checks={k:verify(rows[k],v) for k,v in data.items()},translation=transfer(rows,data),conditional_phases={k:admissible_count(r) for k,r in rows.items()})
    print(json.dumps(result,indent=2))
