"""Week 4: real tiny-model training, record signals, sampling, and reference timings.
Keep week03.py beside this file. Requires torch. Writes the selected checkpoint
to --output (default week04-checkpoint.pt in your exercise folder).
"""
import argparse
import copy
import hashlib
import json
import math
from pathlib import Path
import time
import torch
from torch import nn
from week03 import TinyDecoder


def make_documents():
    states = ['calm', 'warm', 'alert']
    return [f'sensor {i:02d} reports {states[i % 3]} in zone {i % 4}.\n'
            for i in range(48)]


def make_windows(documents, vocabulary, length=24):
    mapping = {character: index for index, character in enumerate(vocabulary)}
    inputs, targets = [], []
    for document in documents:
        identifiers = [mapping[character] for character in document]
        for start in range(0, len(identifiers) - length, 8):
            sample = identifiers[start:start + length + 1]
            inputs.append(sample[:-1])
            targets.append(sample[1:])
    return torch.tensor(inputs), torch.tensor(targets)


def objective(model, inputs, targets):
    logits = model(inputs)
    return nn.functional.cross_entropy(logits.reshape(-1, logits.shape[-1]),
                                        targets.reshape(-1))


def load_checkpoint(filename):
    checkpoint = torch.load(filename, map_location='cpu', weights_only=True)
    model = TinyDecoder(**checkpoint['architecture'])
    model.load_state_dict(checkpoint['state_dict'])
    model.eval()
    return model, checkpoint


def lesson1(output):
    torch.manual_seed(42)
    torch.set_num_threads(1)
    documents = make_documents()
    train_docs, val_docs, test_docs = documents[:32], documents[32:40], documents[40:]
    assert not set(train_docs) & set(test_docs)
    assert not set(train_docs) & set(val_docs)
    vocabulary = sorted(set(''.join(train_docs)))
    assert set(''.join(val_docs + test_docs)) <= set(vocabulary)
    train_x, train_y = make_windows(train_docs, vocabulary)
    val_x, val_y = make_windows(val_docs, vocabulary)
    test_x, test_y = make_windows(test_docs, vocabulary)
    architecture = {'vocabulary_size': len(vocabulary), 'width': 24,
                    'max_length': 32, 'heads': 2}
    model = TinyDecoder(**architecture)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.015)
    model.eval()
    with torch.no_grad():
        initial = objective(model, train_x, train_y).item()
    original = [parameter.detach().clone() for parameter in model.parameters()]
    best_loss, best_state, best_step = float('inf'), None, None
    for step in range(140):
        selected = torch.randint(len(train_x), (16,))
        model.train()
        optimizer.zero_grad()
        loss = objective(model, train_x[selected], train_y[selected])
        assert torch.isfinite(loss)
        loss.backward()
        optimizer.step()
        model.eval()
        with torch.no_grad():
            validation = objective(model, val_x, val_y).item()
        if validation < best_loss:
            best_loss, best_step = validation, step + 1
            best_state = copy.deepcopy(model.state_dict())
    model.load_state_dict(best_state)
    model.eval()
    with torch.no_grad():
        final_train = objective(model, train_x, train_y).item()
        test_loss = objective(model, test_x, test_y).item()
        reference = model(test_x[:1]).clone()
    assert final_train < initial, 'This controlled toy fitting run should reduce training loss'
    assert any(not torch.equal(old, new) for old, new in zip(original, model.parameters()))
    output = Path(output)
    output.parent.mkdir(parents=True, exist_ok=True)
    checkpoint = {'format_version': 1, 'architecture': architecture,
                  'vocabulary': vocabulary, 'state_dict': model.state_dict(),
                  'selected_step': best_step, 'validation_loss': best_loss,
                  'data_sha256': hashlib.sha256(json.dumps(documents).encode()).hexdigest(),
                  'torch_version': str(torch.__version__),
                  'purpose': 'inference reconstruction, not exact optimizer resume'}
    torch.save(checkpoint, output)
    restored, metadata = load_checkpoint(output)
    with torch.no_grad():
        assert torch.allclose(restored(test_x[:1]), reference, atol=1e-6)
    mapping = {character: index for index, character in enumerate(vocabulary)}
    prefix = torch.tensor([[mapping[character] for character in 'sensor ']])
    sample = restored.generate(prefix, count=35, temperature=0)
    text = ''.join(vocabulary[index] for index in sample[0].tolist())
    print('Real training initial/final fixed-batch loss:', initial, final_train)
    print('Selected step:', best_step, '; validation loss:', best_loss)
    print('Final held-out test loss:', test_loss, '; perplexity:', math.exp(test_loss))
    print('Trained toy sample:', repr(text))
    print('Saved checkpoint:', str(output), '; vocabulary entries:', len(metadata['vocabulary']))
    print('PASS: actual updates, source-separated windows, held-out evaluation and fresh reload.')


