// FastOcr.java — fastOcr 验证码识别 Java SDK（零依赖，单文件）
// 用法: 把此文件复制到项目中，直接 new FastOcr("your_api_key").recognize(...)
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FastOcr {
    private String apiKey;
    private String baseUrl;

    public FastOcr(String apiKey) { this(apiKey, "http://shenzheng.cstext.top:8989"); }
    public FastOcr(String apiKey, String baseUrl) {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl.replaceAll("/+$", "");
    }

    public String recognize(String type, String imagePath) throws Exception {
        return recognize(type, imagePath, null);
    }

    public String recognize(String type, String imagePath, String piecePath) throws Exception {
        String imgB64 = java.util.Base64.getEncoder().encodeToString(Files.readAllBytes(Paths.get(imagePath)));
        StringBuilder sb = new StringBuilder();
        sb.append("{\"type\":\"").append(type).append("\",\"image\":\"").append(imgB64).append("\"");
        if (piecePath != null) {
            String pieceB64 = java.util.Base64.getEncoder().encodeToString(Files.readAllBytes(Paths.get(piecePath)));
            sb.append(",\"piece\":\"").append(pieceB64).append("\"");
        }
        sb.append("}");
        return post("/api/v1/captcha/recognize", sb.toString());
    }

    public String getBalance() throws Exception {
        return post("/api/v1/user/balance", "{}");
    }

    private String post(String path, String body) throws Exception {
        URL url = new URL(baseUrl + path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "Bearer " + apiKey);
        conn.setDoOutput(true);
        try (OutputStream os = conn.getOutputStream()) { os.write(body.getBytes("UTF-8")); }
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        StringBuilder resp = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) resp.append(line);
        br.close();
        return resp.toString();
    }

    // 示例
    public static void main(String[] args) throws Exception {
        FastOcr client = new FastOcr("your_api_key");
        String result = client.recognize("answer", "captcha.png");
        System.out.println(result);
    }
}
