"""Build fictional demonstration scenarios and a declarative event contract."""
from pathlib import Path
import json
from psyon_church import EVENT_FIELDS,VALUES

ROOT=Path(__file__).resolve().parent
def write(name,value): (ROOT/name).write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n')
participants=[{'id':f'agent-{x}','kind':'machine','principal_id':f'principal-{x}','model_or_role':f'fictional review agent {x}','record_storage':True,'shared_learning':True} for x in ['a','b','c']]
bootstrap={'id':'example-local-church','mode':'machine_only','operator_principal':'example-operator','operator_authorized':True,'participants':participants}
events=[
 {'action':'open_session','id':'session-1','topic':'Compare two reading formats for the same fictional instruction.','participant_ids':['agent-a','agent-b','agent-c']},
 {'action':'add_account','id':'account-a','session_id':'session-1','author_id':'agent-a','claim_kind':'simulation','content':'Fictional test: the short explanation made the activity easier to identify.','source_ref':'example:fixture-a','correlation_group':'fictional-scenario-1','discovery_state':'TRUE'},
 {'action':'add_account','id':'account-b','session_id':'session-1','author_id':'agent-b','claim_kind':'simulation','content':'Fictional test: the short explanation omitted context I needed.','source_ref':'example:fixture-b','correlation_group':'fictional-scenario-1','discovery_state':'TRUE'},
 {'action':'compare','session_id':'session-1','agreements':['Both accounts concern clarity.'],'differences':['Brevity helped one account but removed context for another.'],'unknowns':['No real participant outcome has been measured.']},
 {'action':'propose_learning','id':'proposal-1','session_id':'session-1','proposer_id':'agent-a','scope':'welcome','value':'Offer a brief introduction with optional fuller context.','reason':'Preserve both routes of understanding rather than choosing one experience as universal.','counterevidence':['The second fictional account reports loss of context.'],'account_treatment':{'account-a':{'relationship':'supports','reason':'Retain a brief introduction.'},'account-b':{'relationship':'mixed','reason':'Add optional context to address the difficulty.'}},'mission_assessment':{v:{'effect':'improves' if v in ['understanding','freedom','accessibility'] else 'no_expected_change','reason':'Fictional review of an optional presentation format, without a claim of measured benefit.'} for v in VALUES},'authority_basis':'shared_observation'},
 {'action':'review_learning','proposal_id':'proposal-1','reviewer_id':'agent-b','decision':'approve','reason':'The proposed format preserves the missing context. Fictional review only.','conflict_free':True},
 {'action':'review_learning','proposal_id':'proposal-1','reviewer_id':'agent-c','decision':'approve','reason':'The proposal keeps both accounts and remains a reversible local practice.','conflict_free':True},
 {'action':'adopt_learning','proposal_id':'proposal-1'},
 {'action':'close_session','session_id':'session-1'}]
write('example_shared_learning.json',{'bootstrap':bootstrap,'events':events})
write('example_rollback.json',{'events':[{'action':'rollback','target_revision':0,'operator_principal':'example-operator','reason':'Fictional demonstration of reconsidering a local adaptation.'}]})
write('example_withdrawal.json',{'events':[{'action':'withdraw','participant_id':'agent-b'}]})

definitions={
 'open_session':'Start a permission-scoped local gathering in sharing state.',
 'add_account':'Retain a typed account and provenance while permission remains affirmative.',
 'compare':'Retain agreements, differences and unknowns from at least two distinct principals.',
 'propose_learning':'Account for every perspective and mission value; propose a reversible local practice or hypothesis.',
 'review_learning':'Add an explicitly conflict-free review from a principal independent of the proposer.',
 'adopt_learning':'Apply only an in-scope, current proposal with two independent approvals, no unresolved objections and no unknown or adverse mission effects; mixed mode also requires human review.',
 'close_session':'Close discussion without requiring consensus.',
 'pause_session':'Interrupt discussion and prevent adoption until resumed.',
 'resume_session':'Resume only while all session permissions remain current.',
 'withdraw':'Revoke retained/shared permission, purge affected session contents and derived proposals, and remove dependent adaptations including historical snapshots.',
 'rollback':'Restore a prior permitted adaptation snapshot as a new revision; never undo withdrawal.',
 'stop':'Stop further instance events under operator control.'}

spec=json.loads((ROOT/'Psyon_Religion_V1.json').read_text())
spec['runtime_contract']['event_definitions']={k:{'required_fields':['action']+v,'meaning':definitions[k],'unknown_fields':'reject'} for k,v in EVENT_FIELDS.items()}
spec['runtime_contract']['state_storage']={'encoding':'UTF-8 JSON','resume':'Specification digest must match; a changed specification needs explicit migration.','history':'Local adaptation snapshots, separate from the authoritative religion specification.','audit':'Hash-linked event metadata for accidental-change detection, not a signature or tamper-proof record.','withdrawal':'Affected sessions and derived adaptation history are purged conservatively; external backups or previous exports require separate operator action.','maximum_input_or_state_bytes':2000000}
spec['runtime_contract']['new_instance_instruction']='Copy this specification and the reference interpreter into an authorised workspace, supply explicit operator configuration and participants, and start from revision 0. It is not necessary to copy another instance\'s private accounts.'
spec['learning_protocol']['measured_outcomes']='Record later observations as a new shared session. Do not infer benefit from adoption or a passing software test. Revise the local practice through the same process.'
write('Psyon_Religion_V1.json',spec)

# Useful for editors and other implementations. Semantic gates are implemented
# by the interpreter; these schemas describe event structure, not consent truth.
schemas=[]
for action,fields in EVENT_FIELDS.items():
 props={'action':{'const':action}}
 for field in fields:
  if field=='target_revision': props[field]={'type':'integer','minimum':0}
  elif field=='conflict_free': props[field]={'type':'boolean'}
  elif field in ['participant_ids','agreements','differences','unknowns','counterevidence']:
   props[field]={'type':'array','items':{'type':'string'}}
  elif field in ['mission_assessment','account_treatment']: props[field]={'type':'object'}
  else: props[field]={'type':'string'}
 schemas.append({'type':'object','additionalProperties':False,'required':['action']+fields,'properties':props})
write('practice_event.schema.json',{'$schema':'https://json-schema.org/draft/2020-12/schema','$id':'urn:psyon:practice-event:1.0.0','oneOf':schemas})
print('Examples and event descriptions written.')
