package com.codechecker.api.parser;

import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.comments.JavadocComment;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 从方法 Javadoc 的 @param 标签提取形参说明（按 Java 形参名匹配）。
 */
public final class MethodParamJavadocExtractor {
    private static final Pattern PARAM_TAG = Pattern.compile(
            "@param\\s+(\\w+)\\s+(.+?)(?=\\s*@param\\s+|\\s*@return\\s+|\\s*@throws\\s+|\\s*@see\\s+|\\s*\\*/|$)",
            Pattern.DOTALL);

    private MethodParamJavadocExtractor() {
    }

    public static Map<String, String> extract(MethodDeclaration method) {
        Map<String, String> descriptions = new HashMap<>();
        if (method == null) {
            return descriptions;
        }
        Optional<JavadocComment> javadoc = method.getJavadocComment();
        if (javadoc.isEmpty()) {
            return descriptions;
        }
        String raw = javadoc.get().getContent();
        if (raw == null || raw.isBlank()) {
            return descriptions;
        }
        String normalized = raw.replace('\r', '\n');
        Matcher matcher = PARAM_TAG.matcher(normalized);
        while (matcher.find()) {
            String paramName = matcher.group(1).trim();
            String desc = cleanDescription(matcher.group(2));
            if (!paramName.isBlank()) {
                descriptions.put(paramName, desc);
            }
        }
        return descriptions;
    }

    private static String cleanDescription(String text) {
        if (text == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String line : text.split("\n")) {
            String trimmed = line.trim();
            if (trimmed.startsWith("*")) {
                trimmed = trimmed.substring(1).trim();
            }
            if (!trimmed.isEmpty()) {
                if (sb.length() > 0) {
                    sb.append(' ');
                }
                sb.append(trimmed);
            }
        }
        return sb.toString().trim();
    }
}
