"""Locked RF-DETR numerics with declared sensor research adaptations."""
from __future__ import annotations

import torch

from .recipes import build_rfdetr_optimizer


def validate_constraints(*, size, effective_batch, epochs, patience, mosaic,
                         warmup_epochs, min_lr_ratio):
    if (size != 640 or effective_batch != 16 or not 1 <= epochs <= 300
            or patience != 50 or mosaic or warmup_epochs != 0 or min_lr_ratio != .01):
        raise ValueError("RF official_research_constrained requires size=640, effective_batch=16, "
                         "1<=epochs<=300, patience=50, mosaic=False, warmup_epochs=0; "
                         "min_lr_ratio=.01 is unused by the official step scheduler")


class RFResearchEMA:
    """Use the installed EMA callback's averaging, counter and state unchanged."""
    def __init__(self, model):
        from rfdetr.training.callbacks.ema import RFDETREMACallback
        from torch.optim.swa_utils import AveragedModel

        self.callback = RFDETREMACallback(decay=.993, tau=100, use_buffers=True,
                                          update_interval_steps=1)
        self.callback._average_model = AveragedModel(
            model, use_buffers=True, multi_avg_fn=self.callback._multi_avg_fn).eval()
        for parameter in self.ema.parameters():
            parameter.requires_grad_(False)

    @property
    def ema(self):
        return self.callback._average_model.module

    @property
    def updates(self):
        return int(self.callback._average_model.n_averaged.item())

    def update(self, model, successful_steps):
        self.callback._update_ema_for_step(model, successful_steps)

    def state_dict(self):
        return self.callback.state_dict()

    def load_state_dict(self, state, model):
        self.callback.load_state_dict(state)
        self.callback._restore_pending_average_state(model)


class RFResearchRecipe:
    """Official groups, managed step scheduler and EMA on project sensor tensors.

    Full equal microbatch windows average the official criterion loss exactly
    once, matching Lightning automatic optimization. Epoch tails use an actual
    example-weighted average, rather than Lightning's fixed accumulation divisor.
    Criterion box normalization remains per microbatch, as in upstream detection.
    """
    clip_max_norm = .1
    accumulation_policy = "fixed16_actual_example_mean_epoch_tail"

    def __init__(self, model, *, samples, epochs, batch_size, num_batches, amp_dtype):
        from rfdetr.config import TrainConfig
        from rfdetr.training.module_model import _build_managed_scheduler

        self.model = model
        config = TrainConfig(dataset_dir=".", epochs=epochs, batch_size=batch_size,
                             grad_accum_steps=16 // batch_size, warmup_epochs=0.)
        self.fused = bool(next(model.parameters()).is_cuda and amp_dtype == torch.bfloat16
                          and model.model_config.fused_optimizer and torch.cuda.is_bf16_supported())
        self.optimizer = build_rfdetr_optimizer(
            model, core_model=model.model, allow_adapter_parameters=True, fused=self.fused)
        self.steps_per_epoch = max(1, (num_batches + config.grad_accum_steps - 1) // config.grad_accum_steps)
        self.warmup_iterations = 0
        self.scheduler = _build_managed_scheduler(
            self.optimizer, config, epochs * self.steps_per_epoch, self.steps_per_epoch, 0)
        self.ema = RFResearchEMA(model)
        self.optimizer_updates = 0
        self.resolved_optimizer = {"name": "AdamW", "lr": config.lr,
                                   "lr_encoder": config.lr_encoder,
                                   "weight_decay": config.weight_decay, "betas": [.9, .999],
                                   "fused": self.fused, "clip_max_norm": .1,
                                   "scheduler_interval": "optimizer_step",
                                   "lr_drop_epochs": 100, "steps_per_epoch": self.steps_per_epoch,
                                   "adapter_extension": "sensor_adapter_base_lr_weight_decay"}

    def begin_epoch(self):
        pass

    def warmup(self, iteration, epoch):
        pass

    def after_step(self, successful):
        if successful:
            self.optimizer_updates += 1
            self.scheduler.step()
            self.ema.update(self.model, self.optimizer_updates)

    def end_epoch(self):
        pass

    def state_dict(self):
        return {"ema": self.ema.ema.state_dict(), "ema_updates": self.ema.updates,
                "ema_callback": self.ema.state_dict(), "optimizer_updates": self.optimizer_updates,
                "resolved_optimizer": self.resolved_optimizer,
                "accumulation_policy": self.accumulation_policy,
                "selection_model": "ema"}

    def load_state_dict(self, state):
        self.ema.load_state_dict(state["ema_callback"], self.model)
        self.optimizer_updates = state["optimizer_updates"]
        if self.ema.updates != state["ema_updates"]:
            raise ValueError("RF EMA counter differs from saved callback state")
