"""Pure, independently testable scoring. SSR references are the 2026 baseline.
2027 publication is locked until an administrator records the governing rules.
All ambiguities become review items; source timing rows are never overwritten.
"""
from collections import defaultdict,Counter
from copy import deepcopy
from decimal import Decimal,ROUND_CEILING
import re
RULES={'version':'2026 baseline — 2027 approval required','approved':False,'source':'','policy_note':'',
 'thresholds':{'A':None,'B':75500,'C':80000,'D':83000,'E':86000,'F':89000},
 'fraction':'0.667','minimum_starters':12,'scheduled_events':8,'large':[10,8,6,5,4,3,2,1],'small':[8,6,5],
 'qual_bonus':1,'race_bonus':1,'debrief_bonus':1,'fastest_requires_distance':True,'drop_attendance':True,
 'guest_policy':'exclude_and_close_up','trophy_basis':'race_points','official_season':False}
def ms(v):
 if v is None or str(v).strip().upper() in ('','-','DNS','DNF','DSQ','N/A','0'):return None
 s=str(v).strip().replace(',','.')
 if not re.fullmatch(r'\d+(?::\d{1,2}){0,2}(?:\.\d{1,3})?',s):raise ValueError('Invalid time: '+s)
 a=[Decimal(n) for n in s.split(':')]
 if len(a)>1 and any(n>=60 for n in a[1:]):raise ValueError('Invalid minutes/seconds')
 t=Decimal(0)
 for n in a:t=t*60+n
 return int(t*1000) if t>0 else None
def fmt(t):
 if t is None:return '—'
 m,r=divmod(int(t),60000);s,f=divmod(r,1000);return f'{m}:{s:02}.{f:03}'
def minlaps(laps,rules):return int((Decimal(str(laps))*Decimal(rules['fraction'])).to_integral_value(rounding=ROUND_CEILING))
def suggested(cls,time,rules):
 if cls not in list('ABCDEF'):raise ValueError('Invalid class')
 i='ABCDEF'.index(cls)
 while i>0 and time is not None and time<rules['thresholds']['ABCDEF'[i]]:i-=1
 return 'ABCDEF'[i]
def factor(round_no):return Decimal('1') if round_no<=3 else Decimal('.9') if round_no<=6 else Decimal('.75')
def drops(n):return 0 if n<=8 else 1 if n==9 else n-8

