"""Pure scoring/switch primitives; no file I/O or research execution at import."""
from collections import Counter
import math,random

def frequency_bin(n):
    if n==0:return '0'
    if n==1:return '1'
    if n<=4:return '2-4'
    if n<=16:return '5-16'
    return '17+'

def graph_signature(groups,bins=None):
    return {'group_degrees':{g:len(ws) for g,ws in groups.items()},'word_degrees':dict(Counter(w for ws in groups.values() for w in ws)), 'group_bin_profiles':{g:dict(Counter(bins[w] for w in ws)) for g,ws in groups.items()} if bins is not None else None}

def switch_attempt(groups,edges,sections,bins,rng,condition_bins=True):
    """Two fixed-position uniformly sampled edges; retain rejected attempts."""
    if len(edges)<2:return 'fewer_than_two_edges'
    a,b=rng.sample(range(len(edges)),2);g,x=edges[a];h,y=edges[b]
    if g==h:return 'same_group'
    if x==y:return 'same_word'
    if sections[g]!=sections[h]:return 'different_section'
    if condition_bins and bins[x]!=bins[y]:return 'different_frequency_bin'
    if y in groups[g] or x in groups[h]:return 'existing_edge'
    groups[g].remove(x);groups[g].add(y);groups[h].remove(y);groups[h].add(x)
    edges[a]=(g,y);edges[b]=(h,x)
    return 'accepted'

def switch_graph(original,sections,bins,seed,attempts,condition_bins=True):
    groups={g:set(ws) for g,ws in original.items()};edges=sorted((g,w) for g,ws in groups.items() for w in ws)
    before=graph_signature(groups,bins if condition_bins else None);rng=random.Random(seed);counts=Counter()
    for _ in range(attempts):counts[switch_attempt(groups,edges,sections,bins,rng,condition_bins)]+=1
    assert graph_signature(groups,bins if condition_bins else None)==before
    assert set(edges)=={(g,w) for g,ws in groups.items() for w in ws} and len(set(edges))==len(edges)
    return groups,{'attempts':attempts,'outcomes':dict(counts),'turnover':{g:len(original[g]-ws) for g,ws in groups.items()},'seed':seed}

def unit_frequencies(units):
    return Counter(w for u in units.values() for w in {x['word'] for x in u['occurrences']})

def score_pair(source_id,source_forms,source_folio,receiver,unit_count,document_frequency):
    """Mask applies identically to observed or reassigned source sets."""
    if source_folio==receiver['folio']:return None
    receiver_words={x['word'] for x in receiver['occurrences']};shared=sorted(source_forms & receiver_words)
    return {'source':source_id,'receiver':receiver['id'],'shared_forms':shared,'count':len(shared),'source_coverage':len(shared)/len(source_forms) if source_forms else None,'receiver_length':len(receiver['occurrences']),'weighted':sum(math.log((unit_count+1)/(document_frequency[w]+1)) for w in shared)}

def section_relation(source_section,receiver_section):
    if source_section is None or receiver_section is None:return 'unknown'
    return 'same_section' if source_section==receiver_section else 'cross_section'

def universe_rank_summary(scored_rows,metric):
    """Linear tally plus sorted unique scores; eligibility recomputed per input."""
    if metric not in ('count','weighted'):raise ValueError(metric)
    answer={}
    for universe in ('all_cross_folio','cross_section','same_section','unknown'):
        base=[r for r in scored_rows if universe=='all_cross_folio' or r['section_relation']==universe]
        answer[universe]={}
        for eligibility in ('unrestricted','candidate'):
            rows=[r for r in base if eligibility=='unrestricted' or r['count']>=2]
            if not rows:
                answer[universe][eligibility]={'cells':0,'universe_cells':len(base),'maximum':None,'empty_candidate':eligibility=='candidate','maximizers':[],'ranks':[]};continue
            tally=Counter(r[metric] for r in rows);bounds={};above=0
            for value in sorted(tally,reverse=True):
                bounds[value]=(above+1,above+tally[value]);above+=tally[value]
            maximum=max(tally)
            answer[universe][eligibility]={'cells':len(rows),'universe_cells':len(base),'maximum':maximum,'empty_candidate':False,'maximizers':[{'source':r['source'],'receiver':r['receiver']} for r in rows if r[metric]==maximum],'ranks':[{'source':r['source'],'receiver':r['receiver'],'first':bounds[r[metric]][0],'last':bounds[r[metric]][1]} for r in rows]}
    return answer
