package com.initialone.jhumanify.llm;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Heuristic, offline doc generator to avoid LLM calls for trivial cases. */
public class RuleDocClient implements DocClient {

    private static final Pattern GETTER = Pattern.compile(
            "^\\s*(?:@\\w+(?:\\([^)]*\\))?\\s+)*" +
                    "(?:public|protected|private)?\\s*(?:static\\s+)?"
                    + "[\\w$<>\\[\\].]+\\s+get([A-Z][\\w]*)\\s*\\("
    );

    private static final Pattern SETTER = Pattern.compile(
            "^\\s*(?:@\\w+(?:\\([^)]*\\))?\\s+)*"
                    + "(?:public|protected|private)?\\s*(?:static\\s+)?"
                    + "void\\s+set([A-Z][\\w]*)\\s*\\("
    );

    private static final Pattern ISSER = Pattern.compile(
            "^\\s*(?:@\\w+(?:\\([^)]*\\))?\\s+)*"
                    + "(?:public|protected|private)?\\s*(?:static\\s+)?"
                    + "(?:boolean|Boolean)\\s+is([A-Z][\\w]*)\\s*\\("
    );


    @Override
    public List<String> summarizeDocs(List<String> snippets, String lang, String style) {
        List<String> out = new ArrayList<>();
        for (String s : snippets) {
            out.add(summarizeOne(s, lang, style));
        }
        return out;
    }

    private static String summarizeOne(String snippet, String lang, String style) {
        String header = firstLine(snippet).trim();
        String lower = header.toLowerCase(Locale.ROOT);

        String zhGetter = "获取%s。";
        String zhSetter = "设置%s。";
        String zhIsser  = "返回%s状态。";

        String enGetter = "Gets %s.";
        String enSetter = "Sets %s.";
        String enIsser  = "Returns whether %s.";

        // simple classifiers
        Matcher m;
        m = GETTER.matcher(header);
        if (m.find()) {
            String field = prettyName(m.group(1));
            return lang.equals("zh") ? String.format(zhGetter, field) : String.format(enGetter, field);
        }

        m = SETTER.matcher(header);
        if (m.find()) {
            String field = prettyName(m.group(1));
            return lang.equals("zh") ? String.format(zhSetter, field) : String.format(enSetter, field);
        }

        m = ISSER.matcher(header);
        if (m.find()) {
            String field = prettyName(m.group(1));
            return lang.equals("zh") ? String.format(zhIsser, field) : String.format(enIsser, field);
        }

        // fallback keywords
        String msg;
        if (lower.contains("tojson") || lower.contains("fromjson") || lower.contains("json")) {
            msg = lang.equals("zh") ? "在 JSON 与对象之间进行序列化/反序列化。" : "Serializes/deserializes between JSON and objects.";
        } else if (lower.contains("hash") || lower.contains("digest") || lower.contains("crc") || lower.contains("fnv")) {
            msg = lang.equals("zh") ? "计算并返回哈希/校验值。" : "Computes and returns a hash/checksum.";
        } else if (lower.contains("parse") || lower.contains("tokenize")) {
            msg = lang.equals("zh") ? "解析输入并返回结构化结果。" : "Parses the input and returns a structured result.";
        } else if (lower.contains("http") || lower.contains("request") || lower.contains("fetch")) {
            msg = lang.equals("zh") ? "执行网络请求并处理响应。" : "Performs a network request and processes the response.";
        } else if (lower.contains("init") || lower.contains("setup") || lower.contains("configure")) {
            msg = lang.equals("zh") ? "完成必要的初始化/配置。" : "Performs necessary initialization/configuration.";
        } else if (lower.contains("close") || lower.contains("shutdown") || lower.contains("dispose")) {
            msg = lang.equals("zh") ? "释放资源并安全关闭。" : "Releases resources and shuts down safely.";
        } else {
            msg = lang.equals("zh") ? "执行与方法名一致的核心功能。" : "Performs the core function implied by its name.";
        }
        if ("detailed".equals(style)) {
            msg += lang.equals("zh") ? "（由启发式规则自动生成）" : " (auto-generated by heuristics).";
        }
        return msg;
    }

    private static String firstLine(String s) {
        int i = s.indexOf('\n');
        return i >= 0 ? s.substring(0, i) : s;
    }

    private static String prettyName(String pascal) {
        if (pascal == null || pascal.isEmpty()) return "value";
        StringBuilder sb = new StringBuilder();
        char[] arr = pascal.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            char c = arr[i];
            if (i > 0 && Character.isUpperCase(c)) sb.append(' ');
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString().trim();
    }
}