/** Shared hook for starting a tool on a workspace. */

import { useCallback, useState } from "react";
import { createInstance, startInstance } from "../api/sessions";
import type { Workspace } from "../types/workspace";
import type { ToolInstance } from "../api/sessions";

export interface UseStartToolResult {
	starting: boolean;
	error: string | null;
	startTool: (
		workspace: Workspace,
		toolTypeId: string,
		displayName?: string,
		configProfileId?: string,
	) => Promise<ToolInstance | null>;
}

export function useStartTool(): UseStartToolResult {
	const [starting, setStarting] = useState(false);
	const [error, setError] = useState<string | null>(null);

	const startTool = useCallback(
		async (
			workspace: Workspace,
			toolTypeId: string,
			displayName?: string,
			configProfileId?: string,
		): Promise<ToolInstance | null> => {
			setStarting(true);
			setError(null);
			try {
				const instance = await createInstance(
					workspace.project_id,
					workspace.repo_id,
					toolTypeId,
					displayName || workspace.name,
					workspace.id,
					configProfileId,
					[],
				);
				await startInstance(
					workspace.project_id,
					workspace.repo_id,
					instance.id,
					configProfileId,
				);
				return instance;
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Failed to start tool";
				setError(msg);
				return null;
			} finally {
				setStarting(false);
			}
		},
		[],
	);

	return { starting, error, startTool };
}
