#!/usr/bin/env python3
"""Minimal cloud-API tool-calling agent for CardputerZero.

The language model runs in the cloud. This process only:

  1. sends the conversation and tool schemas to an OpenAI-compatible API
  2. executes a small allowlist of local tools
  3. returns tool results to the model

It is intended for M5Stack CardputerZero (Raspberry Pi CM0, 512 MB LPDDR2).
Do not use it as a local LLM runner.

Dependencies
------------
- Python 3 standard library only (json, os, platform, subprocess, urllib).
- Official CardputerZero images include a Python 3 REPL app; see the
  official usage guide. No pip packages are required.
- A reachable network (2.4 GHz Wi-Fi or 10/100M Ethernet in USB Host mode).
- An API key for an OpenAI-compatible Chat Completions endpoint that
  supports tool calls.

Usage
-----
  export OPENAI_API_KEY="..."            # required
  export OPENAI_BASE_URL="https://api.openai.com/v1"   # optional
  export OPENAI_MODEL="gpt-4.1-mini"     # optional; any tool-capable model

  python3 tiny_cloud_agent.py
  python3 tiny_cloud_agent.py "现在内存还剩多少？"

This is an unofficial example, not a product or app from M5Stack.
Keep API keys in the environment; do not hard-code them or paste them
into world-readable files.
"""

from __future__ import annotations

import json
import os
import platform
import subprocess
import sys
import urllib.error
import urllib.request

BASE_URL = os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1").rstrip("/")
MODEL = os.environ.get("OPENAI_MODEL", "gpt-4.1-mini")
API_KEY = os.environ.get("OPENAI_API_KEY", "")
TIMEOUT_SEC = 60
MAX_TOOL_ROUNDS = 6

# Only these exact command vectors may be executed. No shell interpolation.
ALLOWED_COMMANDS = {
    "uname": ["uname", "-a"],
    "uptime": ["uptime"],
    "ip4": ["ip", "-4", "addr", "show"],
}

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "host_info",
            "description": (
                "Read local OS, CPU, and memory figures from /proc and Python's "
                "platform module. Use this instead of a shell command when you "
                "only need machine status."
            ),
            "parameters": {"type": "object", "properties": {}, "additionalProperties": False},
        },
    },
    {
        "type": "function",
        "function": {
            "name": "run_allowed",
            "description": (
                "Run one allowlisted read-only command. "
                "name must be one of: uname, uptime, ip4."
            ),
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "enum": sorted(ALLOWED_COMMANDS.keys()),
                    }
                },
                "required": ["name"],
                "additionalProperties": False,
            },
        },
    },
]

SYSTEM = (
    "You are a compact operator assistant running on an M5Stack CardputerZero, "
    "a pocket Linux PC with a Raspberry Pi CM0 (quad Cortex-A53, 512 MB RAM) "
    "and a 320x170 screen. Prefer short, factual answers. Use tools only when "
    "the user asks about this device's current state. If a tool is not in the "
    "allowlist, say so and stop; never invent a command."
)


def _kb(meminfo_kb: str, key: str) -> int | None:
    for line in meminfo_kb.splitlines():
        if line.startswith(key + ":"):
            parts = line.split()
            if len(parts) >= 2 and parts[1].isdigit():
                return int(parts[1])
    return None


def host_info() -> dict:
    mem = ""
    try:
        mem = open("/proc/meminfo", encoding="ascii").read()
    except OSError as exc:
        mem = f"(unavailable: {exc})"
    total = _kb(mem, "MemTotal")
    available = _kb(mem, "MemAvailable")
    return {
        "system": platform.system(),
        "release": platform.release(),
        "machine": platform.machine(),
        "python": platform.python_version(),
        "mem_total_mib": round(total / 1024, 1) if total is not None else None,
        "mem_available_mib": round(available / 1024, 1) if available is not None else None,
    }


def run_allowed(name: str) -> dict:
    argv = ALLOWED_COMMANDS.get(name)
    if not argv:
        return {"ok": False, "error": f"command {name!r} is not in the allowlist"}
    try:
        completed = subprocess.run(
            argv,
            check=False,
            capture_output=True,
            text=True,
            timeout=8,
        )
    except (OSError, subprocess.TimeoutExpired) as exc:
        return {"ok": False, "error": str(exc), "argv": argv}
    return {
        "ok": completed.returncode == 0,
        "argv": argv,
        "returncode": completed.returncode,
        "stdout": completed.stdout[-4000:],
        "stderr": completed.stderr[-1000:],
    }


def dispatch_tool(name: str, arguments: str) -> str:
    try:
        args = json.loads(arguments or "{}")
        if not isinstance(args, dict):
            raise ValueError("tool arguments must be a JSON object")
    except (json.JSONDecodeError, ValueError) as exc:
        return json.dumps({"ok": False, "error": f"bad arguments: {exc}"})

    if name == "host_info":
        return json.dumps(host_info(), ensure_ascii=False)
    if name == "run_allowed":
        return json.dumps(run_allowed(str(args.get("name", ""))), ensure_ascii=False)
    return json.dumps({"ok": False, "error": f"unknown tool {name!r}"})


def chat(messages: list) -> dict:
    if not API_KEY:
        raise SystemExit(
            "OPENAI_API_KEY is not set. Export a key for an OpenAI-compatible "
            "endpoint before running this script."
        )
    payload = json.dumps(
        {
            "model": MODEL,
            "messages": messages,
            "tools": TOOLS,
            "tool_choice": "auto",
        }
    ).encode("utf-8")
    request = urllib.request.Request(
        f"{BASE_URL}/chat/completions",
        data=payload,
        method="POST",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=TIMEOUT_SEC) as response:
            return json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        raise SystemExit(f"API HTTP {exc.code}: {body[:800]}") from exc
    except urllib.error.URLError as exc:
        raise SystemExit(f"network error talking to {BASE_URL}: {exc}") from exc


def one_turn(user_text: str) -> str:
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": user_text},
    ]
    for _ in range(MAX_TOOL_ROUNDS):
        data = chat(messages)
        try:
            message = data["choices"][0]["message"]
        except (KeyError, IndexError, TypeError) as exc:
            raise SystemExit(f"unexpected API payload: {exc}\n{data!r}"[:800]) from exc

        tool_calls = message.get("tool_calls") or []
        if not tool_calls:
            return (message.get("content") or "").strip() or "(empty model reply)"

        messages.append(message)
        for call in tool_calls:
            function = call.get("function") or {}
            result = dispatch_tool(function.get("name", ""), function.get("arguments", "{}"))
            messages.append(
                {
                    "role": "tool",
                    "tool_call_id": call.get("id", ""),
                    "content": result,
                }
            )
    return "Stopped: the model kept requesting tools past the round limit."


def main(argv: list[str]) -> int:
    if len(argv) > 1:
        prompt = " ".join(argv[1:]).strip()
        print(one_turn(prompt))
        return 0

    print(f"tiny_cloud_agent  model={MODEL}  endpoint={BASE_URL}")
    print("Type a question, or q to quit.")
    while True:
        try:
            prompt = input("> ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            return 0
        if not prompt or prompt in {"q", "quit", "exit"}:
            return 0
        print(one_turn(prompt))
        print()


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