"""GridSim's SFT warm start on Tinker: the 2,000 train days' best schedules, 1 epoch, LoRA rank 32, learning rate 1e-4
(cosine), 8 rows a batch. Each row is written as an episode's first prompt is: the task's system prompt with the env's
submit_schedule tool, then the day. The model learns only its answer, a one-line plan and the submit_schedule call.

    hf download earakely-scale/GridSimEnv-AgentEnv --repo-type dataset --include "sft/gridsim-v1/*" --local-dir .
    python tinker_gridsim_sft.py        # writes runs/gridsim-qwen3-8b-sft/
"""

import asyncio
import json
import random

import chz
import tinker
from tinker_cookbook.renderers import TrainOnWhat
from tinker_cookbook.renderers.base import ToolCall
from tinker_cookbook.supervised import train
from tinker_cookbook.supervised.data import conversation_to_datum
from tinker_cookbook.supervised.types import ChatDatasetBuilder, ChatDatasetBuilderCommonConfig, SupervisedDataset

MODEL = "Qwen/Qwen3-8B"
RENDERER = "qwen3_disable_thinking"
ROWS = "sft/gridsim-v1/train.jsonl"

# The env's submit_schedule tool, as an episode's first prompt offers it. The rows' own `tools` are TRL's: they add an
# end_turn tool and leave out the 24-item bounds.
TOOLS = [{
    "name": "submit_schedule",
    "description": "Submit the final 24-hour schedule. This ends the episode.",
    "parameters": {
        "type": "object",
        "required": ["actions"],
        "properties": {
            "actions": {
                "type": "array",
                "items": {"type": "integer"},
                "minItems": 24,
                "maxItems": 24,
                "description": "24 integers for HE01..HE24: a > 0 discharges (sells) a units, a < 0 charges (buys) -a units.",
            },
        },
    },
}]


def datum(row: dict, renderer, max_length: int) -> tinker.Datum:
    """A row, written as an episode's first prompt and its answer, training only the answer."""
    system, user = row["prompt"]
    answer = row["completion"][0]
    calls = [
        ToolCall(function=ToolCall.FunctionBody(name=c["function"]["name"], arguments=json.dumps(c["function"]["arguments"])),
                 id=f"call-{n}")
        for n, c in enumerate(answer["tool_calls"])
    ]
    messages = [
        *renderer.create_conversation_prefix_with_tools(tools=TOOLS, system_prompt=system["content"]),
        {"role": "user", "content": user["content"]},
        {"role": "assistant", "content": answer["content"], "tool_calls": calls},
    ]
    return conversation_to_datum(messages, renderer, max_length, TrainOnWhat.LAST_ASSISTANT_MESSAGE)


class Rows(SupervisedDataset):
    """The rows in batches, shuffled anew each epoch."""

    def __init__(self, rows: list[dict], batch_size: int, datum):
        self.rows, self.batch_size, self.datum = rows, batch_size, datum
        self.order = rows

    def get_batch(self, index: int) -> list[tinker.Datum]:
        return [self.datum(row) for row in self.order[index * self.batch_size:(index + 1) * self.batch_size]]

    def set_epoch(self, seed: int = 0):
        self.order = random.Random(seed).sample(self.rows, len(self.rows))

    def __len__(self) -> int:
        return len(self.rows) // self.batch_size


@chz.chz
class GridSimRows(ChatDatasetBuilder):
    def __call__(self):
        renderer, max_length = self.renderer, self.common_config.max_length
        with open(ROWS) as f:
            rows = [json.loads(line) for line in f]
        dataset = Rows(rows, self.common_config.batch_size, lambda row: datum(row, renderer, max_length))
        dataset.set_epoch(0)
        return dataset, None


config = train.Config(
    log_path="runs/gridsim-qwen3-8b-sft",
    model_name=MODEL,
    renderer_name=RENDERER,
    recipe_name="agentenv-gridsim-sft",
    dataset_builder=GridSimRows(common_config=ChatDatasetBuilderCommonConfig(
        model_name_for_tokenizer=MODEL, renderer_name=RENDERER, max_length=2048, batch_size=8)),
    learning_rate=1e-4,
    lr_schedule="cosine",
    num_epochs=1,
    lora_rank=32,
    save_every=0,
    eval_every=0,
)

if __name__ == "__main__":
    asyncio.run(train.main(config))
