import { isAbsolute, join, normalize, relative, resolve } from 'node:path'
import { CODE_LOCAL_MD, CODE_MD } from './memory/constants.js'

/** 业务仓库内相对路径校验，禁止逃逸 codeWorkDir */
export function resolveInWorkDir(
  codeWorkDir: string,
  relPath: string,
): string {
  const base = resolve(codeWorkDir)
  const target = resolve(base, normalize(relPath))
  const rel = relative(base, target)
  if (rel.startsWith('..') || isAbsolute(rel)) {
    throw new Error(`路径越界: ${relPath}`)
  }
  return target
}

/** apply 禁止修改 code.md / code.local.md */
export function assertApplyPathAllowed(relPath: string): void {
  const norm = relPath.replaceAll('\\', '/')
  const base = norm.split('/').pop() ?? norm
  if (base === CODE_MD || base === CODE_LOCAL_MD) {
    throw new Error(
      `禁止通过 apply 修改 ${base}，请使用 CodeTool action=record`,
    )
  }
}

export function getCodeMdAbsolutePath(codeWorkDir: string): string {
  return join(resolve(codeWorkDir), CODE_MD)
}
