#!/usr/bin/env python3
import lzma,collections,random,sys
path=sys.argv[1]; mode=sys.argv[2]
cla=[]; sizes=collections.Counter(); nvar=0
for line in lzma.open(path,'rt'):
 if line.startswith('c'): continue
 if line.startswith('p'): nvar=int(line.split()[2]); continue
 lits=list(map(int,line.split()))
 if lits and lits[-1]==0: lits=lits[:-1]
 if lits: cla.append(lits); sizes[len(lits)]+=1
n=max(k for k,v in sizes.items() if k==v); prim=n*n
perm=list(range(1,n+1))
# simple permutation position[row]=row maybe reverse maybe random
if len(sys.argv)>3 and sys.argv[3]=='rev': perm=list(range(n,0,-1))
assign=[0]*(nvar+1)
if mode=='onehot':
 for r,pos in enumerate(perm, start=1): assign[(r-1)*n+pos]=1
 for v in range(1,prim+1):
  if assign[v]==0: assign[v]=-1
elif mode=='le':
 for r,pos in enumerate(perm, start=1):
  for c in range(1,n+1): assign[(r-1)*n+c]=1 if pos<=c else -1
elif mode=='ge':
 for r,pos in enumerate(perm, start=1):
  for c in range(1,n+1): assign[(r-1)*n+c]=1 if pos>=c else -1
# propagate unit naïvely
changed=True; it=0
while changed:
 changed=False; it+=1
 for idx,c in enumerate(cla):
  sat=False; un=[]
  for lit in c:
   val=assign[abs(lit)]
   if val and ((lit>0 and val>0) or (lit<0 and val<0)):
    sat=True; break
   if val==0: un.append(lit)
  if sat: continue
  if not un:
   print('conflict',idx+1,c[:10]); sys.exit(0)
  if len(un)==1:
   lit=un[0]; v=abs(lit); val=1 if lit>0 else -1
   if assign[v]==-val:
    print('conflict assign',idx+1,c); sys.exit(0)
   if assign[v]==0: assign[v]=val; changed=True
print('no conflict, assigned',sum(1 for x in assign if x),'iters',it)
