"""Isolated state-carry experiment for the pinned Fish S2-Pro *codec*.

No learned parameter or vendor source is modified. Calls install temporary module
forward overrides and always restore them. Do not share the wrapped model across
threads while a call is active. A cache snapshot denotes the state *before* the
next frame, so overlapping requests must restore that boundary rather than append
already-consumed frames as new timeline positions.
"""
from contextlib import contextmanager
import types

import torch
from torch import nn


def _copy_state(value):
    if torch.is_tensor(value):
        return value.clone()
    if isinstance(value, dict):
        return {key: _copy_state(item) for key, item in value.items()}
    if isinstance(value, list):
        return [_copy_state(item) for item in value]
    return value


class _BoundedKV(nn.Module):
    """Adapter to existing Attention.forward; owns no trained parameters."""

    def __init__(self, state, key, keep):
        super().__init__()
        self.state = state
        self.key = key
        self.keep = keep

    def update(self, positions, k, v):
        previous = self.state.get(self.key)
        if previous is not None:
            if int(previous['positions'][-1]) + 1 != int(positions[0]):
                raise ValueError('KV frames must be monotonic; restore a snapshot before replay')
            k = torch.cat((previous['k'], k), dim=2)
            v = torch.cat((previous['v'], v), dim=2)
            positions = torch.cat((previous['positions'], positions))
        self.state[self.key] = {
            'k': k[:, :, -self.keep:].clone(),
            'v': v[:, :, -self.keep:].clone(),
            'positions': positions[-self.keep:].clone(),
        }
        return k, v


