import { fetchWithAuth } from './apiClient';

export const getAgents = async () => {
    return await fetchWithAuth(`/agents?_t=${Date.now()}`);
};

export const getAgentTelemetry = async (id) => {
    return await fetchWithAuth(`/agents/${id}/telemetry`);
};

export const getAgentDependencies = async (id) => {
    return await fetchWithAuth(`/agents/${id}/dependencies`);
};

export const updateAgentStatus = async (id, status) => {
    return await fetchWithAuth(`/agents/${id}/status`, {
        method: 'PATCH',
        body: { status }
    });
};

export const updateAgentConfig = async (id, config) => {
    return await fetchWithAuth(`/agents/${id}/config`, {
        method: 'PATCH',
        body: config
    });
};

export const deployAgent = async (payload) => {
    return await fetchWithAuth(`/agents/deploy`, {
        method: 'POST',
        body: payload
    });
};

export const deleteAgent = async (id) => {
    return await fetchWithAuth(`/agents/${id}`, {
        method: 'DELETE'
    });
};

export const getAgentTriggers = async (id) => {
    return await fetchWithAuth(`/agents/${id}/triggers`);
};

export const createAgentTrigger = async (id, triggerPayload) => {
    return await fetchWithAuth(`/agents/${id}/triggers`, {
        method: 'POST',
        body: triggerPayload
    });
};

export const deleteAgentTrigger = async (triggerId) => {
    return await fetchWithAuth(`/agents/triggers/${triggerId}`, {
        method: 'DELETE'
    });
};

export const resetAgentMetrics = async (id) => {
    return await fetchWithAuth(`/agents/${id}/metrics/reset`, {
        method: 'POST'
    });
};

/**
 * [Evaluation Hub] Fetch contents of the .cortex/ directory for a specific agent.
 */
export const getAgentCortexFiles = async (agentId, nodeId, sessionId) => {
    const params = new URLSearchParams({ path: ".cortex", session_id: sessionId });
    return await fetchWithAuth(`/nodes/${nodeId}/fs/ls?${params.toString()}`);
};

/**
 * [Evaluation Hub] Reading specific file from .cortex/ (e.g. feedback.md, history.log).
 */
export const getAgentCortexFile = async (agentId, nodeId, sessionId, fileName) => {
    // Distinguish between root guidelines and .cortex/ artifacts
    const filePath = fileName.startsWith('.') ? fileName : `.cortex/${fileName}`;
    const params = new URLSearchParams({ path: filePath, session_id: sessionId });
    return await fetchWithAuth(`/nodes/${nodeId}/fs/cat?${params.toString()}`);
};
