import { readFile, readdir, stat } from 'node:fs/promises'
import { join } from 'node:path'

const MANIFEST_NAMES = [
  'package.json',
  'go.mod',
  'Cargo.toml',
  'pyproject.toml',
  'pom.xml',
  'Makefile',
]

/** 扫描项目 manifest 与浅层目录树，供 inspect 使用 */
export async function scanProjectBrief(
  codeWorkDir: string,
  maxDepth = 2,
): Promise<{ manifests: Record<string, string>; tree: string[] }> {
  const manifests: Record<string, string> = {}
  for (const name of MANIFEST_NAMES) {
    const p = join(codeWorkDir, name)
    try {
      const st = await stat(p)
      if (st.isFile()) {
        const raw = await readFile(p, 'utf8')
        manifests[name] = raw.length > 8000 ? `${raw.slice(0, 8000)}…` : raw
      }
    } catch {
      // 不存在则跳过
    }
  }
  const tree: string[] = []
  await walkDir(codeWorkDir, '', 0, maxDepth, tree)
  return { manifests, tree }
}

async function walkDir(
  root: string,
  rel: string,
  depth: number,
  maxDepth: number,
  out: string[],
): Promise<void> {
  if (depth > maxDepth) return
  const full = rel ? join(root, rel) : root
  let entries: import('node:fs').Dirent[]
  try {
    entries = await readdir(full, { withFileTypes: true })
  } catch {
    return
  }
  const sorted = entries
    .filter(e => !e.name.startsWith('.') && e.name !== 'node_modules')
    .sort((a, b) => a.name.localeCompare(b.name))
  for (const e of sorted.slice(0, 40)) {
    const childRel = rel ? `${rel}/${e.name}` : e.name
    out.push(`${'  '.repeat(depth)}${e.name}${e.isDirectory() ? '/' : ''}`)
    if (e.isDirectory() && depth < maxDepth) {
      await walkDir(root, childRel, depth + 1, maxDepth, out)
    }
  }
}
