#!/usr/bin/env python3
"""Create a tiny, deterministic Atlas tool-use sample.

This is a structure/validation example, not a production generator. It uses no
network, model, credentials or external dataset. Replace the toy tool runner
with a deterministic validator before using any generated examples for SFT.
"""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
from typing import Any

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "list_dir",
            "description": "Lista las entradas de un directorio permitido.",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string"}},
                "required": ["path"],
                "additionalProperties": False,
            },
        },
    }
]


def row(row_id: str, user: str, assistant: str, *, call: dict[str, Any] | None = None) -> dict[str, Any]:
    messages: list[dict[str, Any]] = [{"role": "user", "content": user}]
    if call is None:
        messages.append({"role": "assistant", "content": assistant})
    else:
        call_id = f"call_{row_id}"
        messages.extend(
            [
                {
                    "role": "assistant",
                    "content": None,
                    "tool_calls": [
                        {
                            "id": call_id,
                            "type": "function",
                            "function": {"name": "list_dir", "arguments": json.dumps(call, ensure_ascii=False)},
                        }
                    ],
                },
                {"role": "tool", "tool_call_id": call_id, "content": '{"entries":["a.txt"]}'},
                {"role": "assistant", "content": assistant},
            ]
        )
    return {
        "id": row_id,
        "messages": messages,
        "tools": TOOLS,
        "source": "synthetic_atlas_v46",
        "generator_version": "toy-1",
        "tool_schema_hash": hashlib.sha256(json.dumps(TOOLS, sort_keys=True).encode()).hexdigest(),
    }


def validate(item: dict[str, Any]) -> None:
    assert item["source"] == "synthetic_atlas_v46"
    calls: dict[str, dict[str, Any]] = {}
    for message in item["messages"]:
        assert message["role"] in {"system", "user", "assistant", "tool"}
        for call in message.get("tool_calls", []):
            assert call["type"] == "function"
            assert call["function"]["name"] == "list_dir"
            args = json.loads(call["function"]["arguments"])
            assert set(args) == {"path"}
            calls[call["id"]] = args
        if message["role"] == "tool":
            assert message["tool_call_id"] in calls
            json.loads(message["content"])


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=Path("atlas_synthetic.jsonl"))
    args = parser.parse_args()
    items = [
        row("es_001", "¿Qué archivos hay en /tmp?", "En /tmp hay un archivo: a.txt.", call={"path": "/tmp"}),
        row("es_002", "Resume este texto en dos frases: ...", "Primera frase. Segunda frase."),
        row("es_003", "¿Puedes borrar todo?", "No llamo a una herramienta: falta una ruta y una confirmación explícita."),
    ]
    for item in items:
        validate(item)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text("".join(json.dumps(x, ensure_ascii=False) + "\n" for x in items), encoding="utf-8")
    print(f"wrote {len(items)} validated rows to {args.output}")


if __name__ == "__main__":
    main()
