package com.huimv.employment.integration.kb;

import com.huimv.employment.common.exception.BizException;
import com.huimv.employment.common.exception.ErrorCode;
import org.springframework.util.StringUtils;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * 将业务表中的 {@code content_file_url} 解析为知识库「按 URL 拉取」接口所需的完整地址。
 */
public final class KbFileUrlResolver {

    private KbFileUrlResolver() {
    }

    /**
     * @param contentFileUrl 表字段 content_file_url
     * @param properties     {@code fe.kb} 配置（file-url-base、可选 URL 改写）
     */
    public static String resolveForKbUpload(String contentFileUrl, KbApiProperties properties) {
        if (!StringUtils.hasText(contentFileUrl)) {
            throw new BizException(ErrorCode.BAD_REQUEST, "正文访问地址为空，无法同步知识库");
        }
        String fileUrlBase = properties != null ? properties.getFileUrlBase() : "";
        String p = contentFileUrl.trim();
        if (startsWithHttp(p)) {
            return rewriteHostIfConfigured(contentFileUrl, p, properties);
        }
        if (!StringUtils.hasText(fileUrlBase)) {
            throw new BizException(ErrorCode.BAD_REQUEST,
                    "正文访问地址不是完整 http(s) 地址时，请在配置中设置 fe.kb.file-url-base");
        }
        String base = fileUrlBase.trim();
        while (base.endsWith("/")) {
            base = base.substring(0, base.length() - 1);
        }
        String path = p.startsWith("/") ? p : "/" + p;
        return rewriteHostIfConfigured(contentFileUrl, base + path, properties);
    }

    private static boolean startsWithHttp(String url) {
        return url.regionMatches(true, 0, "http://", 0, 7)
                || url.regionMatches(true, 0, "https://", 0, 8);
    }

    /**
     * 正文 URL 含配置的外网域名时，将解析结果中的域名替换为内网地址，便于知识库节点拉取文件。
     */
    static String rewriteHostIfConfigured(String contentFileUrl, String resolvedUrl, KbApiProperties properties) {
        if (!StringUtils.hasText(contentFileUrl) || !StringUtils.hasText(resolvedUrl) || properties == null) {
            return resolvedUrl;
        }
        String fromHost = properties.getUrlRewriteFromHost();
        String toHost = properties.getUrlRewriteToHost();
        if (!StringUtils.hasText(fromHost) || !StringUtils.hasText(toHost)) {
            return resolvedUrl;
        }
        if (!contentFileUrl.contains(fromHost)) {
            return resolvedUrl;
        }
        try {
            URI uri = new URI(resolvedUrl);
            if (uri.getHost() == null || !fromHost.equalsIgnoreCase(uri.getHost())) {
                return resolvedUrl;
            }
            StringBuilder sb = new StringBuilder();
            sb.append(uri.getScheme()).append("://").append(toHost);
            if (uri.getRawPath() != null) {
                sb.append(uri.getRawPath());
            }
            if (uri.getRawQuery() != null) {
                sb.append('?').append(uri.getRawQuery());
            }
            if (uri.getRawFragment() != null) {
                sb.append('#').append(uri.getRawFragment());
            }
            return sb.toString();
        } catch (URISyntaxException e) {
            return resolvedUrl;
        }
    }
}
