"""Write the fine-tuning example dataset: data/train.jsonl (1,000 records) and data/eval.jsonl
(32 held-out records). Deterministic and synthetic (seeded arithmetic and word tasks, no third-party
text), so the files are license-clean and re-generated byte for byte; `--check` verifies that.

Usage (from this directory): python3 make_data.py [--check]
"""

import json
import os
import random
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
WORDS = ("amber", "basalt", "cedar", "delta", "ember", "fjord", "garnet", "harbor", "indigo", "juniper",
         "kelp", "lumen", "meadow", "nectar", "onyx", "prism", "quartz", "river", "sable", "tundra")


def record(rng):
    kind = rng.randrange(4)
    if kind == 0:
        a, b = rng.randrange(100), rng.randrange(100)
        prompt, answer = "Add %d and %d." % (a, b), str(a + b)
    elif kind == 1:
        a, b = rng.randrange(50, 150), rng.randrange(50)
        prompt, answer = "Subtract %d from %d." % (b, a), str(a - b)
    elif kind == 2:
        word = rng.choice(WORDS)
        prompt, answer = "Reverse the word %s." % word, word[::-1]
    else:
        picked = rng.sample(WORDS, 3)
        prompt, answer = "Sort these words: %s." % ", ".join(picked), ", ".join(sorted(picked))
    return {"text": "### Instruction:\n%s\n### Response:\n%s" % (prompt, answer)}


def build():
    rng = random.Random(20261027)
    rows = [record(rng) for _ in range(1032)]
    lines = [json.dumps(row, sort_keys=True) + "\n" for row in rows]
    return {"data/train.jsonl": "".join(lines[:1000]), "data/eval.jsonl": "".join(lines[1000:])}


def main(argv):
    files = build()
    check = argv[1:] == ["--check"]
    for name, text in files.items():
        path = os.path.join(HERE, name)
        if check:
            with open(path, encoding="utf-8") as handle:
                if handle.read() != text:
                    raise SystemExit("make_data: %s differs from the generator" % name)
        else:
            with open(path, "w", encoding="utf-8") as handle:
                handle.write(text)
    print("make_data: %s %s" % ("checked" if check else "wrote", ", ".join(sorted(files))))


if __name__ == "__main__":
    main(sys.argv)
