package edu.whut.smilepicturebackend.api.imagesearch.sub;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import edu.whut.smilepicturebackend.exception.BusinessException;
import edu.whut.smilepicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取以图搜图页面地址（step 1）
 */
@Slf4j
public class GetImagePageUrlApi {

    /**
     * 获取以图搜图页面地址
     *
     * @param imageUrl
     * @return
     */
    /**
     * 调用百度「以图搜图」上传接口，返回结果页 URL
     */
    public static String getImagePageUrl(String localImagePath) {
        // 1⃣ 参数准备（必须 urlencode）
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", new java.io.File(localImagePath)); // 关键
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");

        String uploadUrl = "https://graph.baidu.com/upload?uptime=" + System.currentTimeMillis();

        // Acs-Token 每次打开 graph.baidu.com 时都会刷新，可抓包固定或动态获取
        String acsToken = "jmM4zyI8OUixvSuWh0sCy4xWbsttVMZb9qcRTmn6SuNWg0vCO7N0s6Lffec+IY5yuqHujHmCctF9BVCGYGH0H5SH/H3VPFUl4O4CP1jp8GoAzuslb8kkQQ4a21Tebge8yhviopaiK66K6hNKGPlWt78xyyJxTteFdXYLvoO6raqhz2yNv50vk4/41peIwba4lc0hzoxdHxo3OBerHP2rfHwLWdpjcI9xeu2nJlGPgKB42rYYVW50+AJ3tQEBEROlg/UNLNxY+6200B/s6Ryz+n7xUptHFHi4d8Vp8q7mJ26yms+44i8tyiFluaZAr66/+wW/KMzOhqhXCNgckoGPX1SSYwueWZtllIchRdsvCZQ8tFJymKDjCf3yI/Lw1oig9OKZCAEtiLTeKE9/CY+Crp8DHa8Tpvlk2/i825E3LuTF8EQfzjcGpVnR00Lb4/8A";

        try (HttpResponse resp = HttpRequest.post(uploadUrl)
                .header("User-Agent",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                                + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36")
                .header("Referer",  "https://graph.baidu.com/")   // 防 403
                .header("Acs-Token", acsToken)                    // 防风控
                .form(formData)
                .setFollowRedirects(true)                         // 跟随 302
                .timeout(5000)
                .execute()) {

            if (resp.getStatus() != HttpStatus.HTTP_OK) {
                log.error("[百度搜图] 上传失败，HTTP={}", resp.getStatus());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜图失败");
            }

            JSONObject json = JSONUtil.parseObj(resp.body());     // 兼容字符串/数字
            if (json.getInt("status", -1) != 0) {
                String msg = json.getStr("msg", "unknown");
                log.error("[百度搜图] 接口返回错误：{}", msg);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜图失败");
            }

            String rawUrl = json.getJSONObject("data").getStr("url");
            String pageUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);

            if (StrUtil.isBlank(pageUrl)) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "未返回有效地址");
            }
            return pageUrl;
        } catch (Exception e) {
            log.error("[百度搜图] 上传过程异常", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜图失败");
        }
    }

    public static void main(String[] args) {
        // 测试以图搜图功能
        String imageUrl = "https://www.codefather.cn/logo.png";
        String searchResultUrl = getImagePageUrl(imageUrl);
        System.out.println("搜索成功，结果 URL：" + searchResultUrl);
    }
}
