"""Explicit post-fit device repair and B0 evidence recovery, no retraining B0."""
from contextlib import contextmanager
from pathlib import Path
import os
import time

import cv2
import torch

from .mask_model_training_data import PROJECT, read, write, digest, require, verify_dataset, gpu_receipt
from .mask_model_improvement import GENERIC_SHA, rf_items, rf_predictions, report

V4 = PROJECT/'outputs/pallet_mask_model_improvement_v4'
V5 = PROJECT/'outputs/pallet_mask_model_improvement_v5'


def ensure_inference_device(model, device):
    """Lightning teardown may move the live module to CPU after fit."""
    return model.to(device)


@contextmanager
def postfit_device_compatibility():
    from . import mask_model_improvement as base
    original = base.rf_predictions
    def on_gpu(model, *args, **kwargs):
        return original(ensure_inference_device(model, 'cuda:0'), *args, **kwargs)
    base.rf_predictions = on_gpu
    try:
        yield
    finally:
        base.rf_predictions = original


def recover_b0():
    """Evaluate the already trained frozen best. ZERO new optimizer updates."""
    from rfdetr import RFDETRSegSmall
    from .mask_model_training import seed_all
    import shutil
    start = time.monotonic()
    out = V5/'B0_recovery'
    out.mkdir(mode=0o700)
    try:
        gpu = gpu_receipt('m2')
        torch.set_num_threads(4); cv2.setNumThreads(1); seed_all()
        _, records = verify_dataset(V5)
        require(digest(V5/'dataset_manifest.json') == digest(V4/'dataset_manifest.json'), 'Recovery data differ')
        source = V4/'B0'
        failure = read(source/'failure.json')
        require(failure['error_type'] == 'RuntimeError' and 'Input type' in failure['error'], 'Unexpected recovery failure cause')
        require(not (source/'completion.json').exists(), 'Do not overwrite/recover a completed run')
        last = torch.load(source/'last.pt', map_location='cpu', weights_only=True)
        require(last['step'] == 1000, 'B0 did not complete1000 actual training updates')
        del last
        best = torch.load(source/'best.pt', map_location='cpu', weights_only=True)
        weight = PROJECT/'outputs/pallet_mask_model_training_v1/generic_pretraining/rf-detr-seg-small.pt'
        require(digest(weight) == GENERIC_SHA['m2'], 'Generic architecture initialization changed')
        # Generic file initializes architecture; source/best is loaded ONLY for
        # recovering inference, never as generic or as a new training start.
        wrapper = RFDETRSegSmall(num_classes=1, resolution=576, device='cuda:0',
            pretrain_weights=str(weight), gradient_checkpointing=True, compile=False)
        model = ensure_inference_device(wrapper.model.model, 'cuda:0')
        model.load_state_dict(best['model'])
        best_step = best['step']; del best
        transforms = read(V5/'private/rfdetr_transforms.json')
        write(out/'recovery_start.json', dict(state='postfit_evaluation_recovery_only', gpu=gpu,
            original_failed_run='outputs/pallet_mask_model_improvement_v4/B0',
            original_failure_sha256=digest(source/'failure.json'),
            original_worker_start_sha256=digest(source/'worker_start.json'),
            source_best_sha256=digest(source/'best.pt'), source_last_sha256=digest(source/'last.pt'),
            trained_optimizer_updates_in_source=1000, new_optimizer_updates=0,
            dataset_sha256=digest(V5/'dataset_manifest.json'), best_step=best_step,
            fixed_native_threshold=.5, selection_changed=False, source_run_modified=False,
            recovery_code_sha256=digest(__file__), pid=os.getpid()))
        for split in ('dev', 'calibration'):
            predictions, diagnostic = rf_predictions(model, rf_items(V5, records, split, transforms), diagnostic=True)
            write(out/f'{split}_predictions.jsonl', predictions, lines=True)
            write(out/f'{split}_quality.json', report(predictions))
            write(out/f'B2_inference_only_{split}_double_threshold_diagnostic.jsonl', diagnostic, lines=True)
        write(out/'recovery_completion.json', dict(state='completed_postfit_evaluation_recovery_not_new_training',
            original_failed_training_root='outputs/pallet_mask_model_improvement_v4/B0',
            actual_optimizer_updates_in_original_training=1000, new_optimizer_updates=0,
            best_step=best_step, source_best_sha256=digest(source/'best.pt'), source_last_sha256=digest(source/'last.pt'),
            elapsed_seconds=time.monotonic()-start, original_failure_preserved=True,
            original_run_completion_created=False, formal_val_test_predictions=0, production_activation=False))
    except BaseException as exc:
        import traceback
        write(out/'failure.json', dict(state='recovery_failed_not_complete', error=str(exc), traceback=traceback.format_exc()))
        raise
