"""CNN-specific observation panel layered over the standard NEAT dashboard."""

from __future__ import annotations

import importlib.util
import math
import sys
from pathlib import Path

import pygame


def _load_base_ui():
    path = Path(__file__).resolve().parent.parent / "training_ui.py"
    spec = importlib.util.spec_from_file_location("base_training_ui", path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Unable to load training UI: {path}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module.TrainingUi


BaseTrainingUi = _load_base_ui()


class CnnTrainingUi(BaseTrainingUi):
    def __post_init__(self) -> None:
        self.raw_observation: list[float] | None = None
        self.cnn_latent: list[float] | None = None
        self.generation_offset = 0
        super().__post_init__()
        pygame.display.set_caption("Touhou 6 AI | CNN + NEAT Training")

    def set_raw_observation(self, observation: list[float]) -> None:
        self.raw_observation = observation

    def set_cnn_latent(self, latent: list[float]) -> None:
        self.cnn_latent = latent

    def set_generation_offset(self, offset: int) -> None:
        self.generation_offset = offset

    def draw(self, generation: int, best_genome=None, current_genome: int | None = None) -> None:
        super().draw(generation + self.generation_offset, best_genome, current_genome)

    def _observation_panel(self, rect: pygame.Rect) -> None:
        pygame.draw.rect(self.screen, (24, 30, 45), rect)
        self._text("CNN INPUT / LATENT", (rect.x + 10, rect.y + 10), (225, 232, 245), self.small_font)
        if self.raw_observation is None:
            self._text("waiting for observation", (rect.x + 10, rect.y + 34), (130, 145, 165), self.small_font)
            return
        size = min(280, (rect.width - 68) // 2)
        gap = 32
        start_x = rect.x + (rect.width - 2 * size - gap) // 2
        for layer, (label, color) in enumerate((("danger path", (255, 75, 65)), ("powerups", (85, 170, 255)))):
            x = start_x + layer * (size + gap)
            self._text(label, (x, rect.y + 20), color, self.small_font)
            self._grid(pygame.Rect(x, rect.y + 42, size, size), self.raw_observation[layer * 1024:(layer + 1) * 1024], color)
        self._text(f"grid samples collected: {self.dataset_samples:,}", (start_x, rect.y + 330),
                   (180, 195, 220), self.small_font)
        self._text("CNN latent (8x8)", (start_x, rect.y + 350), (170, 190, 255), self.small_font)
        if self.cnn_latent is not None:
            self._latent_grid(pygame.Rect(start_x + 140, rect.y + 342, 80, 80), self.cnn_latent)

    def _latent_grid(self, rect: pygame.Rect, values: list[float]) -> None:
        if len(values) != 64:
            return
        scale = max(1e-6, max(abs(value) for value in values))
        cell_size = rect.width / 8.0
        for index, value in enumerate(values):
            row, column = divmod(index, 8)
            intensity = min(255, int(abs(value) / scale * 255))
            color = (intensity, 0, 0) if value < 0 else (0, 0, intensity)
            pygame.draw.rect(self.screen, color, (rect.x + int(column * cell_size), rect.y + int(row * cell_size),
                                                   max(1, math.ceil(cell_size)), max(1, math.ceil(cell_size))))
        pygame.draw.rect(self.screen, (120, 135, 180), rect, 1)
