import { access } from 'node:fs/promises'
import { isEnabledInAgentConfig } from './agentConfig.js'
import { configure, getCachedConfigure, resetConfigure } from './hooks.js'
import { resolveCodeWorkDir } from './workspace.js'

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

export type CodeToolWsInitResult =
  | { state: 'ready' }
  | { state: 'skipped'; reason: string }

/** 会话初始化：按 agent 白名单与工作目录状态决定 CodeTool 是否就绪 */
export async function initWsSession(
  ctx: CodeToolWsInitContext,
): Promise<CodeToolWsInitResult> {
  if (!isEnabledInAgentConfig(ctx.agent)) {
    resetConfigure()
    delete process.env.CODE_WORK_DIR
    return { state: 'skipped', reason: 'CodeTool disabled in agent config' }
  }
  const codeWorkDir = resolveCodeWorkDir(ctx.operWorkspaceDir)
  try {
    await access(codeWorkDir)
  } catch {
    resetConfigure()
    delete process.env.CODE_WORK_DIR
    return {
      state: 'skipped',
      reason: `code work directory not found: ${codeWorkDir}`,
    }
  }
  process.env.CODE_WORK_DIR = codeWorkDir
  configure({
    getCodeWorkDir: () => codeWorkDir,
    getCodeMdExcludes: () => [],
  })
  return { state: 'ready' }
}

/** runtime 重载模块时恢复已配置 hooks */
export function ensureConfigured(): void {
  const cached = getCachedConfigure()
  if (cached) {
    configure(cached)
  }
}
