"""Preprocess raw TH06 observation grids through a trained CNN encoder."""

from __future__ import annotations

from pathlib import Path
from typing import Optional, TYPE_CHECKING

import numpy as np
import torch

from cnn.trainer import GridAutoencoder, training_device
from encoder import EncoderConfig, ObservationEncoder
from protocol import StateMessage

if TYPE_CHECKING:
    from cnn_training_ui import CnnTrainingUi


class CnnObservationEncoder:
    """Replace two raw 32x32 grids with the autoencoder's latent vector."""

    def __init__(self, config: Optional[EncoderConfig], weights_path: Path, use_cpu: bool = False):
        self.raw_encoder = ObservationEncoder(config)
        self.dataset = self.raw_encoder.dataset
        self.device = torch.device("cpu") if use_cpu else training_device()
        if not weights_path.exists():
            raise FileNotFoundError(
                f"CNN weights not found: {weights_path}. Train the autoencoder before starting CNN NEAT."
            )
        checkpoint = torch.load(weights_path, map_location=self.device, weights_only=False)
        if not isinstance(checkpoint, dict) or "model" not in checkpoint:
            raise ValueError(f"CNN weights must contain a model state dictionary: {weights_path}")
        self.latent_dim = int(checkpoint.get("latent_dim", 64))
        self.model = GridAutoencoder(self.latent_dim).to(self.device)
        self.model.load_state_dict(checkpoint["model"])
        self.model.eval()
        self.ui: CnnTrainingUi | None = None

    @property
    def dim(self) -> int:
        return self.latent_dim + 2

    def set_ui(self, ui: CnnTrainingUi) -> None:
        self.ui = ui

    def reset(self) -> None:
        self.raw_encoder.reset()

    def flush_dataset(self) -> None:
        self.raw_encoder.flush_dataset()

    def encode(self, state: StateMessage, previous_action: int = 0) -> list[float]:
        raw_observation = self.raw_encoder.encode(state, previous_action)
        raw_grids = np.asarray(raw_observation[:-2], dtype=np.float32).reshape(1, 2, 32, 32)
        inputs = torch.from_numpy(np.clip(raw_grids, 0.0, 1.0)).to(self.device)
        with torch.inference_mode():
            latent = self.model.encoder(inputs)[0].cpu().tolist()
        if self.ui is not None:
            self.ui.set_raw_observation(raw_observation[:-2])
            self.ui.set_cnn_latent(latent)
        return latent + raw_observation[-2:]
