"""Experimental exact-state streaming for the installed Qwen 12 Hz decoder.

This is not a package patch.  The checkpoint's causal attention masks, RoPE,
quantizer, pointwise operations and final clamp are unchanged.  Only the omitted
causal convolution history and already-supported transformer KV cache persist.
Instances sharing one decoder MUST NOT be called concurrently: convolution
forward methods are temporarily replaced, and are restored even on exceptions.
"""
from __future__ import annotations

import copy
from contextlib import contextmanager
from dataclasses import dataclass
from types import MethodType

import torch
import torch.nn.functional as F


@dataclass
class QwenStateSnapshot:
    kv: object
    conv: dict[str, torch.Tensor]
    kv_position: int
    committed_frames: int


class QwenStateDecoder:
    """Wrap ``adapter.model.decoder``; input is integer ``[1,16,T]``.

    ``decode_chunk`` commits its entire input. ``decode_window`` commits only
    the first ``commit_frames`` and rolls back speculative overlap suffix state.
    Carry flags reset the corresponding state ONCE, at the window boundary;
    split prefix/suffix calls always preserve their within-window state.
    """

    def __init__(self, decoder):
        self.decoder = decoder
        self.modules = {}
        for name, module in decoder.named_modules():
            kind = type(module).__name__
            if kind == 'Qwen3TTSTokenizerV2CausalConvNet':
                if module.stride != 1:
                    raise ValueError(f'Only decoder stride-one causal conv supported: {name}')
                self.modules[name] = ('conv', module)
            elif kind == 'Qwen3TTSTokenizerV2CausalTransConvNet':
                stride = module.conv.stride[0]
                if module.left_pad != 0 or module.right_pad > stride:
                    raise ValueError(f'Unsupported causal transpose geometry: {name}')
                self.modules[name] = ('transpose', module)
        if not self.modules or not hasattr(decoder, 'pre_transformer'):
            raise TypeError('Expected installed Qwen3-TTS 12 Hz decoder')
        if any(not layer.self_attn.is_causal for layer in decoder.pre_transformer.layers):
            raise ValueError('Noncausal checkpoint is not valid for exact KV streaming')
        self.reset()

    def reset(self, kv=True, conv=True):
        if kv:
            self.kv = None
            self.kv_position = 0
        if conv:
            self.conv = {}
        if kv and conv:
            self.committed_frames = 0

    @torch.inference_mode()
    def snapshot(self):
        # DynamicSlidingWindowLayer has both compact tensors and cumulative
        # counters: copy the complete object, not merely its public tensor list.
        return QwenStateSnapshot(copy.deepcopy(self.kv),
                                 {n: x.clone() for n, x in self.conv.items()},
                                 self.kv_position, self.committed_frames)

    @torch.inference_mode()
    def restore(self, snapshot):
        self.kv = copy.deepcopy(snapshot.kv)
        self.conv = {n: x.clone() for n, x in snapshot.conv.items()}
        self.kv_position = snapshot.kv_position
        self.committed_frames = snapshot.committed_frames

    def state_info(self):
        layers = getattr(self.kv, 'layers', []) if self.kv is not None else []
        tensors = [t for layer in layers for t in (getattr(layer, 'keys', None),
                                                   getattr(layer, 'values', None))
                   if isinstance(t, torch.Tensor)]
        return {'kv_position': self.kv_position,
                'committed_frames': self.committed_frames,
                'kv_layers': len(layers),
                'kv_tensor_bytes': sum(t.numel() * t.element_size() for t in tensors),
                'conv_tensor_bytes': sum(t.numel() * t.element_size() for t in self.conv.values()),
                'convolution_states': len(self.conv)}

    @contextmanager
    def _convolution_history(self):
        originals = []
        try:
            for name, (kind, module) in self.modules.items():
                # Preserve whether a local attribute existed, rather than leaving
                # a bound-method shadow on the original class after restoration.
                local = module.__dict__.get('forward')
                had_local = 'forward' in module.__dict__
                originals.append((module, had_local, local))
                if kind == 'conv':
                    def forward(mod, x, state_name=name):
                        padding = mod.padding
                        previous = self.conv.get(state_name)
                        if previous is None:
                            previous = x.new_zeros(x.shape[0], x.shape[1], padding)
                        elif previous.shape[:2] != x.shape[:2]:
                            raise ValueError('Stream batch/channel geometry changed without reset')
                        inputs = torch.cat((previous, x), dim=-1) if padding else x
                        if padding:
                            self.conv[state_name] = inputs[..., -padding:].clone()
                        return mod.conv(inputs).contiguous()
                else:
                    def forward(mod, x, state_name=name):
                        y = mod.conv(x)
                        tail = mod.right_pad
                        if tail:
                            previous = self.conv.get(state_name)
                            if previous is not None:
                                y[..., :tail] += previous
                            bias = (0 if mod.conv.bias is None else
                                    mod.conv.bias.view(1, -1, 1))
                            self.conv[state_name] = (y[..., -tail:] - bias).clone()
                            y = y[..., :-tail]
                        return y.contiguous()
                module.forward = MethodType(forward, module)
            yield
        finally:
            for module, had_local, original in reversed(originals):
                if had_local:
                    module.forward = original
                else:
                    delattr(module, 'forward')

    @torch.inference_mode()
    def _step(self, codes):
        if codes.ndim != 3 or codes.shape[0] != 1 or codes.shape[1] != self.decoder.config.num_quantizers:
            raise ValueError('Expected codes [1, num_quantizers, token_frames]')
        frames = codes.shape[-1]
        if frames < 1:
            raise ValueError('Empty streaming chunk')
        with self._convolution_history():
            hidden = self.decoder.quantizer.decode(codes)
            hidden = self.decoder.pre_conv(hidden).transpose(1, 2)
            positions = torch.arange(self.kv_position, self.kv_position + frames,
                                     device=codes.device, dtype=torch.long)
            result = self.decoder.pre_transformer(
                inputs_embeds=hidden, past_key_values=self.kv, use_cache=True,
                cache_position=positions, position_ids=positions.unsqueeze(0))
            self.kv = result.past_key_values
            self.kv_position += frames
            hidden = result.last_hidden_state.permute(0, 2, 1)
            for blocks in self.decoder.upsample:
                for block in blocks:
                    hidden = block(hidden)
            for block in self.decoder.decoder:
                hidden = block(hidden)
        self.committed_frames += frames
        wave = hidden.clamp(-1, 1)
        expected = frames * int(self.decoder.total_upsample)
        if wave.shape != (1, 1, expected) or not torch.isfinite(wave).all():
            raise RuntimeError(f'Invalid streaming waveform {wave.shape}, expected {expected}')
        return wave

    @torch.inference_mode()
    def decode_chunk(self, codes, carry_kv=True, carry_conv=True):
        self.reset(kv=not carry_kv, conv=not carry_conv)
        return self._step(codes)

    @torch.inference_mode()
    def decode_window(self, codes, commit_frames, carry_kv=True, carry_conv=True):
        """Return entire window audio, but advance the stream by exactly stride.

        Pass ``commit_frames=min(stride_frames, window_actual_frames)``.  The
        speculative suffix is not silently added to history a second time when
        the next overlapping window arrives.  Full-state carry yields identical
        contextual audio in overlap regions, apart from numerical rounding.
        """
        if not 1 <= commit_frames <= codes.shape[-1]:
            raise ValueError('commit_frames must be in [1, window_actual_frames]')
        self.reset(kv=not carry_kv, conv=not carry_conv)
        before_committed = self.committed_frames
        prefix = self._step(codes[..., :commit_frames])
        if commit_frames == codes.shape[-1]:
            return prefix
        committed = self.snapshot()
        try:
            suffix = self._step(codes[..., commit_frames:])
            return torch.cat((prefix, suffix), dim=-1)
        finally:
            self.restore(committed)
            assert self.committed_frames == before_committed + commit_frames

