/**
 * 从混合格式文案（含文件名、说明、提取码等）中解析百度网盘标准分享链接。
 */

const PAN_S_URL_RE =
    /https?:\/\/pan\.baidu\.com\/s\/[A-Za-z0-9_-]+(?:\?(?:[A-Za-z0-9_=&%.-]*))?/i;

const PWD_LABEL_RE = /(?:提取码|密码|提取\s*码)[:：\s]*([A-Za-z0-9]{4,8})\b/i;

const FIRST_HTTP_RE =
    /https?:\/\/[^\s\u4e00-\u9fff\u3000-\u303f]+/i;

/**
 * @param {string|null|undefined} text
 * @returns {{ url: string|null, pwd: string|null }}
 */
export function parseBaiduPanShare(text) {
    if (text == null || text === "") {
        return { url: null, pwd: null };
    }
    const s = String(text);
    const urlMatch = s.match(PAN_S_URL_RE);
    let url = urlMatch ? urlMatch[0] : null;

    let pwd = null;
    if (url) {
        try {
            const u = new URL(url);
            pwd = u.searchParams.get("pwd") || u.searchParams.get("PWD");
        } catch {
            /* ignore */
        }
    }

    const pwdLabel = s.match(PWD_LABEL_RE);
    if (!pwd && pwdLabel) {
        pwd = pwdLabel[1];
    }

    if (url && pwd && !/pwd=/i.test(url)) {
        url += url.includes("?") ? `&pwd=${encodeURIComponent(pwd)}` : `?pwd=${encodeURIComponent(pwd)}`;
    }

    return { url, pwd };
}

/**
 * 表格/外链打开用：优先解析百度分享；否则取文案中首个 http(s) URL（去掉末尾中英文标点粘连）。
 * @param {string|null|undefined} raw
 * @returns {string|null}
 */
export function resolveExternalShareUrl(raw) {
    const { url } = parseBaiduPanShare(raw);
    if (url) return url;
    if (raw == null || raw === "") return null;
    const s = String(raw).trim();
    const any = s.match(FIRST_HTTP_RE);
    if (any) {
        return any[0].replace(/[,.;，。、；]+$/, "");
    }
    if (/^https?:\/\//i.test(s)) {
        return s.replace(/[,.;，。、；]+$/, "");
    }
    return null;
}