def lesson2():
    records = [({'text': 'sensor online'}, 'next-token text'),
               ({'request': 'extract city: Oslo', 'response': 'Oslo'}, 'instruction pair'),
               ({'request': 'answer', 'preferred': 'supported', 'rejected': 'invented'},
                'preference pair'),
               ({'teacher_probabilities': [0.8, 0.2]}, 'distillation signal')]
    def classify(record):
        if 'teacher_probabilities' in record:
            return 'distillation signal'
        if {'preferred', 'rejected'} <= record.keys():
            return 'preference pair'
        if {'request', 'response'} <= record.keys():
            return 'instruction pair'
        if 'text' in record:
            return 'next-token text'
        raise ValueError('Unrecognized training record')
    for record, expected in records:
        assert classify(record) == expected
    teacher, student = [0.8, 0.2], [0.5, 0.5]
    soft_loss = -sum(t * math.log(s) for t, s in zip(teacher, student))
    matched = -sum(t * math.log(t) for t in teacher)
    assert math.isclose(soft_loss, math.log(2))
    assert matched < soft_loss
    print('Signals:', [classify(record) for record, _ in records])
    print('Soft-target loss before / at teacher match:', soft_loss, matched)
    print('PASS: signal classifications and arithmetic; not a full alignment-training run.')


def lesson3(output):
    torch.set_num_threads(1)
    logits = torch.tensor([2., 0.])
    low = torch.softmax(logits, dim=-1)
    high = torch.softmax(logits / 2, dim=-1)
    assert high[1] > low[1]
    probabilities = torch.tensor([0.6, 0.3, 0.1])
    keep = probabilities.cumsum(0) - probabilities < 0.8
    retained = probabilities * keep
    retained /= retained.sum()
    assert torch.allclose(retained, torch.tensor([2/3, 1/3, 0.]))
    def cache_bytes(tokens):
        return 2 * 2 * 1 * tokens * 2 * 4 * 4
    assert cache_bytes(10) == 1280 and cache_bytes(20) == 2560
    if Path(output).exists():
        model, metadata = load_checkpoint(output)
        label = 'trained toy checkpoint'
        vocabulary_size = len(metadata['vocabulary'])
    else:
        torch.manual_seed(42)
        vocabulary_size = 16
        model = TinyDecoder(vocabulary_size).eval()
        label = 'untrained toy decoder'
    print('Probabilities at temperature 1 and 2:', low.tolist(), high.tolist())
    print('Nucleus probabilities:', retained.tolist())
    print('Estimated cache bytes at 10/20 tokens:', cache_bytes(10), cache_bytes(20))
    with torch.no_grad():
        model(torch.zeros(1, 4, dtype=torch.long))  # Warm-up.
        for length in [4, 20]:
            prefix = torch.randint(vocabulary_size, (1, length))
            start = time.perf_counter()
            model(prefix)
            first = time.perf_counter() - start
            start = time.perf_counter()
            model.generate(prefix, count=8, temperature=0)
            total = time.perf_counter() - start
            print(label, '; input tokens:', length,
                  '; measured first-forward seconds:', first,
                  '; 8-token reference generation seconds:', total)
    print('PASS: sampling and estimate checks. Reference decoder recomputes prefixes; it has no KV cache.')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--lesson', choices=['1', '2', '3', 'all'], default='all')
    parser.add_argument('--output', default='week04-checkpoint.pt')
    args = parser.parse_args()
    for number, function in [('1', lesson1), ('2', lambda _: lesson2()), ('3', lesson3)]:
        if args.lesson in (number, 'all'):
            function(args.output)
