#!/usr/bin/env python3
"""Inspect another symbol pair using the saved weights and the student's attention code."""
import argparse
import hashlib
import json
import re
from datetime import datetime, timezone
from pathlib import Path
import torch
import mit_attention
import transformer
import tjek_attention


def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()


def load_run(run_dir):
    report_path=run_dir/'opgave-resultat.json';model_path=run_dir/'model.pt'
    if report_path.stat().st_size>32768:raise ValueError('Resultatfilen er for stor.')
    raw=report_path.read_bytes();report=json.loads(raw.decode('utf-8'))
    if not isinstance(report,dict) or report.get('format')!='learning-lab-own-attention-v1':raise ValueError('Ugyldig resultatfil.')
    expected={'student_sha256':sha(Path(mit_attention.__file__)),'runner_sha256':sha(Path(tjek_attention.__file__)),'transformer_sha256':sha(Path(transformer.__file__)),'model_sha256':sha(model_path)}
    if any(not isinstance(report.get(k),str) or not re.fullmatch(r'[0-9a-f]{64}',report[k]) for k in expected):raise ValueError('Resultatet mangler filhashes. Træn med den nyeste opgavepakke først.')
    if any(report[k]!=v for k,v in expected.items()):raise ValueError('Kode eller model matcher ikke resultatfilens hashes. Brug de samme filer som ved træningen.')
    history=report.get('history');last=history[-1] if isinstance(history,list) and history else None
    if not isinstance(last,dict) or isinstance(last.get('step'),bool) or not isinstance(last.get('step'),int) or not 1<=last['step']<=1000 or isinstance(last.get('validation_accuracy'),bool) or not isinstance(last.get('validation_accuracy'),(float,int)) or not 0<=last['validation_accuracy']<=1:raise ValueError('Ugyldige træningsmetadata.')
    torch.set_num_threads(1);tjek_attention.check_attention(mit_attention.causal_attention)
    model=tjek_attention.StudentTransformer();model.load_state_dict(torch.load(model_path,map_location='cpu',weights_only=True),strict=True)
    return model,report,last,hashlib.sha256(raw).hexdigest(),expected['model_sha256']


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--run-dir',required=True,type=Path);p.add_argument('--first',required=True,type=int);p.add_argument('--second',required=True,type=int);p.add_argument('--output',type=Path)
    a=p.parse_args()
    if not 0<=a.first<6 or not 0<=a.second<6:p.error('Vælg symboler fra 0 til 5.')
    if a.output and a.output.exists():p.error('Outputfilen findes allerede.')
    try:
        model,report,last,report_sha,model_sha=load_run(a.run_dir)
        trace=tjek_attention.make_trace(model,a.first,a.second,last['step'],last['validation_accuracy'],report_sha,model_sha)
        trace['training_torch_version']=report.get('torch_version','ukendt')
    except (OSError,UnicodeError,ValueError,RuntimeError,TypeError,AttributeError,NotImplementedError) as exc:p.error(str(exc))
    out=a.output or a.run_dir/('attention-probe-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S_%fZ')+'.json')
    try:
        with out.open('x',encoding='utf-8') as file:json.dump(trace,file,ensure_ascii=False,indent=2,allow_nan=False)
    except FileExistsError:p.error('Outputfilen findes allerede.')
    print(f"Input {a.first}, {a.second}, ?; model: {trace['prediction']}; facit: {a.first}. Gemt: {out}")

if __name__=='__main__':main()
