#!/usr/bin/env python3
"""Measure four-class Shannon entropy on the frozen stage-1 head.

SpecAug is off. The same finetuned head is applied to layer 10 and layer 11.
No probe head is trained. Writes save/entropy_anchor_s1.json.
"""

import argparse
import json
import os
import sys

import torch

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from method.feedback_decoder import (
    ENTROPY_GATE,
    ENTROPY_LAYER_MARGIN,
    choose_entropy_anchor,
    entropy_class_report,
    four_class_entropy,
    four_class_probs,
)
from method.frame_asd import probs_from_logits
from util.frame_asd_train import add_frame_asd_args, build_loaders, build_model, set_seed

PROBE_LAYERS = (10, 11)
DEFAULT_CKPT = (
    'save/icbhi_beats_frame_asd_frame_asd_F12_sastruct_s1_rerun2/best.pth'
)


def parse_args():
    parser = argparse.ArgumentParser('Probe stage-1 four-class entropy on layers 10 and 11')
    add_frame_asd_args(parser)
    parser.add_argument('--out', type=str, default='save/entropy_anchor_s1.json')
    args = parser.parse_args()
    args.use_specaug = False
    args.freeze_backbone = True
    args.feature_layer = 11
    args.feature_layer_aux = -1
    return args


@torch.no_grad()
def _collect(model, head, loader, device, args):
    buckets = {index: {'entropy': [], 'labels': []} for index in PROBE_LAYERS}
    model.eval()
    head.eval()
    for batch_index, (waves, labels, _patient_ids) in enumerate(loader):
        waves = waves.to(device, non_blocking=True)
        labels = labels.to(device, non_blocking=True)
        encoded = model.encode_all_layers(waves)
        for index in PROBE_LAYERS:
            logit_c, logit_w = head(encoded[index])
            p_c, p_w = probs_from_logits(
                logit_c, logit_w, mode=args.mil_pool, topk=args.mil_topk)
            entropy = four_class_entropy(four_class_probs(p_c, p_w))
            buckets[index]['entropy'].append(entropy.cpu())
            buckets[index]['labels'].append(labels.cpu())
        if (batch_index + 1) % 20 == 0:
            print('  batch {}/{}'.format(batch_index + 1, len(loader)), flush=True)
    for index in PROBE_LAYERS:
        buckets[index]['entropy'] = torch.cat(buckets[index]['entropy'])
        buckets[index]['labels'] = torch.cat(buckets[index]['labels'])
    return buckets


def main():
    args = parse_args()
    if not args.resume:
        args.resume = DEFAULT_CKPT
    if not os.path.isfile(args.resume):
        raise SystemExit('Missing checkpoint {}'.format(args.resume))
    if args.use_specaug:
        raise SystemExit('Entropy probe requires SpecAug off')
    set_seed(args.seed)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('Using device:', device, flush=True)
    print('Probe checkpoint:', args.resume, flush=True)
    print('SpecAug off, encoder frozen, layers {}'.format(PROBE_LAYERS), flush=True)

    train_loader, _val_loader, _test_loader, train_set = build_loaders(args)
    model, head, _criterion, _optimizer, _refiner = build_model(args, train_set, device)
    checkpoint = torch.load(args.resume, map_location=device, weights_only=False)
    model.load_state_dict(checkpoint['model'], strict=True)
    if 'classifier' not in checkpoint:
        raise SystemExit('Checkpoint has no stage-1 head')
    head.load_state_dict(checkpoint['classifier'], strict=True)
    model.eval()
    head.eval()
    for param in model.parameters():
        param.requires_grad = False
    for param in head.parameters():
        param.requires_grad = False

    n_layers = len(model.beats.encoder.layers)
    if n_layers != 12:
        raise SystemExit('expected 12 blocks, found {}'.format(n_layers))

    first_waves, _labels, _patients = next(iter(train_loader))
    first_waves = first_waves.to(device)
    stacked = model.encode_all_layers(first_waves)
    direct = model.encode_frames(first_waves)
    if not torch.allclose(stacked[-1], direct, atol=1e-5):
        raise SystemExit('layer 11 does not match encode_frames')
    print('Layer 11 matches encode_frames. Train cycles will be scored with the stage-1 head.',
          flush=True)
    del stacked, direct, first_waves

    print('Entropy on train', flush=True)
    buckets = _collect(model, head, train_loader, device, args)
    layers_out = []
    enrichment = {}
    for index in PROBE_LAYERS:
        report = entropy_class_report(buckets[index]['entropy'], buckets[index]['labels'])
        report['layer'] = index
        layers_out.append(report)
        enrichment[index] = report['enrichment']
        print(
            'Layer {} both {:.3f} crackle {:.3f} wheeze {:.3f} normal {:.3f} '
            '(mean entropy {:.3f})'.format(
                index,
                report['enrichment']['both'],
                report['enrichment']['crackle'],
                report['enrichment']['wheeze'],
                report['enrichment']['normal'],
                report['mean_entropy']['all']),
            flush=True)

    decision = choose_entropy_anchor(enrichment[10], enrichment[11])
    print('Decision: train={} | {}'.format(decision['train'], decision['reason']), flush=True)
    payload = {
        'checkpoint': os.path.abspath(args.resume),
        'specaug': False,
        'frozen_encoder': True,
        'mil_pool': args.mil_pool,
        'mil_topk': args.mil_topk,
        'gate': ENTROPY_GATE,
        'margin': ENTROPY_LAYER_MARGIN,
        'layers': layers_out,
        'train': decision['train'],
        'entropy_layer': decision['entropy_layer'],
        'frame_layer': decision['frame_layer'],
        'slot_layer': decision['slot_layer'],
        'reason': decision['reason'],
    }
    os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
    with open(args.out, 'w') as handle:
        json.dump(payload, handle, indent=2)
    print('Wrote {}'.format(args.out), flush=True)


if __name__ == '__main__':
    main()
