package com.aicheck.analyzer;

import com.aicheck.model.FieldChange;
import com.aicheck.model.FieldInfo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 对比新旧字段列表，产出新增/删除/类型修改（纯注释变更忽略）。
 */
public class FieldDiffEngine {

    /** 按字段名对比，仅类型变化记为 MODIFIED */
    public List<FieldChange> diff(List<FieldInfo> oldFields, List<FieldInfo> newFields) {
        Map<String, FieldInfo> oldMap = toMap(oldFields);
        Map<String, FieldInfo> newMap = toMap(newFields);
        List<FieldChange> changes = new ArrayList<>();

        for (Map.Entry<String, FieldInfo> entry : newMap.entrySet()) {
            FieldInfo oldField = oldMap.get(entry.getKey());
            FieldInfo newField = entry.getValue();
            if (oldField == null) {
                changes.add(FieldChange.added(newField));
            } else if (!oldField.getType().equals(newField.getType())) {
                changes.add(FieldChange.modified(oldField, newField, buildTypeDetail(oldField, newField)));
            }
            // 仅 @Schema / 注释文案变化：不纳入字段变更
        }

        for (Map.Entry<String, FieldInfo> entry : oldMap.entrySet()) {
            if (!newMap.containsKey(entry.getKey())) {
                changes.add(FieldChange.removed(entry.getValue()));
            }
        }
        return changes;
    }

    /** 字段列表转 LinkedHashMap，保持声明顺序 */
    private Map<String, FieldInfo> toMap(List<FieldInfo> fields) {
        Map<String, FieldInfo> map = new LinkedHashMap<>();
        for (FieldInfo field : fields) {
            map.put(field.getName(), field);
        }
        return map;
    }

    /** 构造类型变化描述，如 Integer → String */
    private String buildTypeDetail(FieldInfo oldField, FieldInfo newField) {
        if (oldField.getType().equals(newField.getType())) {
            return "";
        }
        return oldField.getType() + " → " + newField.getType();
    }
}
