import hashlib
import random
from words import word_list


def _derive_seed(first_word: str, slot: int) -> int:
    """Stable, platform-independent seed from (first_word, slot) via SHA-256."""
    raw = hashlib.sha256(f"{first_word}:{slot}".encode()).digest()
    return int.from_bytes(raw, "big")


def _validate(word_list: list[str], seq_len: int, branches: list[int]):
    n = len(word_list)
    if n < 2:
        raise ValueError("word_list must have at least 2 entries")
    if len(set(word_list)) != n:
        raise ValueError("word_list must contain unique words")
    if seq_len < 2:
        raise ValueError("seq_len must be at least 2")
    tail_len = seq_len - 1
    if len(branches) != tail_len:
        raise ValueError(
            f"branches must have {tail_len} elements for seq_len={seq_len} "
            f"(one per derived slot), got {len(branches)}"
        )
    if any(b < 1 for b in branches):
        raise ValueError("every branch value must be >= 1")


def generate_word_list() -> str:
    seq_len = 12
    branches = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

    _validate(word_list, seq_len, branches)
    n = len(word_list)

    first_word = random.choice(word_list)
    sequence   = [first_word]

    for slot in range(1, seq_len):
        b = branches[slot - 1]
        if slot == 1:
            bucket = random.randrange(b)
        else:
            seed   = _derive_seed(first_word, slot)
            bucket = seed % b

        # Spread bucket across full word list
        spread = int.from_bytes(
            hashlib.sha256(f"{first_word}:{slot}:{bucket}".encode()).digest(),
            "big"
        )
        sequence.append(word_list[spread % n])

    return " ".join(sequence)
