package com.cameleer.server.core.agent;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * In-memory registry tracking the operational state of routes.
 * State is updated from agent heartbeats (routeStates map) and
 * ROUTE_STATE_CHANGED lifecycle events.
 * On server restart, all states reset to STARTED (default Camel behavior).
 */
public class RouteStateRegistry {

    public enum RouteState { STARTED, STOPPED, SUSPENDED }

    // Key: "applicationId:routeId"
    private final ConcurrentHashMap<String, RouteState> states = new ConcurrentHashMap<>();

    public void setState(String applicationId, String routeId, RouteState state) {
        states.put(applicationId + ":" + routeId, state);
    }

    public RouteState getState(String applicationId, String routeId) {
        return states.getOrDefault(applicationId + ":" + routeId, RouteState.STARTED);
    }

    public Map<String, RouteState> getStatesForApplication(String applicationId) {
        Map<String, RouteState> result = new LinkedHashMap<>();
        states.forEach((key, state) -> {
            if (key.startsWith(applicationId + ":")) {
                result.put(key.substring(applicationId.length() + 1), state);
            }
        });
        return result;
    }
}