def score(event,rules):
 e=deepcopy(event);entries={x['id']:x for x in e.get('entries',[])};sessions={};issues=[];hard=[];byentry=defaultdict(list)
 starters=Counter();changes=[];totals=[]
 for kind,ss in e.get('sessions',{}).items():
  for raw in ss.get('rows',[]):
   r=deepcopy(raw);ent=entries.get(r.get('entry_id'))
   if not ent:hard.append(f'{kind}: match #{r["number"]} {r["name"]} to a driver/car or guest');continue
   r.update(name=ent['name'],number=ent['number'],cls=ent['cls'],driver_id=ent.get('driver_id'),car_id=ent.get('car_id'),guest=ent.get('guest',False),eligible=ent.get('eligible',False),race_points=0,bonus=0,class_position=None,scoring_position=None)
   r['session']=kind;byentry[ent['id']].append(r);sessions.setdefault(kind,{'rows':[],'minimum_laps':0})['rows'].append(r)
 for id,ent in entries.items():
  rr=byentry[id]
  valid=[r['best_ms'] for r in rr if r.get('best_ms') and r['status'] not in ('DNS','DSQ')]
  new=suggested(ent['cls'],min(valid) if valid else None,rules)
  if new!=ent['cls']:
   changes.append({'entry_id':id,'number':ent['number'],'name':ent['name'],'from':ent['cls'],'to':new,'best':fmt(min(valid))});hard.append(f'Breakout #{ent["number"]}: {ent["cls"]} → {new}; approve class movement')
  if not ent.get('identity_reviewed'):hard.append(f'Confirm identity and eligibility for #{ent["number"]}')
  started=ent.get('starter_confirmed') or any((r['session']=='Q' and r.get('best_ms')) or (r['session']!='Q' and (r.get('laps',0)>0 or r.get('crossed_start'))) for r in rr)
  if ent.get('eligible') and started:starters[ent['cls']]+=1
 count=sum(starters.values());roundvalid=count>=rules['minimum_starters']
 if not roundvalid:issues.append(f'{count} eligible round starters; minimum {rules["minimum_starters"]}. Championship race/qualifying points held at zero.')
 for kind,ss in sessions.items():
  meta=e['sessions'][kind];race=kind!='Q';scheduled=int(meta.get('scheduled_laps') or e.get('planned_laps') or 0)
  minimum=minlaps(scheduled,rules) if scheduled and race else 0;ss['minimum_laps']=minimum
  actual=int(meta.get('completed_laps') or max((r.get('laps',0) for r in ss['rows']),default=0))
  validrace=not race or scheduled>0 and actual>=minimum
  if race and not scheduled:hard.append(f'{kind}: set scheduled race distance')
  if not validrace:issues.append(f'{kind}: shortened below 66.7%; no race points')
  if meta.get('source_provisional'):issues.append(f'{kind}: provisional source; confirm timing/official review')
  grouped=defaultdict(list)
  for r in ss['rows']:grouped[r['cls']].append(r)
  for cls,group in grouped.items():
   classified=[r for r in group if r['status']=='CLASSIFIED']
   if race and any(r.get('penalty_ms',0) for r in classified):
    if any(r.get('total_ms') is None for r in classified):hard.append(f'{kind}/{cls}: extra time penalty requires all total times')
    ordered=sorted(classified,key=lambda r:(-r.get('laps',0),(r.get('total_ms') or 10**12)+r.get('penalty_ms',0),r.get('position') or 9999))
   elif race:ordered=sorted(classified,key=lambda r:r.get('position') or 9999)
   else:ordered=sorted(classified,key=lambda r:(r.get('best_ms') or 10**12,r.get('second_ms') or 10**12,r.get('position') or 9999))
   p=0
   for i,r in enumerate(ordered,1):
    r['class_position']=i
    if r['eligible']:
     p+=1;r['scoring_position']=p
     enough=not race or r.get('laps',0)>=minimum
     if race and not enough:issues.append(f'{kind} #{r["number"]}: {r.get("laps",0)}/{scheduled} laps; at least {minimum} required for race points')
     if race and enough and roundvalid and validrace:
      scale=rules['large'] if starters[cls]>=4 else rules['small'];r['race_points']=scale[p-1] if p<=len(scale) else (1 if starters[cls]>=4 else 0)
      if e.get('single_race_confirmed'):r['race_points']*=2
   candidates=[r for r in group if r['eligible'] and r.get('best_ms') and r['status'] not in ('DNS','DSQ')]
   allowed=[r for r in candidates if not race or not rules['fastest_requires_distance'] or r['status']=='CLASSIFIED' and r.get('laps',0)>=minimum]
   if candidates and allowed and min(r['best_ms'] for r in candidates)<min(r['best_ms'] for r in allowed):issues.append(f'{kind}/{cls}: outright fastest has insufficient distance; verify bonus eligibility policy')
   if allowed:
    fastest=min(r['best_ms'] for r in allowed);win=[r for r in allowed if r['best_ms']==fastest]
    override=meta.get('fastest_overrides',{}).get(cls)
    if override:
     win=[r for r in win if r['entry_id']==override]
     if not win:hard.append(f'{kind}/{cls}: invalid fastest-lap selection; review again')
    if len(win)>1:hard.append(f'{kind}/{cls}: tied fastest lap; official selection required')
    elif len(win)==1:
     win[0]['fastest']=True
     if roundvalid and validrace:win[0]['bonus']=rules['race_bonus'] if race else rules['qual_bonus']
  for r in ss['rows']:r.update(points=r['race_points']+r['bonus'],best_lap=fmt(r.get('best_ms')),total_time=fmt(r.get('total_ms')))
  ss['rows'].sort(key=lambda r:(r['cls'],r.get('class_position') or 9999,r.get('position') or 9999))
 attendees={a['driver_id']:a for a in e.get('attendance',[]) if a['kind']=='debrief'}
 for id,ent in entries.items():
  rr=byentry[id];a=attendees.get(ent.get('driver_id'),{});races=[r for r in rr if r['session']!='Q']
  t={k:ent.get(k) for k in ('id','driver_id','car_id','name','number','cls','eligible','guest','promotion','non_droppable','championship_action')}
  t.update(race_points=sum(r['race_points'] for r in rr),qual_bonus=sum(r['bonus'] for r in rr if r['session']=='Q'),fastest_bonus=sum(r['bonus'] for r in races),debrief=rules['debrief_bonus'] if ent.get('eligible') and (a.get('present') or a.get('bonus_approved')) else 0,laps=sum(r.get('laps',0) for r in races),combined_ms=sum((r.get('total_ms') or 0)+r.get('penalty_ms',0) for r in races),places=sorted(r['class_position'] for r in races if r.get('class_position')))
  t['total']=sum(t[k] for k in ('race_points','qual_bonus','fastest_bonus','debrief'));totals.append(t)
 winners={}
 for cls in 'ABCDEF':
  group=[r for r in totals if r['cls']==cls and r.get('eligible') and r['race_points']>0]
  if not group:continue
  best=max(r['race_points'] for r in group);tied=[r for r in group if r['race_points']==best]
  if len(tied)>1:
   if len({r['laps'] for r in tied})>1:issues.append(f'Trophy/{cls}: tied points with unequal laps; authority decision needed')
   else:
    fastest=min(r['combined_ms'] for r in tied);tied=[r for r in tied if r['combined_ms']==fastest]
    if len(tied)>1:
     pos=min(r['places'] for r in tied);tied=[r for r in tied if r['places']==pos]
  winners[cls]=[r['id'] for r in tied]
 eligible=[r for r in totals if r.get('eligible')];maxpoints=max((r['total'] for r in eligible),default=0)
 if not sessions:hard.append('Import at least one timing session')
 if e.get('single_race_confirmed') and len([k for k in sessions if k!='Q'])>1:hard.append('Single-race doubling is selected but two races are present')
 return {'sessions':sessions,'totals':totals,'class_winners':winners,'points_leaders':[r['id'] for r in eligible if r['total']==maxpoints and maxpoints>0], 'overall_winner':e.get('overall_winner'),'issues':list(dict.fromkeys(issues)),'blockers':list(dict.fromkeys(hard)),'breakouts':changes,'starters':dict(starters),'starter_count':count,'grids':grids(sessions,entries)}

