"""priority_list.py — Merge BigG rank + PLN sieve consensus into GPU priority list."""
import subprocess, re

# Top 30 from bigg --rank sweep + manually added 137843969 (missed by stride)
rank_top = [
    135139661, 137381261, 138648269, 137447309, 136205261,
    135044621, 137404109, 137520653, 137424461, 135206861,
    138552077, 136257101, 135063437, 135069581, 135113933,
    137707853, 134765837, 135161357, 138556109, 136351949,
    137495117, 136230989, 135977741, 137802893, 135181133,
    137873357, 137496269, 136678541, 136142093, 136649549,
    137843969  # high-scoring sieve candidate missed by rank stride
]

# Top 15 by consensus from sieve ranked list
sieve_consensus = []
with open('ranked_candidates.txt') as f:
    for line in f:
        if line.startswith('#') or not line.strip():
            continue
        parts = line.split()
        rank_i = int(parts[0])
        p = int(parts[1])
        consensus = float(parts[5])
        if rank_i <= 15:
            sieve_consensus.append(p)

# Merge, no duplicates
seen = set()
all_candidates = []
for p in rank_top:
    if p not in seen:
        seen.add(p)
        all_candidates.append(p)
for p in sieve_consensus:
    if p not in seen:
        seen.add(p)
        all_candidates.append(p)

# Score all with BigG
result = subprocess.run(
    ['.\\bigg_overfit.exe', '--score'] + [str(p) for p in all_candidates],
    capture_output=True, text=True)
bigg = {}
for line in result.stdout.splitlines():
    m = re.match(r'\s+(\d+)\s+yes\s+\S+\s+\S+\s+\S+\s+([\d.]+)', line)
    if m:
        bigg[m.group(1)] = float(m.group(2))

rank_set = set(rank_top)
sieve_set = set(sieve_consensus)

rows = []
for p in all_candidates:
    score = bigg.get(str(p), 0.0)
    src = []
    if p in rank_set:
        src.append('bigg-rank')
    if p in sieve_set:
        src.append('pln-sieve')
    rows.append((p, score, '+'.join(src)))

rows.sort(key=lambda x: -x[1])

print("=== PRIORITY GPU TEST LIST (BigG rank + PLN sieve consensus) ===")
print("  Candidates appearing in BOTH paths are highest confidence.")
print()
print("  {:4s}  {:>12s}  {:>6s}  source".format("rank", "p", "BigG"))
print("  " + "-"*45)
for i, (p, score, src) in enumerate(rows[:40], 1):
    both = " <-- BOTH" if "bigg-rank" in src and "pln-sieve" in src else ""
    print("  {:4d}  {:>12d}  {:.4f}  {}{}".format(i, p, score, src, both))

# Save priority list
with open('priority_gpu_list.txt', 'w') as f:
    f.write("# Priority GPU LL test list — BigG rank + PLN sieve consensus\n")
    f.write("# Sorted by BigG overfit score (Path 2). BOTH = consensus between paths.\n")
    f.write("# rank  p             BigG    source\n")
    for i, (p, score, src) in enumerate(rows, 1):
        f.write("{:4d}  {:>12d}  {:.4f}  {}\n".format(i, p, score, src))

print()
print("Saved {} candidates to priority_gpu_list.txt".format(len(rows)))

# Count "BOTH"
both_count = sum(1 for _, _, src in rows if "bigg-rank" in src and "pln-sieve" in src)
print("Consensus (both paths): {} candidates".format(both_count))
