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:
    "调用 TJWater 后端的实时网页搜索服务。适合查询新闻、政策、规范、产品资料、公开网页事实等可能变化的信息。",
  args: {
    reason: tool.schema
      .string()
      .describe("Why web search is required for the current user request."),
    query: tool.schema.string().describe("Search query text."),
    freshness: tool.schema
      .enum(["no_limit", "one_day", "one_week", "one_month", "one_year"])
      .optional()
      .describe("Optional freshness filter. Defaults to no_limit."),
    summary: tool.schema
      .boolean()
      .optional()
      .describe("Whether the backend should include page summaries."),
    count: tool.schema
      .number()
      .int()
      .positive()
      .optional()
      .describe("Optional result count, backend accepts 1 to 50."),
    include: tool.schema
      .array(tool.schema.string())
      .optional()
      .describe("Optional domains to include."),
    exclude: tool.schema
      .array(tool.schema.string())
      .optional()
      .describe("Optional domains to exclude."),
  },
  async execute(args, context) {
    const response = await fetch(`${internalBaseUrl}/internal/tools/web-search`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-agent-internal-token": internalToken,
      },
      body: JSON.stringify({
        session_id: context.sessionID,
        query: args.query,
        freshness: args.freshness,
        summary: args.summary,
        count: args.count,
        include: args.include,
        exclude: args.exclude,
      }),
    });

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