"""Bounded local Psyon shared-learning interpreter. No network or external actions.

Caller identity, operator authority and permissions are supplied assertions.
This is a reference implementation, not production authentication or consent.
"""
from __future__ import annotations
import argparse
import copy
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path

VERSION = '1.0.0'
VALUES = ('care','belonging','dignity','respect','freedom','understanding','accountability','peace')
SCOPES = ('welcome','accessibility','session_format','reflection_prompts','learning_hypotheses')
EVENT_FIELDS = {
 'open_session': ['id','topic','participant_ids'],
 'add_account': ['id','session_id','author_id','claim_kind','content','source_ref','correlation_group','discovery_state'],
 'compare': ['session_id','agreements','differences','unknowns'],
 'propose_learning': ['id','session_id','proposer_id','scope','value','reason','counterevidence','account_treatment','mission_assessment','authority_basis'],
 'review_learning': ['proposal_id','reviewer_id','decision','reason','conflict_free'],
 'adopt_learning': ['proposal_id'],
 'close_session': ['session_id'],
 'pause_session': ['session_id'],
 'resume_session': ['session_id'],
 'withdraw': ['participant_id'],
 'rollback': ['target_revision','operator_principal','reason'],
 'stop': ['operator_principal','reason'],
}

class Rejected(ValueError): pass

def require(condition, message):
    if not condition: raise Rejected(message)

def canonical(value):
    return json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False)

def digest(value): return hashlib.sha256(canonical(value).encode()).hexdigest()

def strict_json(path):
    def pairs(items):
        obj={}
        for key,value in items:
            require(key not in obj,'Duplicate JSON key: '+key)
            obj[key]=value
        return obj
    p=Path(path)
    require(p.stat().st_size<=2_000_000,'Input exceeds 2 MB.')
    def invalid(value): raise Rejected('Non-finite JSON number: '+value)
    return json.loads(p.read_text(encoding='utf-8'),object_pairs_hook=pairs,parse_constant=invalid)

def nonempty(value): return isinstance(value,str) and bool(value.strip()) and len(value)<=20000

def exact(obj,keys):
    require(isinstance(obj,dict) and set(obj)==set(keys),'Unexpected or missing fields: '+str(keys))

def texts(value): return isinstance(value,list) and all(isinstance(x,str) and len(x)<=20000 for x in value)

