#!/usr/bin/env python3
"""Minimal training entry for Frame-Level Native ASD on ICBHI."""

import argparse
import json
import os
import time
import warnings

import torch

from util.frame_asd_train import (
    add_frame_asd_args,
    build_loaders,
    build_model,
    evaluate,
    is_trivial_score,
    set_seed,
    train_one_epoch,
    load_checkpoint,
    update_refiner_average,
)
from util.misc import (
    adjust_learning_rate,
    save_model,
    update_json,
    update_moving_average,
)

warnings.filterwarnings('ignore')


def parse_args():
    p = argparse.ArgumentParser('Frame-Level ASD training')
    add_frame_asd_args(p)
    return p.parse_args()


def _apply_ma(args, model, refiner, ma_ckpt):
    """Stage 0 averages the backbone. Stage 2 averages the refiner and pass-2 head only."""
    if refiner is None:
        if ma_ckpt is None:
            return {k: v.detach().clone() for k, v in model.state_dict().items()}
        model = update_moving_average(args.ma_beta, model, ma_ckpt)
        return {k: v.detach().clone() for k, v in model.state_dict().items()}
    return update_refiner_average(args.ma_beta, refiner, ma_ckpt)


def main():
    args = parse_args()
    if int(getattr(args, 'feedback_stage', 0) or 0) == 2:
        raise SystemExit(
            'Stage 2 does not run inside train.py. '
            'Use train_feedback.py: RESUME=/path/to/f12_best.pth bash scripts/f12_feedback_s2.sh')
    set_seed(args.seed)
    args.model_name = 'icbhi_{}_{}_{}'.format(args.model, args.method, args.tag)
    args.save_folder = os.path.join(args.save_dir, args.model_name)
    os.makedirs(args.save_folder, exist_ok=True)

    with open(os.path.join(args.save_folder, 'train_args.json'), 'w') as f:
        json.dump(vars(args), f, indent=2)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('Using device:', device)

    train_loader, val_loader, test_loader, train_set = build_loaders(args)
    model, head, criterion, optimizer, refiner = build_model(args, train_set, device)

    print('Checkpoint Name:', args.model_name)
    print('Feature layer {} aux {}'.format(args.feature_layer, args.feature_layer_aux))
    if args.ablation_stage:
        print('Ablation stage:', args.ablation_stage)
    print('Training for {} epochs'.format(args.epochs))
    if float(getattr(args, 'lambda_boundary', 0.0) or 0.0) > 0.0:
        print('Boundary hinge lambda {:.3f} (near-threshold crackle, false crackle, confused wheeze, both short of tau_c)'.format(
            float(args.lambda_boundary)))

    # Resp-229K must beat the all-normal baseline. A saved Score of 50 is not a resume point.
    best_score = 50.0 if args.dataset == 'resp229k' else -1.0
    best_metrics = None
    metrics_path = os.path.join(args.save_folder, 'class_metrics.json')
    if args.resume and args.dataset == 'resp229k' and os.path.isfile(metrics_path):
        with open(metrics_path) as f:
            saved_metrics = json.load(f)
        if is_trivial_score(saved_metrics):
            print('Ignoring trivial checkpoint Score {:.2f}; training from scratch'.format(
                float(saved_metrics.get('score', 50.0))))
            args.resume = None

    start_epoch = 1
    if args.resume:
        loaded_epoch = load_checkpoint(args, model, head, optimizer, device, refiner=refiner)
        if getattr(args, 'reset_epoch_on_resume', False):
            start_epoch = 1
            print('reset_epoch_on_resume: starting from epoch 1')
        else:
            start_epoch = loaded_epoch + 1
        if os.path.isfile(metrics_path):
            with open(metrics_path) as f:
                best_metrics = json.load(f)
            best_score = float(best_metrics['score'])
            print('Resume keeping best Score {:.2f}'.format(best_score))
    stale = 0
    ma_ckpt = None

    if getattr(args, 'eval_first', False):
        metrics, _, _, _ = evaluate(
            model, head, criterion, val_loader, device, args, refiner=refiner)
        abn = metrics['abnormal_recalls']
        print('Eval before train: Score {:.2f} Sp {:.1f} Se {:.1f} | cra {:.1f} whe {:.1f} both {:.1f}'.format(
            metrics['score'], metrics['sp'], metrics['se'],
            abn['crackle'], abn['wheeze'], abn['both']))

    for epoch in range(start_epoch, args.epochs + 1):
        adjust_learning_rate(args, optimizer, epoch)
        t0 = time.time()
        train_loss, train_acc = train_one_epoch(
            model, head, criterion, train_loader, optimizer, device, epoch, args, refiner=refiner)
        print('Train epoch {}, time {:.2f}s, loss {:.3f}, acc {:.2f}'.format(
            epoch, time.time() - t0, train_loss, train_acc))

        metrics, _, _, dual = evaluate(
            model, head, criterion, val_loader, device, args, refiner=refiner)
        abn = metrics['abnormal_recalls']
        pmax = metrics.get('positive_prob_max') or {}
        print('Val: Score {:.2f} Sp {:.1f} Se {:.1f} | cra {:.1f} whe {:.1f} both {:.1f} n→whe_fp {} | tau_c={:.3f} tau_w={:.3f} | pmax_c={:.3f} pmax_w={:.3f}'.format(
            metrics['score'], metrics['sp'], metrics['se'],
            abn['crackle'], abn['wheeze'], abn['both'], metrics['normal_wheeze_fp'],
            metrics['tau_crackle'], metrics['tau_wheeze'],
            float(pmax.get('crackle', 0.0)), float(pmax.get('wheeze', 0.0))))

        # Save the weights that were just scored. The moving average is the
        # starting point of the next epoch, not a rewrite of this epoch's checkpoint.
        trivial = args.dataset == 'resp229k' and is_trivial_score(metrics)
        if trivial:
            print('Skip best: Score {:.2f} is the all-normal baseline'.format(metrics['score']))
            stale += 1
        elif metrics['score'] > best_score:
            best_score = metrics['score']
            best_metrics = metrics
            stale = 0
            save_model(model, optimizer, args, epoch,
                       os.path.join(args.save_folder, 'best.pth'), head, feedback=refiner)
            with open(os.path.join(args.save_folder, 'best_threshold.json'), 'w') as f:
                json.dump({
                    'tau_crackle': dual['tau_crackle'],
                    'tau_wheeze': dual['tau_wheeze'],
                    'sp': dual['sp'],
                    'se': dual['se'],
                    'score': dual['score'],
                    'min_se': args.min_se,
                    'min_sp': args.min_sp,
                }, f, indent=2)
            with open(os.path.join(args.save_folder, 'class_metrics.json'), 'w') as f:
                json.dump(best_metrics, f, indent=2)
            print('New best Score {:.2f}'.format(best_score))
        else:
            stale += 1

        if args.ma_update:
            ma_ckpt = _apply_ma(args, model, refiner, ma_ckpt)
        if stale >= args.early_stop_patience:
            print('Early stopping after {} epochs without improvement'.format(stale))
            break

    if best_metrics:
        update_json(args.model_name, [
            best_metrics['sp'], best_metrics['se'], best_metrics['score'], 0.0])
    print('Finished. Best Score: {:.2f}'.format(best_score))

    if test_loader is not None and best_metrics is not None and len(test_loader.dataset) == 0:
        print('Test split has no timed event windows. Validation Score is the reported score.')
        with open(os.path.join(args.save_folder, 'test_metrics.json'), 'w') as f:
            json.dump({
                'skipped': True,
                'reason': 'no timed event windows in the test split',
                'sp': best_metrics['sp'],
                'se': best_metrics['se'],
                'score': best_metrics['score'],
            }, f, indent=2)
    elif test_loader is not None and best_metrics is not None:
        best_path = os.path.join(args.save_folder, 'best.pth')
        ckpt = torch.load(best_path, map_location=device, weights_only=False)
        model.load_state_dict(ckpt['model'])
        head.load_state_dict(ckpt['classifier'])
        if refiner is not None and ckpt.get('feedback'):
            refiner.load_state_dict(ckpt['feedback'])
        test_metrics, _, _, _ = evaluate(
            model, head, criterion, test_loader, device, args,
            fixed_taus=(best_metrics['tau_crackle'], best_metrics['tau_wheeze']),
            refiner=refiner)
        abn = test_metrics['abnormal_recalls']
        print('Test: Score {:.2f} Sp {:.1f} Se {:.1f} | cra {:.1f} whe {:.1f} both {:.1f} n→whe_fp {} | tau_c={:.3f} tau_w={:.3f}'.format(
            test_metrics['score'], test_metrics['sp'], test_metrics['se'],
            abn['crackle'], abn['wheeze'], abn['both'], test_metrics['normal_wheeze_fp'],
            test_metrics['tau_crackle'], test_metrics['tau_wheeze']))
        with open(os.path.join(args.save_folder, 'test_metrics.json'), 'w') as f:
            json.dump(test_metrics, f, indent=2)


if __name__ == '__main__':
    main()