def grids(sessions,entries):
 out={}
 for target,source in [('R1','Q'),('R2','R1')]:
  allrows=[]
  for cls in 'ABCDEF':
   rr=[r for r in sessions.get(source,{}).get('rows',[]) if r['cls']==cls];rr.sort(key=lambda r:r.get('class_position') or 9999)
   if target=='R2':
    top=[r for r in rr if r['status']=='CLASSIFIED'][:5];tail=[r for r in rr if r not in top];inv=[]
    for laps in sorted({r.get('laps',0) for r in top},reverse=True):inv+=list(reversed([r for r in top if r.get('laps',0)==laps]))
    penalised=[r for r in inv if r.get('penalty_ms') or r.get('grid_penalty')]
    rr=[r for r in inv if r not in penalised]+sorted(penalised,key=lambda r:r.get('class_position') or 9999,reverse=True)+tail
   known={r['entry_id'] for r in rr}
   for e in entries.values():
    if e['cls']==cls and e['id'] not in known:rr.append({'entry_id':e['id'],'name':e['name'],'number':e['number'],'cls':cls})
   allrows+=rr
  normal=[r for r in allrows if not entries[r['entry_id']].get('novice_back')]
  novice=[r for r in allrows if entries[r['entry_id']].get('novice_back')];final=[]
  for i,r in enumerate(normal+novice,1):
   ent=entries[r['entry_id']];final.append({'entry_id':r['entry_id'],'position':i,'name':r['name'],'number':r['number'],'cls':r['cls'],'pitlane':bool(ent.get('pitlane')),'novice':bool(ent.get('novice_back'))})
  # Pitlane entries retain their numbered empty grid slot; other cars do not close up.
  out[target]={'rows':final,'status':'Draft — CoC review required'}
 return out

