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 后端的天地图地理编码服务，将中国境内结构化地址或地点名称转换为经纬度。若需缩放地图，把返回的 location.lon/location.lat 传给 zoom_to_map，并设置 source_crs='EPSG:4326'。",
  args: {
    reason: tool.schema
      .string()
      .describe("Why geocoding is required for the current user request."),
    keyword: tool.schema
      .string()
      .describe("Address or place name to geocode, such as 北京市人民政府."),
  },
  async execute(args, context) {
    const response = await fetch(`${internalBaseUrl}/internal/tools/geocode`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-agent-internal-token": internalToken,
      },
      body: JSON.stringify({
        session_id: context.sessionID,
        keyword: args.keyword,
      }),
    });

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