"""The NExT-GPT-lite model: encoders -> input projection -> LLM -> output projection -> decoders."""
from __future__ import annotations

import json
from dataclasses import dataclass, field

import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence

from .config import CLAP_REPO, CLIP_REPO, LLM_REPO, SD_REPO, model_path, pick_device, pick_dtype
from .constants import MODALITIES, MODALITY_ZH, SIGNAL_TOKENS, STAGE1_PROMPT
from .decoders.audio import AudioDecoder
from .decoders.image import ImageDecoder
from .decoders.video import VideoDecoder
from .encoders import ModalityEncoders
from .llm import LLM
from .projection import InputProjector, OutputProjector


@dataclass
class GenResult:
    text: str
    raw_text: str
    modalities: list[str] = field(default_factory=list)
    conds: dict[str, torch.Tensor] = field(default_factory=dict)


class NextGPTLite(nn.Module):
    def __init__(self, device: torch.device | None = None, dtype: torch.dtype | None = None,
                 load_decoders: bool = True, cond_tokens: int = 1, image_size: int = 512,
                 audio_seconds: float = 5.0, cond_dim_image: int = 768, cond_dim_audio: int = 512):
        super().__init__()
        self.device = device or pick_device()
        self.dtype = dtype or pick_dtype(self.device)
        self.image_size = image_size
        self.audio_seconds = audio_seconds
        self.cond_tokens = cond_tokens

        self.encoders = ModalityEncoders(model_path(CLIP_REPO), model_path(CLAP_REPO), dtype=self.dtype)
        self.encoders.to(self.device)
        self.llm_dtype = torch.bfloat16 if self.device.type == "cuda" else torch.float32
        self.llm = LLM(model_path(LLM_REPO), dtype=self.llm_dtype, device=self.device)
        self.llm.freeze()
        hidden = self.llm.hidden_size
        self.input_proj = nn.ModuleDict({m: InputProjector(self.encoders.dims[m], hidden) for m in MODALITIES})
        self.output_proj = nn.ModuleDict({
            "image": OutputProjector(hidden, cond_dim_image, cond_tokens),
            "video": OutputProjector(hidden, cond_dim_image, cond_tokens),
            "audio": OutputProjector(hidden, cond_dim_audio, 1),
        })
        self.input_proj.to(self.device)
        self.output_proj.to(self.device)

        self.image_decoder = None
        self.video_decoder = None
        self.audio_decoder = None
        if load_decoders:
            self.load_decoders()

    # ------------------------------------------------------------------ decoders
    def load_decoders(self) -> None:
        self.image_decoder = ImageDecoder(model_path(SD_REPO), dtype=self.dtype, device=str(self.device))
        self.video_decoder = VideoDecoder(self.image_decoder, frames=4)
        self.audio_decoder = AudioDecoder(cond_dim=512, n_frames=int(self.audio_seconds * 22050) // 512 + 1)
        self.audio_decoder.to(self.device)

    def trainable_parameters(self) -> list[nn.Parameter]:
        params = [p for p in self.input_proj.parameters()] + [p for p in self.output_proj.parameters()]
        params += [p for p in self.llm.model.parameters() if p.requires_grad]
        return params

    # ------------------------------------------------------------------ batching
    def splice_features(self, input_ids: torch.Tensor, features: torch.Tensor | None, modality: str | None,
                        attention_mask: torch.Tensor | None = None, labels: torch.Tensor | None = None):
        """Insert projected modality features right after the signal token."""
        input_ids = input_ids.to(self.device)
        attention_mask = attention_mask.to(self.device) if attention_mask is not None else None
        labels = labels.to(self.device) if labels is not None else None
        if features is None or modality is None:
            return self.llm.embed(input_ids), attention_mask, labels
        tok = self.llm.embed(input_ids)
        feats = features.to(self.device, torch.float32)
        proj = self.input_proj[modality](feats).to(tok.dtype)
        n = proj.shape[1]
        ids = input_ids.tolist()
        signal = self.llm.signal_ids[modality]
        pieces, masks, labs = [], [], []
        for b in range(input_ids.shape[0]):
            row = ids[b]
            pos = row.index(signal) if signal in row else -1
            if pos >= 0:
                pieces.append(torch.cat([tok[b, : pos + 1], proj[b], tok[b, pos + 1:]], dim=0))
                if attention_mask is not None:
                    m = attention_mask[b]
                    masks.append(torch.cat([m[: pos + 1], m.new_ones(n), m[pos + 1:]]))
                if labels is not None:
                    labs.append(torch.cat([labels[b, : pos + 1], labels.new_full((n,), -100), labels[b, pos + 1:]]))
            else:  # no signal token in the prompt: splice the modality features at the front
                pieces.append(torch.cat([proj[b], tok[b]], dim=0))
                if attention_mask is not None:
                    masks.append(torch.cat([attention_mask[b].new_ones(n), attention_mask[b]]))
                if labels is not None:
                    labs.append(torch.cat([labels[b].new_full((n,), -100), labels[b]]))
        embeds = pad_sequence(pieces, batch_first=True, padding_value=0.0)
        mask = pad_sequence(masks, batch_first=True, padding_value=0) if masks else None
        lab = pad_sequence(labs, batch_first=True, padding_value=-100) if labs else None
        return embeds, mask, lab

    def _lm_loss(self, input_ids, features, modality, attention_mask, labels):
        embeds, mask, lab = self.splice_features(input_ids, features, modality, attention_mask, labels)
        bb = self.llm.backbone()
        hs = bb.model(inputs_embeds=embeds, attention_mask=mask).last_hidden_state
        hs, tgt = hs[:, :-1], lab[:, 1:]
        sel = tgt != -100
        if sel.sum() == 0:
            return torch.zeros((), device=embeds.device, requires_grad=True)
        logits = bb.lm_head(hs[sel])
        return torch.nn.functional.cross_entropy(logits.float(), tgt[sel])
    # ------------------------------------------------------------------ stages
    def stage1_loss(self, batch) -> dict:
        """Enc-side alignment: caption / describe the attached modality (input projection only)."""
        loss = self._lm_loss(batch["input_ids"], batch["features"], batch["modality"],
                             batch["attention_mask"], batch["labels"])
        return {"loss": loss, "lm_loss": loss.detach()}

    def stage2_loss(self, batch) -> dict:
        """Dec-side alignment: predict the decoder caption embedding from the signal token."""
        input_ids = batch["input_ids"]
        attention_mask = batch["attention_mask"]
        embeds, mask, _ = self.splice_features(input_ids, None, None, attention_mask, None)
        bb = self.llm.backbone()
        hs = bb.model(inputs_embeds=embeds, attention_mask=mask).last_hidden_state
        modality = batch["modality"]
        signal = self.llm.signal_ids[modality]
        pos = []
        for row in input_ids.tolist():
            pos.append(len(row) - 1 - row[::-1].index(signal))
        h = torch.stack([hs[b, p] for b, p in enumerate(pos)])
        pred = self.output_proj[modality](h.float()).reshape(h.shape[0], -1)
        target = batch["target"].to(self.device, pred.dtype).reshape(pred.shape)
        emb_loss = torch.nn.functional.smooth_l1_loss(pred, target)
        prev = torch.stack([hs[b, p - 1] for b, p in enumerate(pos)])
        ce = torch.nn.functional.cross_entropy(
            bb.lm_head(prev).float(), torch.full((len(pos),), signal, device=hs.device))
        return {"loss": emb_loss + 0.1 * ce, "emb_loss": emb_loss.detach(), "signal_ce": ce.detach()}

    def forward(self, batch, stage: int) -> dict:
        if stage == 1:
            return self.stage1_loss(batch)
        if stage == 2:
            return self.stage2_loss(batch)
        return self.stage1_loss(batch)  # stage 3 shares the LM objective

    # ------------------------------------------------------------------ inference
    @torch.no_grad()
    def encode_modality(self, modality: str, data) -> torch.Tensor:
        if modality == "image":
            px = self.encoders.clip.preprocess(data)
            return self.encoders.clip(px.to(self.device, self.dtype))
        if modality == "video":
            frames = data  # list of PIL images
            px = torch.stack([self.encoders.clip.preprocess(f)[0] for f in frames]).unsqueeze(0)
            return self.encoders.video(px.to(self.device, self.dtype))
        if modality == "audio":
            audio = data  # (1, samples) at 48 kHz for CLAP
            return self.encoders.audio(audio.to(self.device, self.dtype))
        raise ValueError(modality)

    @torch.no_grad()
    def chat(self, messages: list[dict], modality: str | None = None, features: torch.Tensor | None = None,
             max_new_tokens: int = 96, do_sample: bool = False, temperature: float = 0.7,
             top_p: float = 0.9, seed: int | None = None) -> GenResult:
        prompt = self.llm.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
        enc = self.llm.tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to(self.device)
        embeds, mask, _ = self.splice_features(enc["input_ids"], features, modality, enc["attention_mask"], None)
        if seed is not None:
            torch.manual_seed(seed)
        gen_ids = self.llm.generate(
            embeds, attention_mask=mask, max_new_tokens=max_new_tokens, do_sample=do_sample,
            temperature=temperature if do_sample else None, top_p=top_p if do_sample else None,
            pad_token_id=self.llm.tokenizer.pad_token_id, eos_token_id=self.llm.tokenizer.eos_token_id,
        )
        new_ids = gen_ids[0]
        raw = self.llm.tokenizer.decode(new_ids, skip_special_tokens=False)
        out_modalities, conds = [], {}
        if any(t in raw for t in SIGNAL_TOKENS.values()):
            full_embeds = torch.cat([embeds[0], self.llm.embed(new_ids.unsqueeze(0))[0]], dim=0).unsqueeze(0)
            full_mask = torch.ones(full_embeds.shape[:2], device=embeds.device, dtype=torch.long)
            hs = self.llm.model(inputs_embeds=full_embeds, attention_mask=full_mask, output_hidden_states=True).hidden_states[-1]
            for m, tok in SIGNAL_TOKENS.items():
                tid = self.llm.signal_ids[m]
                idx = (new_ids == tid).nonzero(as_tuple=True)[0]
                if len(idx):
                    cond = self.output_proj[m](hs[0, embeds.shape[1] + int(idx[0])].float())
                    conds[m] = cond
                    out_modalities.append(m)
        text = self.llm.tokenizer.decode(new_ids, skip_special_tokens=True).strip()
        return GenResult(text=text, raw_text=raw, modalities=out_modalities, conds=conds)

    @torch.no_grad()
    def caption(self, features: torch.Tensor, modality: str, max_new_tokens: int = 32,
                do_sample: bool = False) -> str:
        """M -> T using exactly the stage-1 prompt format (a chat template would be OOD here)."""
        prompt = SIGNAL_TOKENS[modality] + " " + STAGE1_PROMPT[modality]
        ids = self.llm.tokenizer(prompt, return_tensors="pt", add_special_tokens=False).input_ids.to(self.device)
        mask = torch.ones_like(ids)
        embeds, mask, _ = self.splice_features(ids, features, modality, mask, None)
        gen = self.llm.generate(embeds, attention_mask=mask, max_new_tokens=max_new_tokens,
                                do_sample=do_sample, pad_token_id=self.llm.tokenizer.pad_token_id,
                                eos_token_id=self.llm.tokenizer.eos_token_id)
        # generate() with inputs_embeds returns only the newly generated tokens
        return self.llm.tokenizer.decode(gen[0], skip_special_tokens=True).strip()

    @torch.no_grad()
    def condition_from_text(self, text: str, modality: str) -> torch.Tensor:
        """Stage-2 style conditioning: append the signal token to a caption and project its hidden state.

        Lets the pipeline generate a chosen modality even before stage-3 instruction tuning teaches
        the LLM to emit signal tokens on its own.
        """
        prompt = f"Generate the {modality} described by: {text}\n{SIGNAL_TOKENS[modality]}"
        ids = self.llm.tokenizer(prompt, return_tensors="pt").input_ids.to(self.device)
        hs = self.llm.backbone().model(inputs_embeds=self.llm.embed(ids)).last_hidden_state
        return self.output_proj[modality](hs[0, -1].float())

    @torch.no_grad()
    def generate_image(self, cond: torch.Tensor, steps: int = 20, size: int | None = None,
                       seed: int | None = None, guidance: float = 7.5):
        c = cond.reshape(1, self.cond_tokens, -1)
        return self.image_decoder.decode(c, steps=steps, size=size or self.image_size,
                                         seed=seed, guidance=guidance)[0].numpy()

    @torch.no_grad()
    def generate_image_from_text(self, prompt: str, steps: int = 20, size: int = 512,
                                 guidance: float = 7.5, seed: int | None = 0):
        """Text-assisted decode: the prompt goes through the frozen SD text encoder.

        Documented deviation: with ~6k training pairs the signal-vector regressor cannot
        reproduce SD's 77-token conditioning (see report), so the deployed demo conditions the
        UNet on the text encoder output while the faithful signal path remains available.
        """
        tokens = self.image_decoder.encode_caption_tokens([prompt])
        return self.image_decoder.decode(tokens, steps=steps, size=size, seed=seed, guidance=guidance)[0].numpy()

    @torch.no_grad()
    def generate_video_from_text(self, prompt: str, size: int = 512, steps: int = 20, seed: int = 0):
        tokens = self.image_decoder.encode_caption_tokens([prompt])
        return self.video_decoder.decode(tokens, size=size, steps=steps, seed=seed)

    @torch.no_grad()
    def generate_video(self, cond: torch.Tensor, size: int | None = None, seed: int | None = None):
        c = cond.reshape(1, self.cond_tokens, -1)
        return self.video_decoder.decode(c, size=size or self.image_size, seed=seed or 0)

    @torch.no_grad()
    def generate_audio(self, cond: torch.Tensor, steps: int = 50, seed: int | None = None):
        c = cond.reshape(1, -1).expand(1, -1)
        logmel = self.audio_decoder.sample(c, steps=steps, seed=seed)
        return self.audio_decoder.frontend.to_waveform(logmel)[0].cpu()

    # ------------------------------------------------------------------ checkpoints
    def save_projections(self, path) -> None:
        torch.save({
            "input_proj": self.input_proj.state_dict(),
            "output_proj": self.output_proj.state_dict(),
            "cond_tokens": self.cond_tokens,
        }, path)

    def load_projections(self, path) -> None:
        ckpt = torch.load(path, map_location=self.device)
        self.input_proj.load_state_dict(ckpt["input_proj"])
        for key in ("image", "video", "audio"):
            sub = {k[len(key) + 1:]: v for k, v in ckpt["output_proj"].items() if k.startswith(key + ".")}
            if not sub:
                continue
            try:
                self.output_proj[key].load_state_dict(sub)
            except RuntimeError:
                print(f"[load_projections] skip incompatible output_proj[{key}] from {path}")

    def trainable_state(self) -> dict:
        return {
            "input_proj": self.input_proj.state_dict(),
            "output_proj": self.output_proj.state_dict(),
        }

    def load_trainable_state(self, state: dict) -> None:
        self.input_proj.load_state_dict(state["input_proj"])
        self.output_proj.load_state_dict(state["output_proj"])

