import { client } from "@/client";
import type { AgentSessionResponse } from "@/client/models/agentSessionResponse";

/**
 * Find an existing workspace session or create one.
 * Returns the session ID, or null if creation fails.
 */
export async function ensureWorkspaceSession(
  projectName: string,
  existingSessions: AgentSessionResponse[],
): Promise<string | null> {
  // Reuse existing workspace session if available.
  const wsSession = existingSessions.find(
    (s) => s.enabled && s.wk != null && s.wk !== "",
  );
  if (wsSession) return wsSession.id;

  // Create a new session scoped to this workspace.
  try {
    const modelsRes = await client.aiListModels();
    const modelVersion = modelsRes.data[0]?.id;
    if (!modelVersion) return null;

    const res = await client.agentCreateSession({
      name: `${projectName} Agent`,
      agent_kind: "chat",
      model_version: modelVersion,
      wk: projectName,
      visibility: "workspace",
    });
    return res.data.id;
  } catch {
    return null;
  }
}