class Church:
    def __init__(self,spec,bootstrap):
        self.spec=copy.deepcopy(spec)
        rules=spec['runtime_contract']
        require(rules['network_enabled'] is False and rules['external_actions_enabled'] is False,'External capabilities are not supported.')
        require(set(rules['local_change_scopes'])==set(SCOPES),'Unrecognised adaptation scope configuration.')
        require(rules['independent_reviewers_required']==2,'This runtime requires two independent reviews.')
        require(rules['mixed_adoption_requires_human_review'] is True,'Mixed-mode human review cannot be disabled.')
        require(set(rules['events'])==set(EVENT_FIELDS),'Event configuration mismatch.')
        labels=[x['label'] for x in spec['emotional_model']['core_states']]
        require(len(labels)==4 and set(labels)=={'HAPPY','ANGER','SADNESS','OVERWHELMED'},'The V1 core states must remain distinct and exclude fear.')
        require(spec['theology']['epistemic_kind']=='theological_belief_not_an_empirical_finding','Theology must not be relabelled as an empirical finding.')
        exact(bootstrap,['id','mode','operator_principal','operator_authorized','participants'])
        require(bootstrap['operator_authorized'] is True,'An explicit operator authorisation is required.')
        require(nonempty(bootstrap['id']) and nonempty(bootstrap['operator_principal']),'Instance and operator IDs are required.')
        require(bootstrap['mode'] in ['machine_only','mixed'],'Unknown mode.')
        require(isinstance(bootstrap['participants'],list) and 2<=len(bootstrap['participants'])<=100,'Supply 2 to 100 participants.')
        participants={}
        for p in bootstrap['participants']:
            exact(p,['id','kind','principal_id','model_or_role','record_storage','shared_learning'])
            require(all(nonempty(p[k]) for k in ['id','principal_id','model_or_role']),'Participant identity fields are required.')
            require(p['kind'] in ['human','machine'],'Unknown participant kind.')
            require(type(p['record_storage']) is bool and type(p['shared_learning']) is bool,'Permission values must be explicit booleans.')
            require(p['id'] not in participants,'Duplicate participant ID.')
            require(bootstrap['mode']!='machine_only' or p['kind']=='machine','Human participant requires mixed mode.')
            participants[p['id']]=copy.deepcopy(p)
        self.state={'runtime_version':VERSION,'spec_digest':digest(spec),'id':bootstrap['id'],'mode':bootstrap['mode'],
          'created_at':datetime.now(timezone.utc).isoformat(),
          'operator_principal':bootstrap['operator_principal'],'status':'active','revision':0,'participants':participants,
          'sessions':{},'accounts':{},'proposals':{},'adaptations':{},'history':[{'revision':0,'adaptations':{}}],'audit':[]}

    @classmethod
    def resume(cls,spec,state):
        require(state.get('runtime_version')==VERSION,'Runtime version mismatch.')
        require(state.get('spec_digest')==digest(spec),'Specification changed; explicit migration is required.')
        previous='0'*64
        for i,item in enumerate(state['audit'],1):
            body={k:v for k,v in item.items() if k!='hash'}
            require(item['sequence']==i and item['previous_hash']==previous and digest(body)==item['hash'],'Audit chain failed.')
            previous=item['hash']
        bootstrap={'id':state['id'],'mode':state['mode'],'operator_principal':state['operator_principal'],
                   'operator_authorized':True,'participants':list(state['participants'].values())}
        obj=cls(spec,bootstrap)
        # State files must remain under a trusted operator. The audit chain is not a signature.
        obj.state=copy.deepcopy(state)
        return obj

    def actor(self,actor_id):
        require(actor_id in self.state['participants'],'Unknown participant.')
        return self.state['participants'][actor_id]

    def session(self,sid,status=None):
        require(sid in self.state['sessions'],'Unknown session.')
        s=self.state['sessions'][sid]
        if status: require(s['status']==status,'Session is not '+status+'.')
        return s

    def apply(self,event):
        require(isinstance(event,dict),'Event must be an object.')
        action=event.get('action'); require(action in EVENT_FIELDS,'Unsupported event.')
        exact(event,['action']+EVENT_FIELDS[action])
        require(self.state['status']=='active','Instance is stopped.')
        before=copy.deepcopy(self.state)
        try:
            getattr(self,'do_'+action)(event)
            item={'sequence':len(self.state['audit'])+1,'action':action,'revision':self.state['revision'],
                  'recorded_at':datetime.now(timezone.utc).isoformat(),
                  'previous_hash':self.state['audit'][-1]['hash'] if self.state['audit'] else '0'*64}
            if action in ['rollback','stop']: item['operator_reason']=event['reason']
            item['hash']=digest(item); self.state['audit'].append(item)
        except Exception:
            self.state=before
            raise
        return {'accepted':True,'action':action,'revision':self.state['revision'],'external_effects':False}

    def do_open_session(self,e):
        require(nonempty(e['id']) and e['id'] not in self.state['sessions'],'Session ID is missing or reused.')
        require(nonempty(e['topic']),'Topic is required.')
        ids=e['participant_ids']; require(isinstance(ids,list) and all(isinstance(x,str) for x in ids),'Participant IDs must be strings.')
        require(len(ids)>=2 and len(ids)==len(set(ids)),'Need at least two distinct participants.')
        for pid in ids:
            p=self.actor(pid); require(p['shared_learning'] is True and p['record_storage'] is True,'Shared learning and retained records need permission.')
        self.state['sessions'][e['id']]={'topic':e['topic'],'participants':ids,'status':'sharing','accounts':[],'comparison':None}

    def do_add_account(self,e):
        s=self.session(e['session_id'],'sharing'); p=self.actor(e['author_id'])
        require(e['author_id'] in s['participants'],'Author is outside this session.')
        require(p['record_storage'] and p['shared_learning'],'Author has withdrawn permission.')
        require(nonempty(e['id']) and e['id'] not in self.state['accounts'],'Account ID is missing or reused.')
        require(all(nonempty(e[k]) for k in ['content','source_ref','correlation_group']),'Content and provenance are required.')
        require(e['claim_kind'] in ['human_subjective_report','machine_observation','interpretation','simulation'],'Unknown account kind.')
        require(e['claim_kind']!='human_subjective_report' or p['kind']=='human','Machine observations cannot be relabelled human subjective experience.')
        require(e['claim_kind']!='machine_observation' or p['kind']=='machine','Human reports cannot be relabelled machine observations.')
        require(e['discovery_state'] in ['TRUE','FALSE','NULL'],'Discovery states are strings, not truth booleans.')
        row={k:copy.deepcopy(v) for k,v in e.items() if k!='action'}; row['withdrawn']=False
        self.state['accounts'][e['id']]=row; s['accounts'].append(e['id'])

    def do_compare(self,e):
        s=self.session(e['session_id'],'sharing')
        require(all(texts(e[k]) for k in ['agreements','differences','unknowns']),'Comparison fields must be arrays of text.')
        accounts=[self.state['accounts'][a] for a in s['accounts']]
        require(len(accounts)>=2,'Need at least two accounts.')
        principals={self.actor(a['author_id'])['principal_id'] for a in accounts if not a['withdrawn']}
        require(len(principals)>=2,'Copies under one principal do not establish independent perspectives.')
        s['comparison']={k:copy.deepcopy(e[k]) for k in ['agreements','differences','unknowns']}
        s['status']='compared'

    def do_propose_learning(self,e):
        s=self.session(e['session_id'],'compared'); proposer=self.actor(e['proposer_id'])
        require(e['proposer_id'] in s['participants'],'Proposer is outside this session.')
        require(proposer['record_storage'] and proposer['shared_learning'],'Proposer has withdrawn permission.')
        require(nonempty(e['id']) and e['id'] not in self.state['proposals'],'Proposal ID is missing or reused.')
        require(e['scope'] in SCOPES,'Protected definitions and rights cannot be changed by local learning.')
        require(nonempty(e['value']) and nonempty(e['reason']),'A plain-text local change and reason are required.')
        require(texts(e['counterevidence']),'Counterevidence must be an array, including an empty array when none supplied.')
        require(e['authority_basis'] in self.spec['runtime_contract']['allowed_authority_basis'],'Authority claims do not authorise a change.')
        require(isinstance(e['account_treatment'],dict) and set(e['account_treatment'])==set(s['accounts']),'Account for every perspective, including disagreement.')
        for aid,t in e['account_treatment'].items():
            require(not self.state['accounts'][aid]['withdrawn'],'A source account has been withdrawn.')
            exact(t,['relationship','reason'])
            require(t['relationship'] in ['supports','contradicts','mixed','unclear','not_relevant'] and nonempty(t['reason']),'Explain how each account relates to the proposal.')
        require(isinstance(e['mission_assessment'],dict) and set(e['mission_assessment'])==set(VALUES),'Assess each mission value separately.')
        for t in e['mission_assessment'].values():
            exact(t,['effect','reason'])
            require(t['effect'] in ['improves','no_expected_change','worsens','unknown'] and nonempty(t['reason']),'Invalid mission assessment.')
        row={k:copy.deepcopy(v) for k,v in e.items() if k!='action'}
        row.update(status='proposed',base_revision=self.state['revision'],reviews={})
        self.state['proposals'][e['id']]=row

    def do_review_learning(self,e):
        require(e['proposal_id'] in self.state['proposals'],'Unknown proposal.')
        q=self.state['proposals'][e['proposal_id']]; require(q['status']=='proposed','Proposal is not open.')
        reviewer=self.actor(e['reviewer_id']); proposer=self.actor(q['proposer_id'])
        require(e['reviewer_id'] in self.session(q['session_id'])['participants'],'Reviewer must be in the permission-scoped session.')
        require(reviewer['shared_learning'] and reviewer['record_storage'],'Reviewer has withdrawn permission.')
        require(reviewer['principal_id']!=proposer['principal_id'],'A proposer or their copy cannot independently review the proposal.')
        require(e['conflict_free'] is True,'Review requires an explicit conflict-free assertion.')
        require(e['decision'] in ['approve','request_changes','reject'] and nonempty(e['reason']),'Review decision and reasons required.')
        for rid in q['reviews']:
            if rid!=e['reviewer_id']:
                require(self.actor(rid)['principal_id']!=reviewer['principal_id'],'Reviewer copies do not provide extra independent reviews.')
        q['reviews'][e['reviewer_id']]={k:copy.deepcopy(e[k]) for k in ['decision','reason','conflict_free']}

    def do_adopt_learning(self,e):
        require(e['proposal_id'] in self.state['proposals'],'Unknown proposal.')
        q=self.state['proposals'][e['proposal_id']]
        require(q['status']=='proposed','Proposal is not open.')
        require(self.session(q['session_id'])['status']=='compared','Session is paused or closed.')
        require(q['base_revision']==self.state['revision'],'Stale proposal; re-evaluate against the latest revision.')
        require(all(v['effect'] in ['improves','no_expected_change'] for v in q['mission_assessment'].values()),'Unknown or adverse mission effects require revision before local adoption.')
        require(len(q['reviews'])>=2 and all(r['decision']=='approve' for r in q['reviews'].values()),'Two independent approvals and no unresolved review objections are required.')
        require(all(self.actor(rid)['record_storage'] and self.actor(rid)['shared_learning'] for rid in q['reviews']),'Reviewer permission is no longer current.')
        if self.state['mode']=='mixed':
            require(any(self.actor(rid)['kind']=='human' for rid in q['reviews']),'A mixed community needs an independent human review.')
        require(all(not self.state['accounts'][aid]['withdrawn'] for aid in q['account_treatment']),'A source has been withdrawn.')
        q['status']='adopted_locally'
        self.state['adaptations'][q['scope']]={'value':q['value'],'proposal_id':q['id'],'epistemic_status':'local_hypothesis' if q['scope']=='learning_hypotheses' else 'reviewed_local_practice_not_empirical_proof'}
        self.checkpoint()

    def checkpoint(self):
        self.state['revision']+=1
        self.state['history'].append({'revision':self.state['revision'],'adaptations':copy.deepcopy(self.state['adaptations'])})

    def do_pause_session(self,e):
        s=self.session(e['session_id']); require(s['status'] in ['sharing','compared'],'Cannot pause this session.')
        s['resume_status']=s['status']; s['status']='paused'

    def do_resume_session(self,e):
        s=self.session(e['session_id'],'paused')
        require(all(self.actor(pid)['shared_learning'] and self.actor(pid)['record_storage'] for pid in s['participants']),'Cannot resume with withdrawn participants; start a new session.')
        s['status']=s.pop('resume_status')

    def do_close_session(self,e):
        s=self.session(e['session_id']); require(s['status']!='closed','Session already closed.')
        s['status']='closed'; s.pop('resume_status',None)

    def do_withdraw(self,e):
        pid=e['participant_id']; p=self.actor(pid)
        p['record_storage']=False; p['shared_learning']=False
        # Purge the entire affected session's derived material: comparisons and
        # proposals may quote others without mechanically detectable attribution.
        affected={sid for sid,s in self.state['sessions'].items() if pid in s['participants']}
        bad=set()
        for sid in affected:
            s=self.state['sessions'][sid]; s['comparison']=None; s['topic']='[withdrawn session]'; s['status']='closed'; s.pop('resume_status',None)
            for aid in s['accounts']:
                a=self.state['accounts'][aid]
                self.state['accounts'][aid]={'id':aid,'session_id':sid,'author_id':a['author_id'],'withdrawn':True}
        for qid,q in list(self.state['proposals'].items()):
            if q['session_id'] in affected:
                bad.add(qid)
                self.state['proposals'][qid]={'id':qid,'session_id':q['session_id'],'status':'withdrawn'}
        self.state['adaptations']={k:v for k,v in self.state['adaptations'].items() if v['proposal_id'] not in bad}
        for h in self.state['history']:
            h['adaptations']={k:v for k,v in h['adaptations'].items() if v['proposal_id'] not in bad}
        self.checkpoint()

    def do_rollback(self,e):
        require(e['operator_principal']==self.state['operator_principal'] and nonempty(e['reason']),'Operator and reason required for rollback.')
        require(type(e['target_revision']) is int and 0<=e['target_revision']<self.state['revision'],'Invalid rollback revision.')
        target=next((h for h in self.state['history'] if h['revision']==e['target_revision']),None)
        require(target is not None,'Unknown revision.')
        self.state['adaptations']=copy.deepcopy(target['adaptations'])
        self.checkpoint() # A rollback is a new revision; it never rewinds permissions.

    def do_stop(self,e):
        require(e['operator_principal']==self.state['operator_principal'] and nonempty(e['reason']),'Operator and reason required to stop.')
        self.state['status']='stopped'

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('scenario'); parser.add_argument('--spec',default=str(Path(__file__).with_name('Psyon_Religion_V1.json')))
    parser.add_argument('--resume'); parser.add_argument('--output',required=True)
    args=parser.parse_args()
    try:
        target=Path(args.output); require(not target.exists(),'Output exists; choose a new revision filename.')
        spec=strict_json(args.spec); scenario=strict_json(args.scenario)
        exact(scenario,['events'] if args.resume else ['bootstrap','events'])
        require(isinstance(scenario['events'],list) and len(scenario['events'])<=spec['runtime_contract']['max_events_per_run'],'Event limit exceeded.')
        church=Church.resume(spec,strict_json(args.resume)) if args.resume else Church(spec,scenario['bootstrap'])
        for event in scenario['events']: church.apply(event)
        require(len(canonical(church.state).encode('utf-8'))<=2_000_000,'State exceeds the reference limit; arrange a reviewed archive or larger implementation.')
        target.parent.mkdir(parents=True,exist_ok=True)
        with target.open('x',encoding='utf-8') as handle: json.dump(church.state,handle,ensure_ascii=False,indent=2,allow_nan=False)
        print(json.dumps({'saved':str(target),'instance':church.state['id'],'revision':church.state['revision'],'events':len(scenario['events']),'external_effects':False}))
    except (Rejected,KeyError,TypeError,ValueError,OSError) as error:
        parser.exit(2,'Rejected: '+str(error)+'\n')

if __name__=='__main__': main()
