#!/usr/bin/env python3
"""Recipe: lint tool definitions the way a model will read them.

Input: JSON from a tools/list response ({"tools": [...]}) or a bare list.
Checks names, descriptions, parameter descriptions, enums, required fields,
unbounded integers and arrays, and total description size.

Usage:
    python3 -m cookbook.lint_tools tools.json
"""
from __future__ import annotations

import json
import re
import sys

NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
VAGUE = {"data", "info", "stuff", "handle", "process", "do", "run", "execute", "query"}


def lint(tools: list[dict]) -> list[str]:
    problems: list[str] = []
    seen = set()
    total_desc = 0
    for tool in tools:
        name = tool.get("name", "")
        desc = (tool.get("description") or "").strip()
        schema = tool.get("inputSchema") or tool.get("input_schema") or {}
        where = f"tool {name or '<unnamed>'}"
        if not NAME_RE.match(name):
            problems.append(f"{where}: name should be 1-64 chars of letters, digits, _ or -")
        if name in seen:
            problems.append(f"{where}: duplicate name")
        seen.add(name)
        if name.lower() in VAGUE:
            problems.append(f"{where}: name is too vague to choose correctly")
        if len(desc) < 20:
            problems.append(f"{where}: description is missing or too short to explain when to use it")
        if len(desc) > 1200:
            problems.append(f"{where}: description is very long ({len(desc)} chars); move detail into parameter descriptions")
        total_desc += len(desc)
        props = schema.get("properties", {}) or {}
        required = set(schema.get("required", []) or [])
        for r in required - set(props):
            problems.append(f"{where}: required parameter '{r}' is not defined")
        for pname, p in props.items():
            if not (p.get("description") or "").strip() and not p.get("enum") and pname not in {"id", "limit", "cursor"}:
                problems.append(f"{where}: parameter '{pname}' has no description")
            if p.get("type") == "array" and "maxItems" not in p:
                problems.append(f"{where}: array parameter '{pname}' has no maxItems")
            if p.get("type") == "integer" and "maximum" not in p and pname in {"limit", "count", "max_results", "page_size"}:
                problems.append(f"{where}: '{pname}' has no maximum")
            if p.get("type") == "string" and pname in {"sql", "command", "shell", "code"}:
                problems.append(f"{where}: free-form '{pname}' input is high risk; prefer structured parameters")
    if total_desc > 8000:
        problems.append(f"all tools: {total_desc} characters of descriptions are sent with every request; consider fewer tools")
    return problems


def main(argv: list[str]) -> int:
    if len(argv) != 1:
        print(__doc__)
        return 2
    with open(argv[0], encoding="utf-8") as fh:
        data = json.load(fh)
    tools = data["tools"] if isinstance(data, dict) else data
    problems = lint(tools)
    for p in problems:
        print(p)
    print(f"{len(tools)} tools, {len(problems)} problem(s)")
    return 1 if problems else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
