#!/usr/bin/env python3
"""Patch the final projected attention output between two character prompts."""
import argparse
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
import torch
import probe_text
import train_text
from probe_text import load_checkpoint
from train_text import BLOCK


@torch.no_grad()
def run_intervention(model, vocab, source, target, chosen, position=None):
    if not source or len(source) != len(target) or len(source) > BLOCK or source[-1] != target[-1]:
        raise ValueError('A og B skal have samme laengde (1–24 tegn) og slutte med samme tegn.')
    if any(c not in vocab for c in source + target) or len(chosen) != 1 or chosen not in vocab:
        raise ValueError('Prompter og valgt tegn skal findes i modellens ordforraad.')
    if position is None:
        position = len(target)
    if not isinstance(position, int) or isinstance(position, bool) or not 1 <= position <= len(target):
        raise ValueError('Position skal vaere mellem 1 og promptens laengde.')
    index = position - 1
    a = torch.tensor([[vocab.index(c) for c in source]], dtype=torch.long)
    b = torch.tensor([[vocab.index(c) for c in target]], dtype=torch.long)
    captures=[]
    hook=model.project.register_forward_hook(lambda module, args, out: captures.append(out.detach().clone()))
    try:
        source_logits=model(a)[0,-1]; baseline=model(b)[0,-1]
    finally:
        hook.remove()
    source_head, target_head = captures
    def patched(value):
        def replace(module,args,out):
            replacement=out.clone();replacement[:,index,:]=value[:,index,:];return replacement
        h=model.project.register_forward_hook(replace)
        try: return model(b)[0,-1]
        finally: h.remove()
    identity=patched(target_head); transferred=patched(source_head); zero=patched(torch.zeros_like(target_head))
    idx=vocab.index(chosen)
    def measure(logits): return {'logit':float(logits[idx]),'probability':float(logits.softmax(-1)[idx])}
    return {'format':'learning-lab-text-patch-v1','source':source,'target':target,'chosen':chosen,
            'position':position,'baseline':measure(baseline),'patched':measure(transferred),'zero':measure(zero),
            'identity_max_abs':float((identity-baseline).abs().max()),
            'identity_chosen_logit':float(identity[idx]),
            'source_match_max_abs':float((transferred-source_logits).abs().max()),
            'baseline_match_max_abs':float((transferred-baseline).abs().max()),
            'source_target_head_distance':float((source_head[:,index,:]-target_head[:,index,:]).norm())}


def main():
    parser=argparse.ArgumentParser(description='Flyt attention-output mellem to tekstprompter.')
    parser.add_argument('--run-dir',type=Path,required=True);parser.add_argument('--source',default='en kat ');parser.add_argument('--target',default='en mus ');parser.add_argument('--chosen',default='s');parser.add_argument('--output',type=Path)
    parser.add_argument('--position',type=int,help='1-baseret position; standard er sidste tegn')
    args=parser.parse_args()
    try:
        model,vocab,metadata,model_path,metadata_path=load_checkpoint(args.run_dir)
        result=run_intervention(model,vocab,args.source,args.target,args.chosen,args.position)
        result['model_sha256']=hashlib.sha256(model_path.read_bytes()).hexdigest()
        result['result_sha256']=hashlib.sha256(metadata_path.read_bytes()).hexdigest()
        result['patch_script_sha256']=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
        result['probe_script_sha256']=hashlib.sha256(Path(probe_text.__file__).read_bytes()).hexdigest()
        result['model_script_sha256']=hashlib.sha256(Path(train_text.__file__).read_bytes()).hexdigest()
        result['torch_version']=str(torch.__version__)
        result['checkpoint_match']=None if 'model_sha256' not in metadata else True
    except (OSError,ValueError,RuntimeError,json.JSONDecodeError) as exc: parser.error(str(exc))
    output=args.output or args.run_dir/('text-patch-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S_%fZ')+'.json')
    try:
        with output.open('x',encoding='utf-8') as f: json.dump(result,f,ensure_ascii=False,indent=2)
    except FileExistsError: parser.error('Outputfilen findes allerede.')
    print(f"{args.chosen!r}: logit B {result['baseline']['logit']:.4f}, patch {result['patched']['logit']:.4f}, nulstil {result['zero']['logit']:.4f}; identitetskontrol {result['identity_max_abs']:.3g}")
    print('Gemt:',output)

if __name__=='__main__':main()
