package com.optage.parser;

import com.optage.model.BusinessLabel;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternBExtractor {
    // Pattern: private String fieldName = "";  // 日本語ラベル
    private static final Pattern FIELD_LABEL_PATTERN = Pattern.compile(
        "//\\s*([\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}]+.*?)\\s*$"
    );

    public List<BusinessLabel> extract(String code) {
        List<BusinessLabel> labels = new ArrayList<>();
        String[] lines = code.split("\n");

        for (String line : lines) {
            // Check if line has field declaration and comment
            if (line.contains("private") || line.contains("public")) {
                int commentIndex = line.indexOf("//");
                if (commentIndex > 0) {
                    String fieldPart = line.substring(0, commentIndex);
                    String commentPart = line.substring(commentIndex);

                    String fieldName = extractFieldName(fieldPart);
                    String label = extractLabel(commentPart);

                    if (fieldName != null && label != null && !label.isEmpty()) {
                        labels.add(new BusinessLabel(fieldName, label, "inline_comment"));
                    }
                }
            }
        }

        return labels;
    }

    private String extractFieldName(String fieldPart) {
        Pattern pattern = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\s*=");
        Matcher matcher = pattern.matcher(fieldPart);
        return matcher.find() ? matcher.group(1) : null;
    }

    private String extractLabel(String commentPart) {
        Matcher matcher = FIELD_LABEL_PATTERN.matcher(commentPart);
        return matcher.find() ? matcher.group(1).trim() : null;
    }
}