/**
 * WS 子进程 init：由 runtimeToolLoader 通用入口调用，不经过主工程 git 胶水层。
 */

import { isEnabledInAgentConfig } from './agentConfig.js'
import { resetConfigure } from './hooks.js'
import { prepareForAgent } from './workspace.js'

export type GitToolWsInitContext = {
  agentHomeDir: string
  operWorkspaceDir: string
  agent: {
    tools: string[]
    disallowedTools?: string[]
  }
}

export type GitToolWsInitResult =
  | { state: 'ready' }
  | { state: 'skipped'; reason?: string }
  | { state: 'failed'; error: string }

/** WS init：按 agent 白名单与环境变量准备 git 工作区 */
export async function initWsSession(
  ctx: GitToolWsInitContext,
): Promise<GitToolWsInitResult> {
  if (!isEnabledInAgentConfig(ctx.agent)) {
    resetConfigure()
    return { state: 'skipped', reason: 'GitTool disabled in agent config' }
  }
  try {
    const result = await prepareForAgent({ operWorkspaceDir: ctx.operWorkspaceDir })
    if (result === 'skipped') {
      resetConfigure()
      return {
        state: 'skipped',
        reason: 'git work directory not ready (configure WS_GIT_REPO_URL or existing repo)',
      }
    }
    return { state: 'ready' }
  } catch (e: unknown) {
    resetConfigure()
    return {
      state: 'failed',
      error: e instanceof Error ? e.message : String(e),
    }
  }
}
