import { Annotation, StateGraph, START, END } from '@langchain/langgraph';
import { buildAnalyzePrompt } from './prompts/analyze-repository.prompt.js';
import { hasSettings, getSettings } from '../../../services/settings.service.js';
/** Default timeout for analyze-repo agent (10 minutes) — prevents infinite hangs. */
const DEFAULT_ANALYZE_REPO_TIMEOUT_MS = 600_000;
/**
 * Resolve the timeout for the analyze-repository agent.
 * Reads from settings (workflow.analyzeRepoTimeouts.analyzeMs),
 * falling back to DEFAULT_ANALYZE_REPO_TIMEOUT_MS when not configured.
 */
function getAnalyzeRepoTimeoutMs() {
    if (!hasSettings())
        return DEFAULT_ANALYZE_REPO_TIMEOUT_MS;
    const timeouts = getSettings().workflow?.analyzeRepoTimeouts;
    return timeouts?.analyzeMs ?? DEFAULT_ANALYZE_REPO_TIMEOUT_MS;
}
/**
 * State annotation for the analyze-repository graph.
 *
 * Uses LangGraph's Annotation API to define state channels with
 * last-value semantics (default behavior — each update replaces the value).
 */
export const AnalyzeRepositoryState = Annotation.Root({
    repositoryPath: (Annotation),
    analysisMarkdown: (Annotation),
    error: (Annotation),
});
/**
 * Creates the analyze node function that calls the agent-agnostic executor.
 *
 * The node receives the current state, builds a prompt from the repository path,
 * and delegates execution to the injected IAgentExecutor. Each invocation gets
 * a clean agent context (no session resume).
 */
function createAnalyzeNode(executor) {
    return async (state) => {
        const prompt = buildAnalyzePrompt(state.repositoryPath);
        const result = await executor.execute(prompt, {
            cwd: state.repositoryPath,
            timeout: getAnalyzeRepoTimeoutMs(),
        });
        return {
            analysisMarkdown: result.result,
        };
    };
}
/**
 * Factory function that creates and compiles the analyze-repository LangGraph.
 *
 * The graph has a single node (`analyze`) that calls the provided IAgentExecutor
 * to generate a repository analysis document. An optional checkpointer enables
 * persistence of graph state across invocations.
 *
 * @param executor - The agent executor to delegate prompt execution to
 * @param checkpointer - Optional checkpoint saver for state persistence
 * @returns A compiled LangGraph ready to be invoked
 */
export function createAnalyzeRepositoryGraph(executor, checkpointer) {
    const graph = new StateGraph(AnalyzeRepositoryState)
        .addNode('analyze', createAnalyzeNode(executor))
        .addEdge(START, 'analyze')
        .addEdge('analyze', END);
    return graph.compile({ checkpointer });
}