def standings(snapshots,rules):
 accounts={}
 for snap in sorted(snapshots,key=lambda s:(s['round_no'],s['event_date'],s['id'])):
  for r in snap['scores']['totals']:
   if not r.get('driver_id') or not r.get('eligible'):continue
   a=accounts.setdefault(r['driver_id'],{'driver_id':r['driver_id'],'name':r['name'],'cls':r['cls'],'ledger':[],'cars':set(),'countback':Counter()})
   if r.get('championship_action')=='reset':
    for old in a['ledger']:old['value']=Decimal(0);old['debrief']=Decimal(0);old['reset']=True
    a['countback']=Counter()
   f=factor(snap['round_no']) if r.get('promotion') else Decimal(1)
   for old in a['ledger']:old['value']*=f;old['debrief']*=f
   a['cls']=r['cls'];a['cars'].add(r.get('car_id'));a['name']=r['name']
   a['ledger'].append({'event_id':snap['id'],'round':snap['round_no'],'raw':r['total'],'value':Decimal(str(r['total'])),'debrief':Decimal(str(r.get('debrief',0))),'locked':bool(r.get('non_droppable')),'factor':str(f)})
   for p in r.get('places',[]):a['countback'][p]+=1
 # In-season standings keep up to the allowed counting rounds. Future rounds
 # are not treated as already completed; missed completed rounds are zero slices.
 keep=int(rules['scheduled_events'])-drops(int(rules['scheduled_events']));count=max(0,len(snapshots)-keep);out=[]
 for a in accounts.values():
  seen_ids={x['event_id'] for x in a['ledger']}
  for snap in snapshots:
   if snap['id'] not in seen_ids:a['ledger'].append({'event_id':snap['id'],'round':snap['round_no'],'raw':0,'value':Decimal(0),'debrief':Decimal(0),'locked':False,'factor':'1','absent':True})
  a['ledger'].sort(key=lambda x:x['round'])
  choices=sorted([x for x in a['ledger'] if not x['locked']],key=lambda x:x['value']-(Decimal(0) if rules['drop_attendance'] else x['debrief']))
  dropids={x['event_id'] for x in choices[:count]};total=Decimal(0)
  for x in a['ledger']:
   x['dropped']=x['event_id'] in dropids;total+=x['value'] if not x['dropped'] else Decimal(0) if rules['drop_attendance'] else x['debrief'];x['value']=float(x['value']);x['debrief']=float(x['debrief'])
  a['total']=float(total);a['cars']=sorted(c for c in a['cars'] if c);a['countback']=[a['countback'][i] for i in range(1,21)];out.append(a)
 out.sort(key=lambda a:(-a['total'],[-x for x in a['countback']]))
 ranks={};seen=Counter();last=None;overall=0
 for i,a in enumerate(out,1):
  key=(a['total'],a['countback']);cls=a['cls'];seen[cls]+=1
  if key!=last:overall=i
  if cls not in ranks or ranks[cls][0]!=key:ranks[cls]=(key,seen[cls])
  a['overall_position']=overall;a['class_position']=ranks[cls][1];last=key
 return out