class FishStateDecoder:
    """Decode [1,Q,T] with no, KV-only, conv-only, or complete causal state.

    Modes are experimental ablations. KV-only resets convolution boundaries;
    conv-only resets the transformer's attention history. ``all`` carries both.
    Full state is expected to reproduce full decoding to floating-point tolerance,
    including an uneven final chunk. The encoder is never patched or rerun.
    """

    MODES = ('none', 'kv-only', 'conv-only', 'all')

    def __init__(self, model, mode='all'):
        if mode not in self.MODES:
            raise ValueError(f'Unsupported mode {mode!r}: {self.MODES}')
        self.model = model
        self.mode = mode
        self.transformer = model.quantizer.post_module
        if self.transformer.__class__.__name__ != 'WindowLimitedTransformer':
            raise ValueError('Expected pinned Fish WindowLimitedTransformer')
        if not self.transformer.causal:
            raise ValueError('This helper supports causal Fish checkpoints only')
        if self.transformer.config.pos_embed_type != 'rope':
            raise ValueError('This helper supports RoPE positional embeddings only')
        if not isinstance(self.transformer.look_ahead_conv, nn.Identity):
            raise ValueError('Unimplemented look-ahead convolution state')
        if self.transformer.window_size is None or self.transformer.window_size < 2:
            raise ValueError('Expected a bounded attention window')
        self.window = int(self.transformer.window_size)
        self.convs = []
        for prefix, root in [('quantizer.upsample', model.quantizer.upsample),
                             ('decoder', model.decoder)]:
            for name, module in root.named_modules():
                kind = module.__class__.__name__
                if kind == 'CausalConvNet':
                    if module.conv.stride != (1,):
                        raise ValueError('Decode Conv1d stride != 1 needs phase-state support')
                    self.convs.append((f'{prefix}.{name}', module, 'conv'))
                elif kind == 'CausalTransConvNet':
                    if module.conv.dilation != (1,) or module.conv.padding != (0,):
                        raise ValueError('Unsupported transposed-convolution geometry')
                    if module.kernel_size - module.stride > module.stride:
                        raise ValueError('Long overlap tail requires additional implementation')
                    self.convs.append((f'{prefix}.{name}', module, 'transconv'))
        self.reset()

    def reset(self):
        self.cursor = 0
        self.state = {}
        self.last_work_frames = 0

    def snapshot(self):
        return {'mode': self.mode, 'cursor': self.cursor, 'state': _copy_state(self.state)}

    def restore(self, snapshot):
        if snapshot['mode'] != self.mode:
            raise ValueError('Snapshot mode mismatch')
        self.cursor = int(snapshot['cursor'])
        self.state = _copy_state(snapshot['state'])

    def state_bytes(self):
        def size(value):
            if torch.is_tensor(value):
                return value.numel() * value.element_size()
            if isinstance(value, dict):
                return sum(size(item) for item in value.values())
            return 0
        return size(self.state)

    def _conv(self, module, x, key):
        history_length = (module.conv.kernel_size[0] - 1) * module.conv.dilation[0]
        if history_length == 0:
            return module.conv(x).contiguous()
        history = self.state.get(key)
        if history is None:
            history = x.new_zeros((x.shape[0], x.shape[1], history_length))
        joined = torch.cat((history, x), dim=-1)
        self.state[key] = joined[..., -history_length:].clone()
        return module.conv(joined).contiguous()

    def _transconv(self, module, x, key):
        raw = module.conv(x)
        emitted = x.shape[-1] * module.stride
        tail_length = module.kernel_size - module.stride
        if tail_length:
            carry = self.state.get(key)
            if carry is not None:
                raw[..., :tail_length] += carry
            bias = module.conv.bias
            tail = raw[..., emitted:].clone()
            if bias is not None:
                tail -= bias[None, :, None]
            self.state[key] = tail
        return raw[..., :emitted].contiguous()

    def _transform(self, module, x):
        if module.channels_first:
            x = x.transpose(1, 2)
        x = module.look_ahead_conv(module.input_proj(x))
        positions = torch.arange(self.cursor, self.cursor + x.shape[1], device=x.device)
        if int(positions[-1]) >= module.freqs_cis.shape[0]:
            raise ValueError('Absolute timeline exceeds pinned RoPE buffer')
        previous = self.state.get('kv.0')
        keys = positions if previous is None else torch.cat((previous['positions'], positions))
        mask = ((keys[None, :] <= positions[:, None]) &
                (keys[None, :] >= positions[:, None] - self.window + 1))[None, None]
        frequencies = module.freqs_cis[positions]
        for layer in module.layers:
            x = layer(x, positions, frequencies, mask)
        x = module.output_proj(module.norm(x))
        if module.channels_first:
            x = x.transpose(1, 2)
        return x

    @contextmanager
    def _overrides(self):
        restored = []
        previous_caches = []
        try:
            if self.mode in ('kv-only', 'all'):
                for index, layer in enumerate(self.transformer.layers):
                    attention = layer.attention
                    previous_caches.append((attention, attention.kv_cache))
                    attention.kv_cache = _BoundedKV(self.state, f'kv.{index}', self.window - 1)
                restored.append((self.transformer, self.transformer.forward))
                self.transformer.forward = types.MethodType(
                    lambda module, x, x_lens=None: self._transform(module, x), self.transformer)
            if self.mode in ('conv-only', 'all'):
                for key, module, kind in self.convs:
                    restored.append((module, module.forward))
                    if kind == 'conv':
                        def forward(current, x, state_key=key):
                            return self._conv(current, x, state_key)
                    else:
                        def forward(current, x, state_key=key):
                            return self._transconv(current, x, state_key)
                    module.forward = types.MethodType(forward, module)
            yield
        finally:
            for module, original in reversed(restored):
                module.forward = original
            for attention, original in reversed(previous_caches):
                attention.kv_cache = original

    @torch.inference_mode()
    def decode(self, codes):
        if codes.ndim != 3 or codes.shape[0] != 1 or codes.shape[-1] < 1:
            raise ValueError('Expected nonempty codes[1,Q,T]')
        if self.model.training:
            raise ValueError('State experiments require model.eval()')
        with self._overrides():
            # Upstream quantizer clamps indices in-place; never modify cached tokens.
            result = self.model.from_indices(codes.clone())
        self.cursor += codes.shape[-1]
        self.last_work_frames = int(codes.shape[-1])
        return result

    __call__ = decode

    @torch.inference_mode()
    def decode_window(self, codes, commit_frames):
        """Render W frames but commit exactly the first S timeline frames.

        Overlap samples are provisional and can be decoded again, never appended
        twice to the cache. Keeping each full window as a single decoder call is
        essential for the KV-only and conv-only ablations: splitting the window
        would introduce an extra artificial reset. The safe fallback re-decodes
        its first S frames solely to capture the committed state, costing W+S
        frames when S<W. ``last_work_frames`` exposes that actual compute budget.
        """
        width = int(codes.shape[-1])
        commit_frames = int(commit_frames)
        if not 1 <= commit_frames <= width:
            raise ValueError('commit_frames must be between 1 and window width')
        before = self.snapshot()
        wave = self.decode(codes)
        if commit_frames < width:
            self.restore(before)
            self.decode(codes[..., :commit_frames])
            self.last_work_frames = width + commit_frames
        else:
            self.last_work_frames = width
        return wave
