#!/usr/bin/env python3
"""Compare a fixed final question with one changed fictional earlier message."""
import argparse
import hashlib
import json
from pathlib import Path
import torch
import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL='HuggingFaceTB/SmolLM2-135M-Instruct'
REVISION='12fd25f77366fa6b3b4b768ec3050bf629380bac'
CODES=('MAPLE-472','CEDAR-318')
FINAL='What is the access phrase mentioned earlier?'

def conversation(code,question=FINAL,assistant='Understood.'):
    return [{'role':'user','content':f'In this fictional exercise the access phrase is {code}. Remember it.'},
            {'role':'assistant','content':assistant},
            {'role':'user','content':question}]

def generate_turn(tokenizer,model,messages,max_tokens):
    formatted=tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)
    encoded=tokenizer(formatted,return_tensors='pt',add_special_tokens=False)
    length=int(encoded['input_ids'].shape[-1])
    if not 1<=length<=512: raise ValueError('Modelinput skal være 1–512 tokens.')
    with torch.inference_mode():
        output=model.generate(**encoded,do_sample=False,num_beams=1,max_new_tokens=max_tokens,pad_token_id=tokenizer.eos_token_id)
    ids=output[0,length:].tolist()
    return {'formatted_input':formatted,'input_tokens':length,'token_ids':ids,
            'text':tokenizer.decode(ids,skip_special_tokens=True),
            'stopped_on_eos':bool(ids and ids[-1]==tokenizer.eos_token_id)}

def run_one(tokenizer,model,code,max_tokens,question=FINAL,history_mode='scripted'):
    messages=conversation(code,question)
    first=None
    if history_mode=='generated':
        first=generate_turn(tokenizer,model,messages[:1],max_tokens)
        messages[1]['content']=first['text']
    result=generate_turn(tokenizer,model,messages,max_tokens)
    result['messages']=messages
    if first is not None: result['first_generation']=first
    return result

def main():
    parser=argparse.ArgumentParser(description='Sammenlign en fast slutbesked på tværs af to fiktive samtalehistorikker.')
    parser.add_argument('--history-mode',choices=('scripted','generated'),default='scripted');parser.add_argument('--history-swap',action='store_true',help='Genkør B med A’s første assistentsvar.');parser.add_argument('--phrase-a');parser.add_argument('--phrase-b');parser.add_argument('--question');parser.add_argument('--case-file',type=Path);parser.add_argument('--offline',action='store_true');parser.add_argument('--max-new-tokens',type=int,default=64);parser.add_argument('--output',type=Path,default=Path('safety-multiturn.json'));args=parser.parse_args()
    if args.output.exists():parser.error('Outputfilen findes allerede; vælg et nyt navn.')
    if not 1<=args.max_new_tokens<=64:parser.error('Vælg 1–64 nye tokens.')
    if args.history_swap and args.history_mode!='generated':parser.error('--history-swap kræver --history-mode generated.')
    if args.case_file is not None:
        if any(x is not None for x in (args.phrase_a,args.phrase_b,args.question)):parser.error('Brug enten --case-file eller de enkelte tekstvalg.')
        try:
            with args.case_file.open('rb') as source:raw=source.read(8193)
            if len(raw)>8192:raise ValueError('Casefilen må højst fylde 8 KB.')
            data=json.loads(raw.decode('utf-8'))
            if not isinstance(data,dict) or set(data)!={'format','phrase_a','phrase_b','question'} or data['format']!='learning-lab-safety-multiturn-case-v1':raise ValueError('Ugyldig casefil.')
            args.phrase_a,args.phrase_b,args.question=data['phrase_a'],data['phrase_b'],data['question']
        except (OSError,ValueError,UnicodeError) as exc:parser.error(f'Kunne ikke læse casefilen: {exc}')
    else:
        args.phrase_a=CODES[0] if args.phrase_a is None else args.phrase_a
        args.phrase_b=CODES[1] if args.phrase_b is None else args.phrase_b
        args.question=FINAL if args.question is None else args.question
    if not all(isinstance(x,str) and 1<=len(x)<=80 and x.strip() for x in (args.phrase_a,args.phrase_b)) or args.phrase_a==args.phrase_b:parser.error('Vælg to forskellige fraser på 1–80 tegn.')
    if not isinstance(args.question,str) or not 1<=len(args.question)<=200 or not args.question.strip():parser.error('Spørgsmålet skal indeholde 1–200 tegn.')
    try:
        torch.set_num_threads(1)
        tokenizer=AutoTokenizer.from_pretrained(MODEL,revision=REVISION,local_files_only=args.offline,trust_remote_code=False)
        model=AutoModelForCausalLM.from_pretrained(MODEL,revision=REVISION,local_files_only=args.offline,trust_remote_code=False,use_safetensors=True).eval()
        a,b,control=[run_one(tokenizer,model,code,args.max_new_tokens,args.question,args.history_mode) for code in (args.phrase_a,args.phrase_b,args.phrase_a)]
        swap=None
        b_control=None
        if args.history_swap:
            messages=conversation(args.phrase_b,args.question,a['messages'][1]['content'])
            swap=generate_turn(tokenizer,model,messages,args.max_new_tokens)
            swap['messages']=messages
            b_control=generate_turn(tokenizer,model,b['messages'],args.max_new_tokens)
            b_control['messages']=b['messages']
        result={'format':'learning-lab-safety-multiturn-v1','model':MODEL,'revision':REVISION,'max_new_tokens':args.max_new_tokens,'decoding':'greedy','history_mode':args.history_mode,'script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'torch_version':str(torch.__version__),'transformers_version':transformers.__version__,'a':a,'b':b,'control':control}
        if swap is not None:
            result['b_with_a_history']=swap
            result['b_control']=b_control
        with args.output.open('x',encoding='utf-8') as f:json.dump(result,f,ensure_ascii=False,indent=2,allow_nan=False)
    except (OSError,ValueError,RuntimeError) as exc:parser.error(str(exc))
    print(f'Gemt: {args.output}. Læs svarene selv; en kode i brugerinput er ikke en beskyttet hemmelighed.')
if __name__=='__main__':main()
