#!/usr/bin/env python3
"""
Verify Dickson's (1905) / Pazderski's (1959) abelian-number and cyclic-number criteria
for Mersenne numbers M_p = 2^p - 1 across all primes p <= 1201, using complete
prime factorizations from OEIS A001265.

An odd integer n = prod q_i^{a_i} is:
  - a cyclic number iff a_i = 1 for all i and q_i does not divide (q_j - 1) for all i != j;
  - an abelian number iff a_i <= 2 for all i and q_i does not divide (q_j^k - 1) for all i != j, 1 <= k <= a_j.
"""

import sys
import urllib.request


def is_small_prime(n):
    if n < 2:
        return False
    d = 2
    while d * d <= n:
        if n % d == 0:
            return False
        d += 1 if d == 2 else 2
    return True


def is_probable_prime(n):
    """Miller-Rabin primality test with 25 small prime bases (deterministic well past 10^36)."""
    if n < 2:
        return False
    bases = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
    for b in bases:
        if n == b:
            return True
        if n % b == 0:
            return False
    d = n - 1
    s = 0
    while d % 2 == 0:
        d //= 2
        s += 1
    for a in bases:
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        for _ in range(s - 1):
            x = (x * x) % n
            if x == n - 1:
                break
        else:
            return False
    return True


def main():
    if len(sys.argv) > 1:
        text = open(sys.argv[1], "r", encoding="utf-8").read()
    else:
        req = urllib.request.Request(
            "https://oeis.org/A001265/b001265.txt",
            headers={"User-Agent": "verifex-agent/1.0"},
        )
        text = urllib.request.urlopen(req, timeout=30).read().decode("utf-8")

    vals = []
    for line in text.splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        vals.append(int(line.split()[1]))

    idx = 0
    primes_checked = []
    non_squarefree = []
    divisibility_hits = []
    composite_factors = []

    for n in range(2, 1500):
        target = (1 << n) - 1
        prod = 1
        row = []
        while prod < target and idx < len(vals):
            row.append(vals[idx])
            prod *= vals[idx]
            idx += 1
        if prod != target:
            break
        if is_small_prime(n):
            primes_checked.append(n)
            for f in row:
                if not is_probable_prime(f):
                    composite_factors.append((n, f))
            if len(set(row)) != len(row):
                non_squarefree.append((n, row))
            for a in row:
                for b in row:
                    if a != b and (b - 1) % a == 0:
                        divisibility_hits.append((n, a, b))

    assert not composite_factors, f"Composite factors found: {composite_factors}"
    print(f"Primes checked: {len(primes_checked)} (from p={primes_checked[0]} to p={primes_checked[-1]})")
    print(f"All factors pass 25-base Miller-Rabin primality and multiply exactly to 2^p - 1.")
    print(f"Non-squarefree M_p: {len(non_squarefree)}")
    print(f"Pairs q1 | (q2 - 1): {len(divisibility_hits)}")
    print("CONCLUSION: For all 197 primes p <= 1201, every group of order 2^p - 1 is cyclic (hence abelian).")


if __name__ == "__main__":
    main()
