"""Step 1, Count: the dumbest possible language model.

Go through the text and, for each character, count which character came next.
To write, start with a character, pick the next one using those counts, and
repeat. That is already a language model; its memory is one character long.

The loss printed here is the score every later step must beat.

Run:  python get_tinystories.py        (once, from 1-own-model/)
      python step1_count/bigram.py     (plain Python, no libraries)
"""
import math
import random
import sys
from collections import Counter
from pathlib import Path

DATA = Path(__file__).parent.parent / "data" / "tinystories-valid.txt"
STORY_END = "<|endoftext|>"   # TinyStories puts this between stories
HELD_OUT = 0.1                # last 10% of the text is never counted, only scored
SMOOTHING = 1                 # pretend every pair was seen once more (see below)


def show(ch):
    return {" ": "␣", "\n": "↵"}.get(ch, ch)


# ------------------------------------------------------------------ counting
def count_pairs(text):
    """counts[a][b] = how many times character b came right after a."""
    counts = {}
    for (a, b), n in Counter(zip(text, text[1:])).items():
        counts.setdefault(a, {})[b] = n
    return counts


def probabilities(counts, chars, smoothing=SMOOTHING):
    """Turn each row of counts into chances that add up to 1.

    Smoothing adds a small count to every pair, so a pair we never saw gets a
    tiny chance instead of zero. Without it, one unseen pair in the held-out
    text would make the loss infinite.
    """
    probs = {}
    for a in chars:
        row = counts.get(a, {})
        total = sum(row.values()) + smoothing * len(chars)
        if total == 0:   # a character never followed by anything, no smoothing
            probs[a] = {b: 1 / len(chars) for b in chars}
            continue
        probs[a] = {b: (row.get(b, 0) + smoothing) / total for b in chars}
    return probs


# ------------------------------------------------------------------- scoring
def loss(text, probs):
    """Average surprise (negative log chance) of each next character.

    Pairs with a character the model has never seen are skipped and counted.
    """
    total, scored, skipped = 0.0, 0, 0
    for a, b in zip(text, text[1:]):
        p = probs.get(a, {}).get(b)
        if p is None:
            skipped += 1
            continue
        total -= math.log(p)
        scored += 1
    return total / max(scored, 1), skipped


# ------------------------------------------------------------------- writing
def sample(probs, start, n, rng):
    out = [start]
    for _ in range(n):
        row = probs[out[-1]]
        out.append(rng.choices(list(row), weights=list(row.values()))[0])
    return "".join(out)


# ---------------------------------------------------------------------- main
def banner(title):
    print(f"\n{'=' * 70}\n{title}\n{'=' * 70}")


def main():
    if not DATA.exists():
        sys.exit(f"missing {DATA}\nrun: python get_tinystories.py")
    text = DATA.read_text(encoding="utf-8").replace(STORY_END, "\n")
    cut = int(len(text) * (1 - HELD_OUT))
    train, held = text[:cut], text[cut:]

    banner("1. TEXT")
    print(f"   {len(text):,} characters: {len(train):,} to count, {len(held):,} held out")
    chars = sorted(set(train))
    print(f"   {len(chars)} different characters (the vocabulary)")

    banner("2. COUNT: which character came next?")
    counts = count_pairs(train)
    pairs = Counter({(a, b): n for a, row in counts.items() for b, n in row.items()})
    print("   the 10 most common pairs:")
    for (a, b), n in pairs.most_common(10):
        print(f"     {show(a)!s:>2} then {show(b)!s:<2} {n:>9,} times")
    for a in ("t", "q", "."):
        row = counts.get(a, {})
        total = sum(row.values())
        top = sorted(row.items(), key=lambda kv: -kv[1])[:5]
        cells = ", ".join(f"{show(b)} {n:,} ({n / total:.0%})" for b, n in top)
        print(f"   after {show(a)!r} ({total:,} times): {cells}")

    banner("3. SCORE: loss = average surprise per character (lower is better)")
    probs = probabilities(counts, chars)
    uniform = math.log(len(chars))
    train_loss, _ = loss(train, probs)
    held_loss, skipped = loss(held, probs)
    print(f"   pure guessing (every character equally likely): ln({len(chars)}) = {uniform:.3f}")
    print(f"   bigram on the text it counted:                  {train_loss:.3f}")
    print(f"   bigram on held-out text it never saw:           {held_loss:.3f}"
          + (f"   ({skipped} pairs with unseen characters skipped)" if skipped else ""))
    print(f"   so one character of memory takes the loss from {uniform:.2f} to {held_loss:.2f}.")
    print("   every later step (bricks, brain, reading) has to beat the held-out number.")

    banner("4. WRITE: start with a character, pick the next from the counts, repeat")
    for seed in range(3):
        print(f"   {sample(probs, 'O', 120, random.Random(seed))!r}")
    print("   right letters, right word lengths, no sense: one character of memory.")


if __name__ == "__main__":
    main()
