"""Recursive orbit representatives for exact gaps in a square-free wheel."""
from math import gcd, prod
from pathlib import Path
import json
import sys

sys.path.append(str(Path(__file__).resolve().parents[2]/"diffusion/IX/src"))
from motif_address import CoverFiber
from motifs import primes


def representatives(n,g,limit=10000):
    if n<2 or g<1:
        raise ValueError("n >= 2, g >= 1")
    ps = primes(n)
    period = prod(ps)
    points = []
    calls = stable = 0

    def descend(a,b,i):
        nonlocal calls, stable
        if i==len(ps):
            if all(gcd(a+h,b)>1 for h in range(1,g)):
                points.append(a)
                calls += 1
                stable += 1
            return
        p = ps[i]
        for digit in range(p):
            x = a+b*digit
            m = b*p
            if x%p==0 or (x+g)%p==0:
                continue
            y = (-g-x)%m
            if x>y:
                continue
            if x==y:
                descend(x,m,i+1)
            else:
                holes = [h for h in range(1,g) if gcd(x+h,m)==1]
                fibre = CoverFiber(ps[i+1:],holes,g)
                if len(points)+2*fibre.total>limit:
                    raise ValueError("output limit")
                for k in range(fibre.total):
                    v = fibre.unrank(k,x,m)
                    points.extend([v,(-g-v)%period])
                calls += fibre.total
        if len(points)>limit:
            raise ValueError("output limit")

    descend(0,1,0)
    assert 2*calls==len(points)+stable
    return sorted(points),calls,stable


if __name__=="__main__":
    checks = 0
    example = {}
    for n in (2,3,5,7,11,13):
        period = prod(primes(n))
        units = [x for x in range(period) if gcd(x,period)==1]
        pairs = list(zip(units,units[1:]+[units[0]+period]))
        for g in range(1,19):
            out,calls,fixed = representatives(n,g)
            assert out==[x for x,y in pairs if y-x==g]
            checks += 1
            if n==7 and g in (2,4,6,10):
                example[g] = {"events":len(out),"representatives":calls,"fixed":fixed}
    even_periods = 0
    for r in range(4, 501, 2):
        units = [a for a in range(r) if gcd(a,r)==1]
        fixed = sorted(b-a for a,b in zip(units,units[1:]+[units[0]+r]) if (a+b)%r==0)
        assert fixed == ([2,2] if r%4==0 else [2,4])
        even_periods += 1
    print(json.dumps({"exact_checks":checks,"level_7":example,"fixed_gap_checks":even_periods},indent=2))
