package org.dromara.ai.mcp.tools;

import org.dromara.ai.mcp.McpTool;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

public class HttpFetchTool implements McpTool {
    @Override
    public String name() {
        return "http_fetch";
    }

    @Override
    public String description() {
        return "HTTP抓取";
    }

    @Override
    public Map<String, Object> schema() {
        Map<String, Object> s = new HashMap<>();
        s.put("type", "object");
        s.put("properties", Map.of("url", Map.of("type", "string")));
        return s;
    }

    @Override
    public Map<String, Object> invoke(Map<String, Object> input) {
        try {
            String url = String.valueOf(input.get("url"));
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build();
            HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
            return Map.of("status", resp.statusCode(), "body", resp.body());
        } catch (Exception e) {
            return Map.of("error", e.getMessage());
        }
    }
}
