package com.agent.management.rag.graph;

import com.agent.management.service.GraphSourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
public class GraphSchemaDiscoveryService {
    private static final Duration CACHE_TTL = Duration.ofMinutes(5);
    private final GraphSourceService graphSources;
    private final Map<Long, CachedSchema> cache = new ConcurrentHashMap<>();

    public GraphSchemaSnapshot get(Long graphSourceId) {
        CachedSchema cached = cache.get(graphSourceId);
        if (cached != null && cached.loadedAt().plus(CACHE_TTL).isAfter(Instant.now())) return cached.schema();
        return refresh(graphSourceId);
    }

    public GraphSchemaSnapshot refresh(Long graphSourceId) {
        GraphSchemaSnapshot schema = graphSources.discoverSchema(graphSourceId);
        cache.put(graphSourceId, new CachedSchema(schema, Instant.now()));
        return schema;
    }

    private record CachedSchema(GraphSchemaSnapshot schema, Instant loadedAt) {}
}
