package com.example.demo.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class DraftUrlExtractor {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 从JSON字符串中提取draft_url
     * @param jsonString 包含draft_url的JSON字符串
     * @return 提取的draft_url，如果不存在则返回null
     */
    public static String extractDraftUrl(String jsonString) {
        if (jsonString == null || jsonString.isEmpty()) {
            return null;
        }

        try {
            // 解析主JSON对象
            JsonNode rootNode = objectMapper.readTree(jsonString);
            
            // 获取Output字段
            JsonNode outputNode = rootNode.get("Output");
            if (outputNode == null || !outputNode.isObject()) {
                return null;
            }
            
            // 获取output字段
            JsonNode draftUrlNode = outputNode.get("output");
            if (draftUrlNode == null || !draftUrlNode.isTextual()) {
                return null;
            }
            
            // 获取URL字符串
            String draftUrl = draftUrlNode.asText();
            
            // 处理可能的转义字符
            draftUrl = draftUrl.replaceAll("\\\"", "");
            
            return draftUrl;
            
        } catch (IOException e) {
            // 解析失败时返回null
            return null;
        }
    }

    /**
     * 测试提取方法
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        // 测试用例
        String testJson = "{\n" +
                "  \"node_status\": \"0\",\n" +
                "  \"Output\": {\"output\":\"https://www.1818ai.com/api/v1/drafts/download_draft?draft_id=040ac6aa-a786-4fa5-8dee-506ba1d6c35d\"}\n" +
                "}";
        
        String draftUrl = extractDraftUrl(testJson);
        System.out.println("提取的draft_url: " + draftUrl);
        
        // 验证结果
        if (draftUrl != null && draftUrl.equals("https://www.1818ai.com/api/v1/drafts/download_draft?draft_id=040ac6aa-a786-4fa5-8dee-506ba1d6c35d")) {
            System.out.println("测试成功！");
        } else {
            System.out.println("测试失败！");
        }
    }
}