"""BMWCCCT Driver Lounge v1.0.0-rc1.
Run: uvicorn app:create_app --factory --host 127.0.0.1 --port 8000
Use scripts/manage.py to initialise an administrator; no default production accounts.
"""
import os,re,json,secrets,hashlib,time,io,sqlite3,base64,html,socket
from pathlib import Path
from datetime import date,datetime,timezone
from copy import deepcopy
from urllib.parse import urlparse
from fastapi import FastAPI,Request,HTTPException
from fastapi.responses import JSONResponse,FileResponse,Response,HTMLResponse
from fastapi.staticfiles import StaticFiles
from PIL import Image,ImageOps,UnidentifiedImageError
import qrcode,qrcode.image.svg
from storage import Store,password_hash,password_ok,totp_check
from fields import PROFILE_FIELDS,CAR_FIELDS,DECLARATION,BANK,VERSION
from scoring import score,standings,suggested,RULES,ms
from importers import parse
ROOT=Path(__file__).parent

def clean(value,limit=4000):return str(value or '').strip()[:limit]
def need(ok,msg,status=400):
 if not ok:raise HTTPException(status,msg)
def email_valid(e):return bool(re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+',e))
def public_user(u):return {k:u[k] for k in ('id','email','name','role','approved','disabled','must_change','created_at')}
def safe_filename(name):return re.sub(r'[^A-Za-z0-9._ -]','_',Path(str(name)).name)[:120] or 'upload'
def now():return datetime.now(timezone.utc).isoformat()

def create_app(data_dir=None,production=None,encryption_key=None,testing=False):
 prod=(os.getenv('APP_ENV')=='production') if production is None else production
 base=os.getenv('PUBLIC_BASE_URL','http://127.0.0.1:8000').rstrip('/')
 if prod:
  need(base.startswith('https://'),'PUBLIC_BASE_URL must be HTTPS in production',500)
  need(os.getenv('PRIVACY_NOTICE_URL','').startswith('https://'),'Publish a privacy notice before production',500)
  need(bool(os.getenv('CLAMAV_SOCKET')),'Configure CLAMAV_SOCKET before accepting production uploads',500)
 store=Store(data_dir or os.getenv('DATA_DIR',ROOT/'data'),encryption_key or os.getenv('ENCRYPTION_KEY'),prod)
 app=FastAPI(title='BMWCCCT Driver Lounge',version=VERSION,docs_url=None,redoc_url=None,openapi_url=None)
 app.state.store=store;app.state.production=prod
 def token_hash(t):return hashlib.sha256(t.encode()).hexdigest()
 def new_session(c,uid=None):
  token=secrets.token_urlsafe(32);csrf=secrets.token_urlsafe(32)
  c.execute('INSERT INTO sessions VALUES(?,?,?,?)',(token_hash(token),uid,csrf,time.time()+8*3600));return token,csrf
 def get_auth(c,req,required=True):
  raw=req.cookies.get('bmw_session','');s=c.execute('SELECT * FROM sessions WHERE token_hash=? AND expires>?',(token_hash(raw),time.time())).fetchone()
  u=c.execute('SELECT * FROM users WHERE id=?',(s['user_id'],)).fetchone() if s and s['user_id'] else None
  if u and u['disabled']:u=None
  if required:need(u is not None,'Please sign in',401)
  return (dict(u) if u else None),s
 def csrf(req,s):need(s is not None and secrets.compare_digest(req.headers.get('x-csrf-token',''),s['csrf']),'Session expired or invalid security token',403)
 def cookie(response,token):response.set_cookie('bmw_session',token,httponly=True,secure=prod,samesite='lax',max_age=8*3600,path='/')
 def admin(u):need(u is not None and u['role']=='admin','Administrator access required',403)
 def own(u,owner):need(u['role']=='admin' or u['id']==owner,'This record is private',403)
 def membership(c,uid):
  r=c.execute('SELECT * FROM memberships WHERE driver_id=? AND season=2027',(uid,)).fetchone()
  if not r:return None
  m=dict(r);m['valid']=m['status']=='active' and bool(m['paid']) and date(2027,1,1)<=date.today()<=date(2027,12,31)
  m['valid_from']='2027-01-01';m['expires']='2027-12-31';return m
 def requirements(c,u):
  p=store.profile(c,u['id']);missing=[label for key,label,*_ in PROFILE_FIELDS if key!='nickname' and not clean(p.get(key))]
  if not p.get('rules_agreed'):missing.append('Race Series declaration')
  cars=store.cars(c,u['id'])
  if not any(not x['archived'] for x in cars):missing.append('Register a race car')
  m=membership(c,u['id'])
  if not m:missing+=['Portrait and annual proof of payment']
  elif m['status']!='active':missing.append('Administrator membership activation')
  if not u['approved']:missing.append('Driver account approval')
  return missing
 def caseview(c,row,u):
  own(u,row['owner_id']);obj=store.unseal(row['cipher']);messages=obj.get('messages',[])
  if u['role']!='admin':messages=[m for m in messages if not m.get('internal')]
  return dict(obj,id=row['id'],owner_id=row['owner_id'],reference=row['reference'],status=row['status'],kind=row['kind'],event_id=row['event_id'],created_at=row['created_at'],messages=messages)
 def eventview(c,e):return dict(e,scores=score(e,store.rules(c,e['season'])))
 def safepublic(snapshot):
  x=deepcopy(snapshot)
  for ss in x.get('scores',{}).get('sessions',{}).values():
   for r in ss['rows']:
    for key in ('source_line','msa','entry_id'):r.pop(key,None)
  x.pop('review_note',None);return x
 def scan(data):
  if not prod:return
  # ClamAV INSTREAM over an administrator-configured Unix socket; fail closed.
  with socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) as s:
   s.settimeout(20);s.connect(os.environ['CLAMAV_SOCKET']);s.sendall(b'zINSTREAM\0')
   import struct
   for p in range(0,len(data),65536):chunk=data[p:p+65536];s.sendall(struct.pack('>I',len(chunk))+chunk)
   s.sendall(b'\0\0\0\0');result=s.recv(4096)
   need(b'OK' in result and b'FOUND' not in result,'Upload failed malware screening',400)
 def file_store(c,u,kind,content,filename):
  ext=Path(filename).suffix.lower();mime='';isimage=ext in ('.jpg','.jpeg','.png','.webp')
  need(kind in ('portrait','payment','evidence','task','rules'),'Invalid upload type')
  need(0<len(content)<=(25 if kind=='evidence' else 8)*1024*1024,'Upload is empty or exceeds its size limit')
  if isimage:
   try:
    with Image.open(io.BytesIO(content)) as im:
     need(im.width*im.height<=24_000_000,'Image is too large');im.verify()
    with Image.open(io.BytesIO(content)) as im:
     im=ImageOps.exif_transpose(im).convert('RGB');im.thumbnail((1600,1600));b=io.BytesIO();im.save(b,'JPEG',quality=90);content=b.getvalue()
    filename=Path(filename).stem+'.jpg';mime='image/jpeg'
   except (UnidentifiedImageError,OSError):raise ValueError('Invalid image')
  elif ext=='.pdf' and kind!='portrait':
   need(content.startswith(b'%PDF-'),'Invalid PDF');mime='application/pdf'
  elif ext in ('.mp4','.mov') and kind=='evidence':
   need(len(content)>12 and content[4:8]==b'ftyp','Invalid video container');mime='video/mp4' if ext=='.mp4' else 'video/quicktime'
  else:raise ValueError('Use JPG, PNG or WebP; documents may be PDF; evidence can also be MP4/MOV')
  scan(content);fid=secrets.token_hex(24);blob=store.fernet.encrypt(content);(store.files/fid).write_bytes(blob);(store.files/fid).chmod(0o600)
  c.execute('INSERT INTO files(id,owner_id,kind,name,mime,size,sha256) VALUES(?,?,?,?,?,?,?)',(fid,u['id'],kind,safe_filename(filename),mime,len(content),hashlib.sha256(content).hexdigest()))
  store.audit(c,u['id'],'file_uploaded',fid);return {'id':fid,'name':safe_filename(filename),'kind':kind,'size':len(content)}
 @app.middleware('http')
 async def guard(req,call):
  if req.method not in ('GET','HEAD','OPTIONS'):
   origin=req.headers.get('origin')
   if origin and origin not in ((base,) if prod else (base,str(req.base_url).rstrip('/'))):return JSONResponse({'detail':'Cross-site request rejected'},403)
   try:size=int(req.headers.get('content-length','0'))
   except ValueError:return JSONResponse({'detail':'Invalid content length'},400)
   if size>30*1024*1024:return JSONResponse({'detail':'Request too large'},413)
  response=await call(req)
  response.headers.update({'X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Permissions-Policy':'camera=(self), microphone=(), geolocation=()','Cache-Control':'no-store'})
  ancestors="'self' https://www.bmwccct.co.za https://bmwccct.co.za" if req.url.path=='/public' else "'none'"
  response.headers['Content-Security-Policy']=f"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'; frame-ancestors {ancestors}; object-src 'none'; base-uri 'self'; form-action 'self'"
  if prod:response.headers['Strict-Transport-Security']='max-age=31536000'
  return response
 @app.get('/health')
 def health():
  with store.db() as c:c.execute('SELECT 1').fetchone()
  return {'ok':True,'version':VERSION}
 @app.get('/')
 def index():return FileResponse(ROOT/'static/index.html')
 @app.get('/public')
 def publicpage():return FileResponse(ROOT/'static/index.html')
 @app.get('/verify/{token}')
 def verify(token:str):
  with store.db() as c:
   m=c.execute('SELECT m.*,u.name,u.disabled FROM memberships m JOIN users u ON m.driver_id=u.id WHERE verify_token=?',(token,)).fetchone()
   need(m is not None,'Membership not found',404)
   valid=m['status']=='active' and m['paid'] and not m['disabled'] and date(2027,1,1)<=date.today()<=date(2027,12,31)
   status='VALID' if valid else 'NOT CURRENTLY VALID';name=html.escape(m['name']);number=html.escape(m['member_number'])
  return HTMLResponse(f'<!doctype html><meta name="viewport" content="width=device-width"><link rel="stylesheet" href="/static/style.css"><main class="verification"><div class="wordmark">BMWCCCT<span>.</span></div><p class="eyebrow">RACE SERIES MEMBERSHIP CHECK</p><h1>{status}</h1><h2>{name}</h2><p>{number}</p><p>Season 2027 · 1 January–31 December 2027</p><p>Membership verification only. This is not an MSA competition licence or permission to race.</p></main>')
 @app.get('/api/files/{fid}')
 def download(fid:str,req:Request):
  with store.db() as c:
   u,_=get_auth(c,req);f=c.execute('SELECT * FROM files WHERE id=?',(fid,)).fetchone();need(f is not None,'File not found',404);own(u,f['owner_id']);store.audit(c,u['id'],'private_file_read',fid)
   content=store.fernet.decrypt((store.files/fid).read_bytes());inline=f['kind']=='portrait'
   return Response(content,media_type=f['mime'],headers={'Content-Disposition':('inline' if inline else 'attachment')+'; filename="'+f['name'].replace('"','')+'"'})
 @app.get('/api/card-qr')
 def qr(req:Request):
  with store.db() as c:
   u,_=get_auth(c,req);m=membership(c,u['id']);need(m and m['status']=='active','Membership is not activated',403)
   img=qrcode.make(base+'/verify/'+m['verify_token'],image_factory=qrcode.image.svg.SvgPathImage);b=io.BytesIO();img.save(b);return Response(b.getvalue(),media_type='image/svg+xml')
 @app.api_route('/api/{path:path}',methods=['GET','POST','PATCH','DELETE'])
 async def api(path:str,req:Request):
  try:
   with store.db() as c:
    u,s=get_auth(c,req,False)
    if path=='bootstrap' and req.method=='GET':
     tok=None
     if not s:tok,csrf_token=new_session(c);s={'csrf':csrf_token}
     result={'version':VERSION,'user':public_user(u) if u else None,'csrf':s['csrf'],'fields':PROFILE_FIELDS,'car_fields':CAR_FIELDS,'declaration':DECLARATION,'bank':BANK,'privacy_notice':os.getenv('PRIVACY_NOTICE_URL',''),'production':prod}
     response=JSONResponse(result)
     if tok:cookie(response,tok)
     return response
    if path=='public' and req.method=='GET':
     published=store.published(c);return {'events':[safepublic(x) for x in published],'standings':standings([p for p in published if p['season']==2027],store.rules(c,2027))}
    if req.method!='GET':csrf(req,s)
    if u and u['must_change'] and path not in ('password','logout'):raise HTTPException(403,'Change your temporary password first')
    if path=='upload' and req.method=='POST':
     need(u,'Please sign in',401);form=await req.form();f=form.get('file');need(f is not None and getattr(f,'filename',None),'Choose a file');content=await f.read(26*1024*1024);return file_store(c,u,clean(form.get('kind')),content,f.filename)
    if path=='admin/import' and req.method=='POST':
     admin(u);form=await req.form();f=form.get('file');need(f is not None and getattr(f,'filename',None),'Choose a timing file')
     content=await f.read(12*1024*1024+1);parsed=parse(content,f.filename);e=store.event(c,int(form.get('event_id')));need(e,'Event not found',404)
     kind=clean(form.get('session') or parsed['session']);need(kind in ('Q','R1','R2'),'Choose a session')
     need(not parsed.get('session') or kind==parsed['session'],'PDF session differs from the selected session')
     need(not parsed.get('date') or parsed['date']==e['event_date'],'Timing file date differs from selected event; choose the correct event')
     need(1<=int(form.get('scheduled_laps') or parsed['scheduled_laps'] or e['planned_laps'])<=999,'Scheduled laps must be 1–999')
     for row in parsed['rows']:
      # Never silently bind a new driver just because a number was reused.
      matches=[a for a in e['entries'] if a['number']==row['number'] and re.sub(r'\W','',a['name']).casefold()==re.sub(r'\W','',row['name']).casefold()]
      row['entry_id']=matches[0]['id'] if len(matches)==1 else None
     e['sessions'][kind]={'rows':parsed['rows'],'scheduled_laps':int(form.get('scheduled_laps') or parsed['scheduled_laps'] or e['planned_laps']),'source_name':safe_filename(f.filename),'source_hash':hashlib.sha256(content).hexdigest(),'source_provisional':parsed['source_provisional'],'imported_at':now()}
     store.save_event(c,e,u['id'],'timing_import');return eventview(c,store.event(c,e['id']))
    data=await req.json() if req.method!='GET' and req.headers.get('content-type','').startswith('application/json') else {}
    if path=='login' and req.method=='POST':
     email=clean(data.get('email'),200).lower();key=hashlib.sha256(((req.client.host if req.client else '')+'|'+email).encode()).hexdigest();c.execute('DELETE FROM attempts WHERE at<?',(time.time()-3600,));n=c.execute('SELECT count(*) FROM attempts WHERE key=? AND at>?',(key,time.time()-900)).fetchone()[0]
     need(n<10,'Too many attempts. Try again later.',429);row=c.execute('SELECT * FROM users WHERE email=?',(email,)).fetchone()
     okay=row and not row['disabled'] and password_ok(clean(data.get('password'),256),row['password_hash'])
     ctr=None
     if okay and row['role']=='admin' and (prod or row['totp_secret']):ctr=totp_check(store.unseal(row['totp_secret']) if row['totp_secret'] else '',clean(data.get('otp')),row['last_totp']);okay=ctr is not None
     if not okay:
      c.execute('INSERT INTO attempts VALUES(?,?)',(key,time.time()));c.commit();raise HTTPException(401,'Invalid credentials or authenticator code')
     if ctr is not None:c.execute('UPDATE users SET last_totp=? WHERE id=?',(ctr,row['id']))
     c.execute('DELETE FROM sessions WHERE token_hash=?',(token_hash(req.cookies.get('bmw_session','')),));token,cr=new_session(c,row['id']);store.audit(c,row['id'],'login');response=JSONResponse({'ok':True,'csrf':cr});cookie(response,token);return response
    if path=='register' and req.method=='POST':
     email=clean(data.get('email'),200).lower();name=clean(data.get('name'),120);need(email_valid(email) and len(name)>2,'Enter your name and a valid email')
     need(data.get('privacy_agreed') is True,'Accept the privacy notice to register')
     c.execute('INSERT INTO users(email,name,password_hash) VALUES(?,?,?)',(email,name,password_hash(str(data.get('password','')))));return {'ok':True,'message':'Account created. Sign in to complete registration; administrator approval is required to race.'}
    need(u is not None,'Please sign in',401)
    if u['must_change'] and path not in ('password','logout'):raise HTTPException(403,'Change your temporary password first')
    if path=='logout' and req.method=='POST':
     c.execute('DELETE FROM sessions WHERE token_hash=?',(token_hash(req.cookies.get('bmw_session','')),));response=JSONResponse({'ok':True});response.delete_cookie('bmw_session',path='/');return response
    if path=='password' and req.method=='POST':
     need(password_ok(str(data.get('current','')),u['password_hash']),'Current password incorrect',403);p=password_hash(str(data.get('password','')));c.execute('UPDATE users SET password_hash=?,must_change=0 WHERE id=?',(p,u['id']));c.execute('DELETE FROM sessions WHERE user_id=?',(u['id'],));store.audit(c,u['id'],'password_changed');return {'ok':True,'relogin':True}
    if path=='lounge' and req.method=='GET':
     pubs=store.published(c,2027);log=standings(pubs,store.rules(c,2027));standing=next((x for x in log if x['driver_id']==u['id']),None)
     return {'user':public_user(u),'profile':store.profile(c,u['id']),'cars':store.cars(c,u['id']),'membership':membership(c,u['id']),'outstanding':requirements(c,u),'tasks':[dict(x) for x in c.execute('SELECT * FROM tasks WHERE driver_id=? ORDER BY id DESC',(u['id'],))],'cases':[caseview(c,r,u) for r in c.execute('SELECT * FROM cases WHERE owner_id=? ORDER BY id DESC',(u['id'],))],'standing':standing,'published':[safepublic(x) for x in pubs],'events':[dict(x) for x in c.execute('SELECT id,label,event_date FROM events ORDER BY event_date DESC')]}
    if path=='profile' and req.method=='POST':
     old=store.profile(c,u['id']);p={k:clean(data.get(k)) for k,*_ in PROFILE_FIELDS};p['email']=u['email'];p['rules_agreed']=bool(data.get('rules_agreed'));p['rules_version']=clean(data.get('rules_version') or 'Awaiting season rules',200)
     need(not p.get('dob') or date.fromisoformat(p['dob'])<=date.today(),'Date of birth cannot be in the future')
     p['declaration']=DECLARATION;p['accepted_at']=old.get('accepted_at') if old.get('rules_agreed') and old.get('rules_version')==p['rules_version'] else now() if p['rules_agreed'] else None
     c.execute('INSERT INTO profiles(driver_id,cipher) VALUES(?,?) ON CONFLICT(driver_id) DO UPDATE SET cipher=excluded.cipher,updated_at=CURRENT_TIMESTAMP',(u['id'],store.seal(p)));store.audit(c,u['id'],'profile_saved');return {'ok':True}
    if path=='cars' and req.method=='POST':
     obj={k:clean(data.get(k),180) for k,*_ in CAR_FIELDS};need(obj['number'] and obj['model'],'Number and model are required');need(obj['proposed_class'] in list('ABCDEF'),'Choose proposed class');id=data.get('id')
     if id:
      old=c.execute('SELECT * FROM cars WHERE id=?',(int(id),)).fetchone();need(old,'Car not found',404);own(u,old['driver_id']);obj['approved_class']=json.loads(old['payload']).get('approved_class');c.execute('UPDATE cars SET payload=? WHERE id=?',(json.dumps(obj),id))
     else:
      obj['approved_class']=None;active=not c.execute('SELECT 1 FROM cars WHERE driver_id=? AND archived=0',(u['id'],)).fetchone();id=c.execute('INSERT INTO cars(driver_id,payload,current) VALUES(?,?,?)',(u['id'],json.dumps(obj),int(active))).lastrowid
     store.audit(c,u['id'],'car_saved',id);return {'ok':True,'id':id}
    if path=='cars/current' and req.method=='POST':
     car=c.execute('SELECT * FROM cars WHERE id=? AND archived=0',(int(data.get('id')),)).fetchone();need(car,'Car not found',404);own(u,car['driver_id']);c.execute('UPDATE cars SET current=0 WHERE driver_id=?',(car['driver_id'],));c.execute('UPDATE cars SET current=1 WHERE id=?',(car['id'],));return {'ok':True}
    if path=='membership' and req.method=='POST':
     need(data.get('portrait_id') and data.get('proof_id'),'Upload both portrait and proof of payment')
     for key,kind in [('portrait_id','portrait'),('proof_id','payment')]:
      f=c.execute('SELECT * FROM files WHERE id=? AND owner_id=? AND kind=?',(data[key],u['id'],kind)).fetchone();need(f,'Invalid or unowned '+kind+' file',403)
     existing=membership(c,u['id']);need(not existing or existing['status'] not in ('active','pending'),'Application is already active or awaiting review')
     number=f'BMW-RS-27-{u["id"]:05d}';token=secrets.token_urlsafe(32)
     c.execute("INSERT INTO memberships(driver_id,season,portrait_id,proof_id,member_number,verify_token) VALUES(?,2027,?,?,?,?) ON CONFLICT(driver_id,season) DO UPDATE SET portrait_id=excluded.portrait_id,proof_id=excluded.proof_id,status='pending',paid=0,updated_at=CURRENT_TIMESTAMP",(u['id'],data['portrait_id'],data['proof_id'],number,token));store.audit(c,u['id'],'membership_submitted');return {'ok':True}
    if path=='cases' and req.method=='POST':
     need(u['approved'] or u['role']=='admin','Account approval is required to submit cases',403);kind=clean(data.get('kind'));need(kind in ('incident','dispute'),'Choose incident or dispute')
     need(len(clean(data.get('description')))>14 and clean(data.get('location')),'Give location and at least 15 characters of detail')
     ids=data.get('files',[]);need(isinstance(ids,list) and len(ids)<=5,'Maximum 5 evidence files')
     for fid in ids:need(c.execute("SELECT 1 FROM files WHERE id=? AND owner_id=? AND kind='evidence'",(fid,u['id'])).fetchone(),'Evidence file is not yours',403)
     obj={k:clean(data.get(k)) for k in ('subject','description','location','race_session','lap','other_cars','event_date','authority','requested_outcome','video_url')};obj.update(files=ids,messages=[],safety_concern=bool(data.get('safety_concern')))
     if obj['video_url']:need(urlparse(obj['video_url']).scheme=='https','Video links must use HTTPS')
     ref=('INC' if kind=='incident' else 'DSP')+'-'+date.today().strftime('%y%m%d')+'-'+secrets.token_hex(3).upper();eid=int(data['event_id']) if data.get('event_id') else None
     need(not eid or store.event(c,eid),'Event not found',404)
     id=c.execute('INSERT INTO cases(owner_id,kind,event_id,reference,cipher) VALUES(?,?,?,?,?)',(u['id'],kind,eid,ref,store.seal(obj))).lastrowid;store.audit(c,u['id'],'case_submitted',ref);return {'ok':True,'id':id,'reference':ref}
    if path=='tasks/reply' and req.method=='POST':
     task=c.execute('SELECT * FROM tasks WHERE id=?',(int(data.get('id')),)).fetchone();need(task,'Task not found',404);own(u,task['driver_id']);fid=data.get('file_id')
     if fid:need(c.execute('SELECT 1 FROM files WHERE id=? AND owner_id=?',(fid,u['id'])).fetchone(),'File not yours',403)
     c.execute("UPDATE tasks SET reply=?,file_id=?,status='Submitted' WHERE id=?",(clean(data.get('reply')),fid,task['id']));return {'ok':True}
    if path=='results' and req.method=='GET':
     pubs=store.published(c);return {'events':[safepublic(x) for x in pubs],'standings':standings([x for x in pubs if x['season']==2027],store.rules(c,2027))}
    admin(u)
    if path=='admin/overview' and req.method=='GET':
     members=[]
     for row in c.execute("SELECT * FROM users WHERE role='driver' ORDER BY name"):
      user=dict(row);members.append(dict(public_user(user),cars=store.cars(c,user['id']),membership=membership(c,user['id']),outstanding=requirements(c,user)))
     events=[store.event(c,r[0]) for r in c.execute('SELECT id FROM events ORDER BY event_date DESC')]
     return {'members':members,'events':events,'cases':[caseview(c,x,u) for x in c.execute('SELECT * FROM cases ORDER BY id DESC')],'tasks':[dict(x) for x in c.execute('SELECT * FROM tasks ORDER BY id DESC')],'rules':store.rules(c,2027),'audit':[dict(x) for x in c.execute('SELECT * FROM audit ORDER BY id DESC LIMIT 80')]}
    if path=='admin/member' and req.method=='GET':
     did=int(req.query_params.get('id'));user=c.execute('SELECT * FROM users WHERE id=?',(did,)).fetchone();need(user,'Driver not found',404);store.audit(c,u['id'],'private_profile_read',did);return {'user':public_user(user),'profile':store.profile(c,did),'cars':store.cars(c,did),'membership':membership(c,did)}
    if path=='admin/member' and req.method=='POST':
     action=data.get('action');did=int(data.get('id'))
     need(c.execute("SELECT 1 FROM users WHERE id=? AND role='driver'",(did,)).fetchone(),'Driver not found',404)
     if action=='approve':c.execute('UPDATE users SET approved=1,disabled=0 WHERE id=?',(did,))
     elif action=='disable':
      c.execute('UPDATE users SET disabled=1 WHERE id=?',(did,));c.execute('DELETE FROM sessions WHERE user_id=?',(did,));c.execute("UPDATE memberships SET status='revoked' WHERE driver_id=?",(did,))
     elif action=='reactivate':c.execute('UPDATE users SET disabled=0 WHERE id=?',(did,))
     else:raise ValueError('Unknown member action')
     store.audit(c,u['id'],'member_'+action,did);return {'ok':True}
    if path=='admin/create-driver' and req.method=='POST':
     email=clean(data.get('email'),200).lower();need(email_valid(email),'Valid email required');name=clean(data.get('name'),120);need(name,'Name required')
     id=c.execute('INSERT INTO users(email,name,password_hash,approved,must_change) VALUES(?,?,?,1,1)',(email,name,password_hash(str(data.get('password',''))))).lastrowid;store.audit(c,u['id'],'driver_created',id);return {'ok':True,'id':id}
    if path=='admin/membership' and req.method=='POST':
     mid=int(data.get('id'));m=c.execute('SELECT * FROM memberships WHERE id=?',(mid,)).fetchone();need(m,'Membership not found',404);state=data.get('status');need(state in ('active','rejected','revoked'),'Invalid membership state')
     if state=='active':
      need(data.get('payment_verified') is True,'Confirm funds received; upload alone is not proof of payment');need(m['portrait_id'] and m['proof_id'],'Both uploads are required');usr=c.execute('SELECT * FROM users WHERE id=?',(m['driver_id'],)).fetchone();need(not usr['disabled'],'Driver access is disabled')
      c.execute('UPDATE users SET approved=1 WHERE id=?',(m['driver_id'],))
     c.execute('UPDATE memberships SET status=?,paid=?,note=?,decided_by=?,updated_at=CURRENT_TIMESTAMP WHERE id=?',(state,1 if state=='active' else m['paid'],clean(data.get('note')),u['id'],mid));store.audit(c,u['id'],'membership_'+state,mid);return {'ok':True}
    if path=='admin/task' and req.method=='POST':
     if data.get('id'):
      need(data.get('status') in ('Open','Submitted','Closed'),'Invalid task status');c.execute('UPDATE tasks SET status=? WHERE id=?',(data['status'],int(data['id'])))
     else:
      did=int(data.get('driver_id'));need(c.execute('SELECT 1 FROM users WHERE id=?',(did,)).fetchone(),'Driver not found');need(clean(data.get('title')),'Title required');c.execute('INSERT INTO tasks(driver_id,title,note) VALUES(?,?,?)',(did,clean(data['title'],180),clean(data.get('note'))))
     store.audit(c,u['id'],'task_changed',data.get('id',data.get('driver_id')));return {'ok':True}
    if path=='admin/case' and req.method=='POST':
     row=c.execute('SELECT * FROM cases WHERE id=?',(int(data.get('id')),)).fetchone();need(row,'Case not found',404);obj=store.unseal(row['cipher']);state=clean(data.get('status') or row['status']);need(state in ('Submitted','Under review','Awaiting driver','Referred to CoC','Closed'),'Invalid case status')
     if clean(data.get('note')):obj.setdefault('messages',[]).append({'at':now(),'author':u['name'],'text':clean(data['note']),'internal':bool(data.get('internal'))})
     if data.get('related_case_id'):obj['related_case_id']=int(data['related_case_id'])
     c.execute('UPDATE cases SET status=?,cipher=? WHERE id=?',(state,store.seal(obj),row['id']));store.audit(c,u['id'],'case_updated',row['reference']);return {'ok':True}
    if path=='admin/rules' and req.method=='POST':
     season=int(data.get('season',2027));r=deepcopy(RULES);r.update({k:data[k] for k in RULES if k in data})
     need(bool(clean(r['source'])) and bool(clean(r['policy_note'])),'Record source/version and committee policy approval')
     need(int(r['minimum_starters'])>0 and int(r['scheduled_events'])>0,'Invalid rules values');need(0<float(r['fraction'])<=1,'Invalid distance fraction')
     values=[r['thresholds'][x] for x in 'BCDEF'];need(all(isinstance(x,(int,float)) and x>0 for x in values) and values==sorted(values),'Invalid class thresholds')
     need(r['guest_policy']=='exclude_and_close_up' and r['trophy_basis']=='race_points','Unsupported policy: record an official event adjustment instead')
     for key in ('large','small'):
      need(isinstance(r[key],list) and len(r[key])==(8 if key=='large' else 3) and all(isinstance(n,int) and 0<=n<=1000 for n in r[key]),'Invalid points table')
     for key in ('qual_bonus','race_bonus','debrief_bonus'):
      need(isinstance(r[key],int) and 0<=r[key]<=100,'Invalid bonus value')
     r['approved']=data.get('approved') is True;r['approved_by']=u['id'];r['approved_at']=now();c.execute('INSERT INTO rules VALUES(?,?) ON CONFLICT(season) DO UPDATE SET payload=excluded.payload',(season,json.dumps(r)));c.execute('UPDATE events SET published_revision=NULL WHERE season=?',(season,));store.audit(c,u['id'],'rules_changed',season);return {'ok':True}
    if path=='admin/event' and req.method=='GET':
     e=store.event(c,int(req.query_params.get('id')));need(e,'Event not found',404);return eventview(c,e)
    if path=='admin/event' and req.method=='POST':
     dt=clean(data.get('event_date'));date.fromisoformat(dt);season=int(dt[:4]);rnd=int(data.get('round_no'));need(rnd>0,'Round must be positive');label=clean(data.get('label'),150);need(label,'Event label required')
     need(1<=int(data.get('planned_laps') or 8)<=999,'Scheduled laps must be 1–999')
     payload={'entries':[],'sessions':{},'attendance':[],'notes':'','planned_laps':int(data.get('planned_laps') or 8),'notices':[],'grid_approvals':{}}
     id=c.execute('INSERT INTO events(season,round_no,event_date,label,payload) VALUES(?,?,?,?,?)',(season,rnd,dt,label,json.dumps(payload))).lastrowid;store.audit(c,u['id'],'event_created',id);return {'ok':True,'id':id}
    if path.startswith('admin/event/') and req.method=='POST':
     e=store.event(c,int(data.get('event_id')));need(e,'Event not found',404);action=path.split('/')[-1]
     if action=='entry':
      did=int(data['driver_id']) if data.get('driver_id') else None;cid=int(data['car_id']) if data.get('car_id') else None
      if did:
       user=c.execute('SELECT * FROM users WHERE id=?',(did,)).fetchone();car=c.execute('SELECT * FROM cars WHERE id=? AND driver_id=?',(cid,did)).fetchone();need(user and car,'Select a registered driver and their car');cp=json.loads(car['payload']);name=user['name'];number=cp['number'];cls=cp.get('approved_class') or cp['proposed_class'];need(not user['disabled'],'Driver is disabled');need(not any(x.get('driver_id')==did for x in e['entries']),'A driver can enter only one car in this round')
      else:name=clean(data.get('name'),120);number=clean(data.get('number'),12);cls=clean(data.get('cls'));need(name and number,'Guest name and number required')
      need(cls in list('ABCDEF'),'Choose class');need(not any(x['number']==number for x in e['entries']),'Race number already used in this event')
      eid=secrets.token_hex(6);ent={'id':eid,'driver_id':did,'car_id':cid,'name':name,'number':number,'cls':cls,'original_class':cls,'guest':not bool(did),'eligible':bool(data.get('eligible')),'identity_reviewed':bool(data.get('identity_reviewed')),'novice_back':bool(data.get('novice_back')),'pitlane':bool(data.get('pitlane')),'non_droppable':False};e['entries'].append(ent)
      for ss in e['sessions'].values():
       for r in ss['rows']:
        if r['number']==number and re.sub(r'\W','',r['name']).casefold()==re.sub(r'\W','',name).casefold():r['entry_id']=eid
     elif action=='entry-review':
      ent=next((x for x in e['entries'] if x['id']==data.get('entry_id')),None);need(ent,'Entry not found');need(clean(data.get('note')),'Record the official eligibility / sanction decision')
      for key in ('eligible','identity_reviewed','novice_back','pitlane','non_droppable'):ent[key]=bool(data.get(key))
      choice=clean(data.get('championship_action') or 'continue');need(choice in ('continue','promote','reset'),'Invalid championship transition')
      ent['championship_action']=choice
      if choice=='promote':ent['promotion']=True
      if choice=='reset':ent['promotion']=False
      ent['review_note']=clean(data['note']);ent['reviewed_by']=u['id']
     elif action=='match':
      ent=next((x for x in e['entries'] if x['id']==data.get('entry_id')),None);need(ent,'Entry not found');kind=data.get('session');ss=e['sessions'].get(kind);need(ss,'Session not found')
      row=next((r for r in ss['rows'] if r['number']==str(data.get('number'))),None);need(row,'Timing row not found');need(not any(r.get('entry_id')==ent['id'] and r is not row for r in ss['rows']),'Driver already matched in this session');row['entry_id']=ent['id'];ent['identity_reviewed']=True
     elif action=='class':
      ent=next((x for x in e['entries'] if x['id']==data.get('entry_id')),None);need(ent,'Entry not found');new=clean(data.get('cls'));need(new in list('ABCDEF'),'Invalid class');need('ABCDEF'.index(new)<'ABCDEF'.index(ent['cls']),'Use this action only for movement to a faster class');need(clean(data.get('note')),'Record written notification / authority reference')
      old=ent['cls'];ent['cls']=new;ent['promotion']=True;e['notices'].append({'at':now(),'entry_id':ent['id'],'from':old,'to':new,'note':clean(data['note'])})
      if ent.get('car_id'):
       car=c.execute('SELECT payload FROM cars WHERE id=?',(ent['car_id'],)).fetchone();cp=json.loads(car[0]);cp['approved_class']=new;c.execute('UPDATE cars SET payload=? WHERE id=?',(json.dumps(cp),ent['car_id']))
      if ent.get('driver_id'):c.execute('INSERT INTO tasks(driver_id,title,note) VALUES(?,?,?)',(ent['driver_id'],'Class change notification',f'{old} to {new}: '+clean(data['note'])))
     elif action=='attendance':
      did=int(data.get('driver_id'));kind=data.get('kind');need(kind in ('briefing','debrief'),'Invalid meeting type');need(c.execute("SELECT 1 FROM users WHERE id=? AND role='driver'",(did,)).fetchone(),'Driver not found')
      if data.get('bonus_approved'):need(clean(data.get('note')),'Record committee approval for an excused bonus')
      e['attendance']=[a for a in e['attendance'] if not(a['driver_id']==did and a['kind']==kind)]
      e['attendance'].append({'driver_id':did,'kind':kind,'present':bool(data.get('present')),'excused':bool(data.get('excused')),'bonus_approved':bool(data.get('bonus_approved')) if kind=='debrief' else False,'note':clean(data.get('note')),'recorded_at':now(),'recorded_by':u['id']})
     elif action=='adjust':
      kind=data.get('session');ss=e['sessions'].get(kind);need(ss,'Session not found');row=next((x for x in ss['rows'] if x['number']==str(data.get('number'))),None);need(row,'Row not found');need(clean(data.get('note')),'Official decision/reference required')
      if 'penalty_seconds' in data:row['penalty_ms']=int(float(data['penalty_seconds'])*1000);need(row['penalty_ms']>=0,'Penalty cannot be negative')
      if data.get('status'):need(data['status'] in ('CLASSIFIED','DNF','DNS','DSQ','NOT CLASSIFIED'),'Invalid status');row['status']=data['status']
      row['decision']=clean(data['note']);row['grid_penalty']=bool(data.get('grid_penalty'))
     elif action=='settings':
      for key in ('single_race_confirmed','planned_laps','overall_winner'): 
       if key in data:e[key]=data[key]
      if data.get('overall_winner'):need(any(x['id']==data['overall_winner'] for x in e['entries']),'Unknown overall winner');need(clean(data.get('note')),'Overall winner requires authority reference');e['overall_winner_note']=clean(data['note'])
     elif action=='grid':
      kind=data.get('session');need(kind in ('R1','R2'),'Grid session required');rows=data.get('rows');need(isinstance(rows,list),'Provide reviewed grid rows')
      ids=[x.get('entry_id') for x in rows];need(len(ids)==len(set(ids)) and set(ids)=={x['id'] for x in e['entries']},'Grid must contain every entry exactly once');need(clean(data.get('note')),'Grid approval note required');need(all(isinstance(r.get('position'),int) and 1<=r['position']<=999 for r in rows) and len({r['position'] for r in rows})==len(rows),'Grid positions must be unique positive integers')
      e['grid_approvals'][kind]={'rows':rows,'approved_by':u['id'],'note':clean(data['note']),'at':now()}
     elif action=='fastest':
      ss=e['sessions'].get(data.get('session'));need(ss,'Session not found');need(clean(data.get('note')),'Official tie decision required');ss.setdefault('fastest_overrides',{})[clean(data.get('cls'))]=data.get('entry_id')
     elif action=='notes':e['notes']=clean(data.get('notes'),12000)
     else:raise ValueError('Unknown event action')
     if action not in ('grid','notes','attendance'):e['grid_approvals']={}
     store.save_event(c,e,u['id'],action);return eventview(c,store.event(c,e['id']))
    if path=='admin/publish' and req.method=='POST':
     e=store.event(c,int(data.get('event_id')));need(e,'Event not found',404);r=store.rules(c,e['season']);sc=score(e,r)
     need(r.get('approved'),'Approve the applicable season rules first',409);
     earlier=c.execute('SELECT e.id FROM events e WHERE e.season=? AND e.round_no<? AND e.published_revision IS NULL AND EXISTS(SELECT 1 FROM publications p WHERE p.event_id=e.id)',(e['season'],e['round_no'])).fetchall()
     need(not earlier,'Review and republish withdrawn earlier rounds before publishing a later round',409)
     previous=standings([p for p in store.published(c,e['season']) if p['round_no']<e['round_no']],r)
     for ent in e['entries']:
      prior=next((p for p in previous if p['driver_id']==ent.get('driver_id')),None)
      if prior and prior['cls']!=ent['cls']:
       faster='ABCDEF'.index(ent['cls'])<'ABCDEF'.index(prior['cls'])
       need((faster and ent.get('promotion')) or (not faster and ent.get('championship_action')=='reset'),'Driver #'+ent['number']+' changed championship class: record carryover/reset authority in Entry review',409)
     need(not sc['blockers'],'Cannot publish: '+'; '.join(sc['blockers']),409);need(clean(data.get('review_note')),'Enter administrator review / decision note')
     need(data.get('review_confirmed') is True,'Confirm source, eligibility, distance, decisions and awards have been checked')
     if sc['issues']:need(data.get('exceptions_reviewed') is True,'Acknowledge every review item before publishing',409)
     snapshot={k:e[k] for k in ('id','season','round_no','event_date','label','revision')};snapshot.update(scores=sc,rules_version=r['version'],published_at=now(),review_note=clean(data['review_note']),grids=e.get('grid_approvals',{}))
     c.execute('INSERT OR REPLACE INTO publications(event_id,revision,payload,created_by) VALUES(?,?,?,?)',(e['id'],e['revision'],json.dumps(snapshot),u['id']));c.execute('UPDATE events SET published_revision=revision WHERE id=?',(e['id'],));store.audit(c,u['id'],'published',e['id']);return {'ok':True,'revision':e['revision']}
    if path=='admin/unpublish' and req.method=='POST':
     id=int(data.get('event_id'));e=store.event(c,id);need(e,'Event not found',404);c.execute('UPDATE events SET published_revision=NULL WHERE season=? AND round_no>=?',(e['season'],e['round_no']));store.audit(c,u['id'],'unpublished',id);return {'ok':True}
    if path=='admin/debrief' and req.method=='GET':
     id=int(req.query_params.get('id'));e=store.event(c,id);need(e,'Event not found',404);rows=c.execute('SELECT * FROM cases WHERE event_id=? ORDER BY id',(id,)).fetchall()
     # This output is explicitly private; a shareable summary excludes case narratives.
     return {'event':eventview(c,e),'cases':[caseview(c,x,u) for x in rows],'shareable':{'event':e['label'],'date':e['event_date'],'scores':safepublic({'scores':score(e,store.rules(c,e['season']))})['scores'],'incident_count':sum(x['kind']=='incident' for x in rows),'dispute_count':sum(x['kind']=='dispute' for x in rows)}}
    raise HTTPException(404,'Endpoint not found')
  except sqlite3.IntegrityError:return JSONResponse({'detail':'Duplicate record or invalid reference. Nothing was saved.'},409)
  except (ValueError,TypeError,KeyError) as err:return JSONResponse({'detail':str(err)[:500]},400)
 app.mount('/static',StaticFiles(directory=ROOT/'static'),name='static')
 return app
