"""Actual pretrained-only inference with immutable per-task evidence; never load PEFT."""
import argparse
import importlib.metadata
import json
import os
from pathlib import Path
import sys
import time
import traceback

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.mask_model_training_data import read,write,jsonl,require,gpu_receipt
from pallet.cluster_targets import digest
from pallet.pallet_vlm_native_intensity import ROOT,parse_structure


def main(name):
    import torch
    from PIL import Image
    from transformers import AutoProcessor,AutoModelForImageTextToText
    route='m1' if name=='qwen08b' else 'm2';gpu=gpu_receipt(route);torch.set_num_threads(4);torch.manual_seed(20261105)
    if name=='qwen08b':
        folder=PROJECT/'outputs/pallet_description_vlm_models_v1/qwen';receipt=folder.parent/'qwen_download.json'
    else:folder=ROOT/'models/qwen4b';receipt=folder.parent/'qwen4b_download.json'
    pinned=read(receipt)
    for path,h in pinned['files'].items():require(digest(folder/path)==h,'Original pretrained weights/config changed')
    require(not list(folder.rglob('adapter_config.json')),'Adapter must never enter native inference')
    sample=read(ROOT/'sample/manifest.json')
    for path,h in sample['files'].items():require(digest(ROOT/'sample'/path)==h,'Frozen experiment sample changed')
    out=ROOT/'runs'/name;out.mkdir(parents=True,mode=0o700,exist_ok=True);(out/'predictions').mkdir(mode=0o700,exist_ok=True)
    require(not (out/'complete.json').exists(),'Preserve completed native run')
    processor=AutoProcessor.from_pretrained(folder,local_files_only=True)
    processor.image_processor.min_pixels=128*128;processor.image_processor.max_pixels=1024*1024
    model=AutoModelForImageTextToText.from_pretrained(folder,dtype=torch.bfloat16,attn_implementation='sdpa',local_files_only=True).cuda().eval()
    model.requires_grad_(False);model.config.use_cache=True
    tasks=jsonl(ROOT/'sample/tasks.jsonl');start=time.monotonic()
    if not (out/'execution.json').exists():
        write(out/'execution.json',dict(model=name,repo_id=pinned['repo_id'],revision=pinned['revision'],gpu=gpu,
            total_parameters=sum(p.numel() for p in model.parameters()),trainable_parameters=sum(p.numel() for p in model.parameters() if p.requires_grad),
            no_adapter=True,no_finetuning=True,no_quantization=True,dtype='bfloat16',attention='sdpa',thinking=False,do_sample=False,
            image_min_pixels=128*128,image_max_pixels=1024*1024,torch=torch.__version__,transformers=importlib.metadata.version('transformers'),
            sample_manifest_sha256=digest(ROOT/'sample/manifest.json'),model_receipt_sha256=digest(receipt),code_sha256=digest(__file__)))
    with torch.inference_mode():
        for i,t in enumerate(tasks,1):
            target=out/'predictions'/(t['task_id']+'.json')
            if target.exists():
                previous=read(target);require(previous['input_image_sha256']==t['image_sha256'] and previous['prompt']==t['prompt'],'Cannot resume with changed inputs');continue
            image=Image.open(ROOT/t['image']).convert('RGB');messages=[dict(role='user',content=[dict(type='image',image=image),dict(type='text',text=t['prompt'])])]
            text=processor.apply_chat_template(messages,tokenize=False,add_generation_prompt=True,enable_thinking=False)
            data=processor(text=[text],images=[image],return_tensors='pt').to('cuda');torch.cuda.synchronize();now=time.perf_counter()
            ids=model.generate(**data,max_new_tokens=t['max_new_tokens'],do_sample=False,pad_token_id=processor.tokenizer.pad_token_id)
            torch.cuda.synchronize();elapsed=(time.perf_counter()-now)*1000;new=ids[0,data['input_ids'].shape[1]:]
            raw=processor.tokenizer.decode(new,skip_special_tokens=True)
            value=dict(task_id=t['task_id'],sample_id=t['sample_id'],kind=t['kind'],control=t['control'],model=name,
                prompt=t['prompt'],input_image_sha256=t['image_sha256'],raw=raw,elapsed_ms=elapsed,input_ids=int(data['input_ids'].shape[1]),
                generated_tokens=int(len(new)),hit_token_limit=int(len(new))>=t['max_new_tokens'],native_image_size=list(image.size),
                image_grid_thw=data.get('image_grid_thw').tolist() if data.get('image_grid_thw') is not None else None)
            if t['kind']=='structure':value['parsed']=parse_structure(raw)
            write(target,value)
            if i%12==0:print(dict(model=name,finished=i,total=len(tasks),seconds=round(time.monotonic()-start)),flush=True)
    predictions=[read(out/'predictions'/(t['task_id']+'.json')) for t in tasks]
    write(out/'predictions.jsonl',predictions,lines=True)
    write(out/'complete.json',dict(state='actual_pretrained_only_inference_complete',model=name,tasks=len(predictions),seconds=time.monotonic()-start,
        peak_allocated_GiB=torch.cuda.max_memory_allocated()/2**30,predictions_sha256=digest(out/'predictions.jsonl'),execution_sha256=digest(out/'execution.json'),
        model_unchanged=all(digest(folder/path)==h for path,h in pinned['files'].items()),code_sha256=digest(__file__)))
    print(read(out/'complete.json'),flush=True)


if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('model',choices=('qwen08b','qwen4b'));a=p.parse_args()
    try:main(a.model)
    except Exception:
        folder=ROOT/'runs'/a.model;folder.mkdir(parents=True,mode=0o700,exist_ok=True)
        write(folder/('failure_'+str(time.time_ns())+'.json'),dict(traceback=traceback.format_exc()));raise
