package com.gzzm.lobster.api;

import com.gzzm.lobster.common.MemoryCategory;
import com.gzzm.lobster.identity.UserContext;
import com.gzzm.lobster.identity.UserContextHolder;
import com.gzzm.lobster.memory.MemoryService;
import com.gzzm.lobster.memory.PersonalMemory;
import net.cyan.arachne.HttpMethod;
import net.cyan.arachne.annotation.Service;
import net.cyan.nest.annotation.Inject;

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

/**
 * MemoryApi —— 个人记忆后台管理 API / Personal memory admin API.
 *
 * <p>遵循 Claude Code 的「索引 + 正文」两层接口：
 * <ul>
 *   <li>{@code /list}：全量索引（不含 content），前端列表页用</li>
 *   <li>{@code /read}：单条完整正文</li>
 *   <li>{@code /create}：写入（name + description + category 必填）</li>
 *   <li>{@code /suppress}：软删除</li>
 * </ul>
 */
@Service
public class MemoryApi {

    @Inject private MemoryService memoryService;

    @Service(url = "/ai/api/memories/list", method = HttpMethod.all)
    public Map<String, Object> list(String category, Integer limit) throws Exception {
        UserContext user = UserContextHolder.require();
        int l = limit == null ? 50 : Math.min(500, limit);
        List<PersonalMemory> hits;
        if (category == null || category.isEmpty() || "ALL".equalsIgnoreCase(category)) {
            hits = memoryService.listIndex(user, l);
        } else {
            hits = memoryService.listByCategory(user, MemoryCategory.valueOf(category), l);
        }
        List<Map<String, Object>> items = new ArrayList<>();
        for (PersonalMemory m : hits) items.add(toIndexRow(m));
        Map<String, Object> out = new LinkedHashMap<>();
        out.put("memories", items);
        return out;
    }

    @Service(url = "/ai/api/memories/read", method = HttpMethod.post)
    public Map<String, Object> read(String memoryId) throws Exception {
        UserContext user = UserContextHolder.require();
        PersonalMemory m = memoryService.read(user, memoryId);
        Map<String, Object> out = toIndexRow(m);
        out.put("content", m.getContent());
        out.put("sourceType", m.getSourceType());
        out.put("updateTime", m.getUpdateTime());
        return out;
    }

    @Service(url = "/ai/api/memories/create", method = HttpMethod.post)
    public Map<String, Object> create(String name, String description, String content,
                                      String category, String sourceType) throws Exception {
        UserContext user = UserContextHolder.require();
        MemoryCategory cat = category == null ? MemoryCategory.user : MemoryCategory.valueOf(category);
        PersonalMemory m = memoryService.write(user, name, description, content, cat,
                sourceType == null || sourceType.isEmpty() ? "explicit_user_write" : sourceType);
        Map<String, Object> out = toIndexRow(m);
        out.put("status", "SAVED");
        return out;
    }

    @Service(url = "/ai/api/memories/suppress", method = HttpMethod.post)
    public Map<String, Object> suppress(String memoryId) throws Exception {
        UserContext user = UserContextHolder.require();
        int n = memoryService.suppress(user, memoryId);
        Map<String, Object> out = new LinkedHashMap<>();
        out.put("memoryId", memoryId);
        out.put("affected", n);
        return out;
    }

    private Map<String, Object> toIndexRow(PersonalMemory m) {
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("memoryId", m.getMemoryId());
        row.put("name", m.getName());
        row.put("description", m.getDescription());
        row.put("category", m.getCategory() == null ? null : m.getCategory().name());
        row.put("createTime", m.getCreateTime());
        return row;
    }
}
