package com.agent.management.skillgeneration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 技能生成运行状态注册表：内存跟踪所有进行中或已完成的生成任务。
 * 应用重启后状态丢失，但已写入全局 skills 目录的新技能持久保留。
 */
@Slf4j
@Component
public class SkillGenerationRegistry {

    private final Map<String, SkillGenerationState> store = new ConcurrentHashMap<>();

    public void save(SkillGenerationState state) {
        store.put(state.getRunId(), state);
    }

    public SkillGenerationState get(String runId) {
        return runId == null ? null : store.get(runId);
    }

    /**
     * 标记为运行中
     */
    public void markRunning(String runId) {
        SkillGenerationState state = store.get(runId);
        if (state != null) {
            state.setStatus(SkillGenerationState.Status.RUNNING);
        }
    }

    /**
     * 标记为成功，记录新技能 folderName
     */
    public void markSuccess(String runId, String generatedFolderName) {
        SkillGenerationState state = store.get(runId);
        if (state != null) {
            state.setStatus(SkillGenerationState.Status.SUCCESS);
            state.setGeneratedFolderName(generatedFolderName);
            state.setCompletedAt(Instant.now());
            log.info("[SkillGen] 生成成功 runId={}, newSkill={}", runId, generatedFolderName);
        }
    }

    /**
     * 标记为失败
     */
    public void markFailed(String runId, String error) {
        SkillGenerationState state = store.get(runId);
        if (state != null) {
            state.setStatus(SkillGenerationState.Status.FAILED);
            state.setErrorMessage(error);
            state.setCompletedAt(Instant.now());
            log.warn("[SkillGen] 生成失败 runId={}, error={}", runId, error);
        }
    }

    public void remove(String runId) {
        store.remove(runId);
    }
}
