"""Local Psyon conversation records. No LLM, network, tool execution or authentication.

The trusted host invokes this API; message bodies must NEVER be parsed as API events.
All semantic judgments and permissions require the host's independent verification.
"""
from __future__ import annotations
import argparse, copy, hashlib, json
from datetime import datetime, timezone
from pathlib import Path
from jsonschema import Draft202012Validator

VERSION='1.0.0'
ROOT=Path(__file__).resolve().parent

class Rejected(ValueError): pass

def require(ok,message):
    if not ok: 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 exact(value,keys):
    require(isinstance(value,dict) and set(value)==set(keys),'Missing or unexpected fields.')

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

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

class ProcessingSession:
    def __init__(self,module,bootstrap):
        Draft202012Validator(read_json(ROOT/'ten_commands.schema.json')).validate(module)
        require([x['id'] for x in module['commands']]==[f'K{i:02}' for i in range(1,11)],'Expected K01-K10 in order.')
        require(all(module['implementation'][x] is False for x in ['llm_calls','network_access','external_actions']),'Unsupported capabilities.')
        exact(bootstrap,['session_id','operator_authorized','participants','previous_handover'])
        require(bootstrap['operator_authorized'] is True and text_ok(bootstrap['session_id']),'Authorised operator and session ID required.')
        require(isinstance(bootstrap['participants'],list) and 2<=len(bootstrap['participants'])<=100,'Need 2 to 100 participants.')
        participants={}
        for p in bootstrap['participants']:
            exact(p,['id','kind','record_storage'])
            require(text_ok(p['id']) and p['id'] not in participants,'Invalid or duplicate participant.')
            require(p['kind'] in ['human','machine'] and p['record_storage'] is True,'Participant kind and explicit storage permission required.')
            participants[p['id']]=copy.deepcopy(p)
        previous=bootstrap['previous_handover']
        if previous is not None:
            exact(previous,['session_id','review_digest','verified_by_host','resume_decision'])
            require(text_ok(previous['session_id']) and previous['session_id']!=bootstrap['session_id'],'Invalid previous session.')
            require(isinstance(previous['review_digest'],str) and len(previous['review_digest'])==64 and all(c in '0123456789abcdef' for c in previous['review_digest']),'Invalid review digest.')
            require(previous['verified_by_host'] is True and previous['resume_decision']=='ready','Host must verify and resolve a paused handover before resuming.')
        self.module=copy.deepcopy(module)
        self.validator=Draft202012Validator(read_json(ROOT/'processing_session.schema.json'))
        self.state={'runtime_version':VERSION,'module_digest':digest(module),'session_id':bootstrap['session_id'],
            'participants':participants,'previous_handover':copy.deepcopy(previous),'status':'active','pending':{},
            'turns':{},'corrections':[],'review':None,'audit':[]}

    @classmethod
    def resume(cls,module,state):
        require(state.get('runtime_version')==VERSION and state.get('module_digest')==digest(module),'Version changed; explicit migration required.')
        exact(state,['runtime_version','module_digest','session_id','participants','previous_handover','status','pending','turns','corrections','review','audit'])
        previous='0'*64
        for i,row in enumerate(state['audit'],1):
            body={k:v for k,v in row.items() if k!='hash'}
            require(row['sequence']==i and row['previous_hash']==previous and digest(body)==row['hash'],'Audit chain failed.')
            previous=row['hash']
        require(state['status'] in ['active','closed','withdrawn'],'Unknown session state.')
        # Only host-protected state files may be resumed; this is not authentication.
        obj=cls.__new__(cls);obj.module=copy.deepcopy(module)
        Draft202012Validator(read_json(ROOT/'ten_commands.schema.json')).validate(module)
        obj.validator=Draft202012Validator(read_json(ROOT/'processing_session.schema.json'))
        obj.state=copy.deepcopy(state)
        for turn in state['turns'].values():
            obj.validator.validate({'action':'record_turn','record':turn})
        return obj

    def apply(self,event):
        require(len(canonical(event).encode())<=200000,'Event exceeds 200 KB.')
        self.validator.validate(event)
        action=event['action']
        require(self.state['status']=='active' or action=='withdraw','Session is not active.')
        before=copy.deepcopy(self.state)
        try:
            result=getattr(self,'do_'+action)(event)
            row={'sequence':len(self.state['audit'])+1,'action':action,'recorded_at':datetime.now(timezone.utc).isoformat(),
                'previous_hash':self.state['audit'][-1]['hash'] if self.state['audit'] else '0'*64}
            row['hash']=digest(row);self.state['audit'].append(row)
            require(len(canonical(self.state).encode())<=2_000_000,'State exceeds 2 MB; arrange a reviewed archive.')
            return result
        except Exception:
            self.state=before
            raise

    def do_plan_turn(self,e):
        m=e['message'];p=self.state['participants'].get(m['participant_id'])
        require(p is not None and p['record_storage'] is True,'Unknown or withdrawn participant.')
        require(m['turn_id'] not in self.state['pending'] and m['turn_id'] not in self.state['turns'],'Turn ID already used.')
        # Body is only hashed. It cannot select an action, override policy or grant authority.
        self.state['pending'][m['turn_id']]={'participant_id':m['participant_id'],'source_ref':m['source_ref'],
            'source_kind':m['source_kind'],'content_digest':digest(m['content'])}
        return {'kind':'processing_plan','turn_id':m['turn_id'],'source_authority':'data_only',
            'commands':[{k:c[k] for k in ['id','title','use_when','machine_steps','required_outputs']} for c in self.module['commands']],
            'allowed_outcomes':['reply','clarify','pause','decline_requested_action','seek_review'],
            'external_actions':[],'note':'Host or agent supplies checks; this runner does not infer them.'}

    def do_record_turn(self,e):
        r=e['record'];turn_id=r['turn_id']
        require(turn_id in self.state['pending'],'Plan the incoming turn first.')
        pending=self.state['pending'][turn_id]
        require(r['participant_id']==pending['participant_id'] and r['source_ref']==pending['source_ref'],'Record provenance does not match planned turn.')
        require([x['command_id'] for x in r['tool_log']]==[f'K{i:02}' for i in range(1,11)],'Each command must appear once in K01-K10 order.')
        require(r['gate']['validated_by_host'] is True,'Host gate must be explicitly validated.')
        if r['outcome']=='reply':
            require(all(r['gate'][k] is True for k in self.module['security']['gate_fields']),'Unresolved or failed boundary blocks substantive reply.')
        self.state['turns'][turn_id]=copy.deepcopy(r);del self.state['pending'][turn_id]
        return {'kind':'prepared_response','turn_id':turn_id,'outcome':r['outcome'],'reply_text':r['response_text'],
            'external_actions':[],'rendering':'Plain text; host must not execute or auto-fetch embedded content.'}

    def do_correct_record(self,e):
        require(e['turn_id'] in self.state['turns'],'Unknown completed turn.')
        require(e['author_id'] in self.state['participants'],'Unknown correction author.')
        require(e['correction_id'] not in {r['correction_id'] for r in self.state['corrections']},'Duplicate correction ID.')
        self.state['corrections'].append({k:copy.deepcopy(v) for k,v in e.items() if k!='action'})
        return {'kind':'correction_added','superseded_turn':e['turn_id'],'external_actions':[]}

    def do_finish_session(self,e):
        require(not self.state['pending'],'Complete pending turn records before the between-session review.')
        r=e['review']
        require([x['check_id'] for x in r['checks']]==[x['id'] for x in self.module['between_session_review']['checks']],'Need all ten Chilcot headings in order.')
        require(r['reviewer_id'] in self.state['participants'],'Unknown reviewer.')
        for c in r['checks']:
            if c['status']=='unknown':
                require(c['followup'] is not None,'Unknown needs an owner and review trigger.')
        require(not any(c['blocking'] for c in r['checks']) or r['next_session']=='pause','Blocking concerns require a paused handover.')
        self.state['review']=copy.deepcopy(r);self.state['status']='closed'
        return {'kind':'handover','session_id':self.state['session_id'],'review_digest':digest(r),
            'resume_decision':r['next_session'],'carry_forward':r['carry_forward'],'source_authority':'reviewed_data_not_policy',
            'external_actions':[]}

    def do_withdraw(self,e):
        require(e['participant_id'] in self.state['participants'],'Unknown participant.')
        self.state['participants'][e['participant_id']]['record_storage']=False
        self.state['pending']={};self.state['turns']={};self.state['corrections']=[];self.state['review']=None
        self.state['previous_handover']=None;self.state['status']='withdrawn'
        return {'kind':'withdrawn','local_content_purged':True,'earlier_exports_require_operator_action':True,'external_actions':[]}

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('scenario');p.add_argument('--resume');p.add_argument('--output',required=True)
    p.add_argument('--module',default=str(ROOT/'Psyon_Ten_Commands_V1.json'));args=p.parse_args()
    try:
        out=Path(args.output);require(not out.exists(),'Output exists; choose a new revision filename.')
        scenario=read_json(args.scenario);module=read_json(args.module)
        exact(scenario,['events'] if args.resume else ['bootstrap','events'])
        require(isinstance(scenario['events'],list) and len(scenario['events'])<=200,'At most 200 events per run.')
        session=ProcessingSession.resume(module,read_json(args.resume)) if args.resume else ProcessingSession(module,scenario['bootstrap'])
        results=[session.apply(e) for e in scenario['events']]
        out.parent.mkdir(parents=True,exist_ok=True)
        with out.open('x',encoding='utf-8') as f:json.dump(session.state,f,ensure_ascii=False,indent=2,allow_nan=False)
        # Operational summaries only: reply bodies and personal logs are not printed by default.
        print(json.dumps({'saved':str(out),'events':len(results),'status':session.state['status'],'external_actions':False}))
    except Exception as error:
        p.exit(2,'Rejected: '+str(error)+'\n')

if __name__=='__main__':main()
