import { tool } from "@opencode-ai/plugin";

const internalBaseUrl =
  process.env.TJWATER_AGENT_INTERNAL_BASE_URL ?? "http://127.0.0.1:8787";
const internalToken = process.env.TJWATER_AGENT_INTERNAL_TOKEN ?? "";

export default tool({
  description:
    "通过本地 Agent 桥接调用 tjwater-cli 命令访问 TJWater 后端服务。提供 CLI 子命令和参数。",
  args: {
    reason: tool.schema
      .string()
      .describe("Why this tool call is required for the current user request."),
    command: tool.schema
      .string()
      .describe(
        "tjwater-cli 子命令，不含二进制路径。示例：'project list'、'data timeseries realtime links --start-time 2025-01-01T00:00:00+08:00 --end-time 2025-01-01T01:00:00+08:00'",
      ),
    timeout: tool.schema
      .number()
      .optional()
      .describe("超时秒数，默认 120。大结果集建议设 300+。"),
  },
  async execute(args, context) {
    const response = await fetch(
      `${internalBaseUrl}/internal/tools/tjwater-cli-call`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-agent-internal-token": internalToken,
        },
        body: JSON.stringify({
          session_id: context.sessionID,
          reason: args.reason,
          command: args.command,
          timeout: args.timeout,
        }),
      },
    );

    const text = await response.text();
    if (!response.ok) {
      throw new Error(text);
    }
    return text;
  },
});
