import { loadCodeMd } from '../memory/loadCodeMd.js'
import { scanProjectBrief } from '../projectScan.js'
import { getCodeMdExcludes, requireCodeWorkDir } from '../hooks.js'

export async function runInspect(brief: boolean): Promise<Record<string, unknown>> {
  const codeWorkDir = requireCodeWorkDir()
  const memory = await loadCodeMd({
    projectRoot: codeWorkDir,
    excludes: getCodeMdExcludes(),
    maxChars: brief ? 12_000 : undefined,
  })
  const { manifests, tree } = await scanProjectBrief(codeWorkDir)
  let readme = ''
  try {
    const { readFile } = await import('node:fs/promises')
    const { join } = await import('node:path')
    readme = await readFile(join(codeWorkDir, 'README.md'), 'utf8')
    if (readme.length > 6000) readme = `${readme.slice(0, 6000)}…`
  } catch {
    readme = ''
  }
  return {
    codeWorkDir,
    codeMemory: memory,
    hasCodeMemory: memory.length > 0,
    readme: brief && readme.length > 2000 ? `${readme.slice(0, 2000)}…` : readme,
    manifests: brief ? Object.keys(manifests) : manifests,
    tree: brief ? tree.slice(0, 40) : tree,
  }
}
