"""Archivo de programas con islas y selección estable; no ejecuta código."""
from dataclasses import dataclass
import math
from random import Random


@dataclass(frozen=True)
class Program:
    source: str
    score: float


class ProgramDatabase:
    def __init__(self, islands, seed=0):
        if islands < 1:
            raise ValueError('at least one island is required')
        self.islands = [[] for _ in range(islands)]
        self.random = Random(seed)

    def insert(self, island, source, score):
        if not source or not math.isfinite(score):
            raise ValueError('invalid program')
        self.islands[island].append(Program(source, float(score)))

    def select_two(self, island, temperature=1):
        candidates = list(self.islands[island])
        if len(candidates) < 2 or not math.isfinite(temperature) or temperature <= 0:
            raise ValueError('need two programs and positive temperature')
        selected = []
        for _ in range(2):
            maximum = max(p.score for p in candidates)
            weights = [math.exp((p.score-maximum)/temperature) for p in candidates]
            index = self.random.choices(range(len(candidates)), weights=weights, k=1)[0]
            selected.append(candidates.pop(index))
        return selected

    def reset_worst(self, count=1):
        populated = [(i, max(p.score for p in island)) for i, island in enumerate(self.islands) if len(island) >= 2]
        if len(populated) < 2 or not 0 <= count < len(populated):
            raise ValueError('need at least two populated islands and a valid count')
        ordered = sorted(populated, key=lambda x: (-x[1], x[0]))
        best = sorted(self.islands[ordered[0][0]], key=lambda p:p.score, reverse=True)[:2]
        victims = [i for i,_ in ordered[-count:]] if count else []
        for i in victims:
            self.islands[i] = list(best)
        return victims
