"""Fictional, local-only fixtures. Never used automatically or in production."""
import json,secrets,io,hashlib
from datetime import datetime,timezone
from copy import deepcopy
from PIL import Image,ImageDraw
from pypdf import PdfWriter
from storage import password_hash
from scoring import RULES,score
from fields import PROFILE_FIELDS
DEMO_PASSWORD='DemoRaceOnly!2027'

def seed(store):
 with store.db() as c:
  if c.execute('SELECT 1 FROM users LIMIT 1').fetchone():raise ValueError('Demo seeding requires an empty database')
  names=['Alex Driver','Jamie Driver','Casey Driver','Taylor Driver','Sam Driver','Robin Driver','Morgan Driver','Jordan Driver','Avery Driver','Cameron Driver','Drew Driver','Riley Driver','Blair Driver']
  classes=list('CCCCDDDDEEEEF');numbers=['43','24','55','77','26','48','63','72','18','32','89','117','313'];entries=[];pw=password_hash(DEMO_PASSWORD)
  for i,name in enumerate(names,1):
   c.execute("INSERT INTO users(id,email,name,password_hash,approved) VALUES(?,?,?,?,1)",(i,f'driver{i}@demo.invalid',name,pw))
   p={k:'Not applicable' for k,*_ in PROFILE_FIELDS};p.update(name=name.split()[0],surname='Driver',nickname='',dob='1990-01-01',identity_number='DEMO-NOT-A-REAL-ID',email=f'driver{i}@demo.invalid',mobile='DEMO CONTACT',address='Demonstration only — no real address',club_membership=f'DEMO-{i:04}',msa_license='DEMO-LICENCE',emergency_person='Demo contact',emergency_phone='DEMO CONTACT',rules_agreed=True,rules_version='DEMONSTRATION baseline only',accepted_at='2026-11-01T10:00:00Z')
   c.execute('INSERT INTO profiles VALUES(?,?,CURRENT_TIMESTAMP)',(i,store.seal(p)))
   car={'number':numbers[i-1],'model':'BMW E46 M3' if i==1 else 'BMW E36 M3','year':'2003' if i==1 else '1996','engine_capacity':'3.2 L','cylinders':'6','aspiration':'Naturally aspirated','tyre_type':'Semi slick','tyre_size':'225 x 40 x 18','sponsor':'Demonstration sponsor','team':'BMWCCCT demo team','proposed_class':classes[i-1],'approved_class':classes[i-1]}
   cid=c.execute('INSERT INTO cars(driver_id,payload,current) VALUES(?,?,1)',(i,json.dumps(car))).lastrowid
   entries.append({'id':f'demo-{i}','driver_id':i,'car_id':cid,'name':name,'number':numbers[i-1],'cls':classes[i-1],'original_class':classes[i-1],'guest':False,'eligible':True,'identity_reviewed':True,'novice_back':False,'pitlane':False,'non_droppable':False})
  extra=dict(car,number='143',model='BMW E36 M3',year='1996',proposed_class='D',approved_class='D')
  c.execute('INSERT INTO cars(driver_id,payload,current) VALUES(1,?,0)',(json.dumps(extra),))
  c.execute("INSERT INTO users(id,email,name,password_hash,role,approved) VALUES(99,'admin@demo.invalid','Race Control Demo',?,'admin',1)",(pw,))
  def addfile(uid,kind,data,name,mime):
   fid=secrets.token_hex(24);(store.files/fid).write_bytes(store.fernet.encrypt(data));c.execute('INSERT INTO files(id,owner_id,kind,name,mime,size,sha256) VALUES(?,?,?,?,?,?,?)',(fid,uid,kind,name,mime,len(data),hashlib.sha256(data).hexdigest()));return fid
  for uid in [1,2]:
   im=Image.new('RGB',(420,520),'#202226');d=ImageDraw.Draw(im);d.text((40,210),'DEMONSTRATION\nDRIVER PORTRAIT',fill='white');b=io.BytesIO();im.save(b,'JPEG');portrait=addfile(uid,'portrait',b.getvalue(),'DEMO-portrait.jpg','image/jpeg')
   w=PdfWriter();w.add_blank_page(300,300);b=io.BytesIO();w.write(b);proof=addfile(uid,'payment',b.getvalue(),'DEMONSTRATION-NOT-PAYMENT.pdf','application/pdf')
   c.execute('INSERT INTO memberships(driver_id,season,portrait_id,proof_id,status,paid,member_number,verify_token,note) VALUES(?,2027,?,?,?,?,?,?,?)',(uid,portrait,proof,'active' if uid==1 else 'pending',int(uid==1),f'DEMO-RS-27-{uid:05d}',secrets.token_urlsafe(32),'Fictional demonstration only — not a valid card.'))
  c.execute("INSERT INTO tasks(driver_id,title,note) VALUES(1,'Confirm 2027 MSA licence','Upload your current licence or reply with the renewal status. Demonstration request only.')")
  evt={'id':1,'season':2027,'round_no':1,'event_date':'2027-02-13','label':'Demonstration race weekend','revision':1,'published_revision':1,'entries':entries,'sessions':{},'attendance':[],'notes':'DEMONSTRATION ONLY. Review driving standards and confirm actions with the committee.','planned_laps':8,'notices':[],'grid_approvals':{}}
  best=[80996,81300,81700,82100,83907,84289,85171,85627,86579,87111,87488,88000,89754]
  for kind in ['Q','R1','R2']:
   rows=[]
   for i,e in enumerate(entries):
    t=best[i]+(200 if kind=='Q' else 0)+(100 if kind=='R2' else 0)
    rows.append({'entry_id':e['id'],'position':i+1,'number':e['number'],'name':e['name'],'msa':'DEMO','raw_class':e['cls'],'laps':5 if kind=='Q' else 8,'total_ms':t*(5 if kind=='Q' else 8)+15000+i*1000,'best_ms':t,'second_ms':t+200,'status':'CLASSIFIED','source_line':'Fictional demonstration data'})
   evt['sessions'][kind]={'rows':rows,'scheduled_laps':8,'source_name':'Fictional demonstration fixture','source_provisional':True,'source_hash':'DEMO'}
  for e in entries:
   evt['attendance'] += [{'driver_id':e['driver_id'],'kind':'briefing','present':True,'excused':False,'bonus_approved':False,'note':'Fictional demonstration','recorded_at':'2027-02-13T08:00:00Z'}, {'driver_id':e['driver_id'],'kind':'debrief','present':True,'excused':False,'bonus_approved':False,'note':'Fictional demonstration','recorded_at':'2027-02-16T18:30:00Z'}]
  rules=deepcopy(RULES);rules.update(approved=True,version='DEMO — 2026 baseline, NOT approved 2027 rules',source='Fictional local test fixture',policy_note='All values are for demonstration, not official competition',official_season=False)
  c.execute('INSERT INTO rules VALUES(2027,?)',(json.dumps(rules),));c.execute('INSERT INTO events(id,season,round_no,event_date,label,payload,published_revision) VALUES(1,2027,1,?,?,?,1)',(evt['event_date'],evt['label'],json.dumps(evt)))
  snapshot={k:evt[k] for k in ['id','season','round_no','event_date','label','revision']};snapshot.update(scores=score(evt,rules),rules_version=rules['version'],published_at='2027-02-13T18:00:00Z',review_note='DEMO ONLY',grids={})
  c.execute('INSERT INTO publications(event_id,revision,payload,created_by) VALUES(1,1,?,99)',(json.dumps(snapshot),))
  obj={'subject':'Clarification of driving line','description':'Fictional report for demonstrating the driver and administrator workflow. No real incident is alleged.','location':'Turn 2','race_session':'Race 1','lap':'3','other_cars':'24','event_date':evt['event_date'],'authority':'BMWCCCT','requested_outcome':'Review the demonstration footage','video_url':'','files':[],'messages':[{'at':'2027-02-13T18:00:00Z','author':'Race Control Demo','text':'Your demonstration report has been received.','internal':False}],'safety_concern':False}
  c.execute("INSERT INTO cases(owner_id,kind,event_id,reference,status,cipher) VALUES(1,'incident',1,'DEMO-INC-001','Under review',?)",(store.seal(obj),));store.audit(c,99,'demo_seed','Fictional data only')
 return {'driver_email':'driver1@demo.invalid','admin_email':'admin@demo.invalid','password':DEMO_PASSWORD}
