/**
 * audit-dev-actions-alignment / validate.ts
 *
 * Zod parse + path checks. Mode `apply` requires the writeReport flag to be
 * intentional (we never mutate without leaving an audit trail).
 */
import { existsSync, statSync } from 'node:fs'
import { ActionAlignmentArgsSchema, type ValidationResult } from './types.js'

export function validateArgs(raw: unknown): ValidationResult {
  const parsed = ActionAlignmentArgsSchema.safeParse(raw)
  if (!parsed.success) {
    return {
      valid: false,
      errors: parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`),
    }
  }
  const args = parsed.data
  const errors: string[] = []

  for (const [field, p] of [
    ['projectPath', args.projectPath],
    ['backendPath', args.backendPath],
  ] as const) {
    if (!existsSync(p) || !statSync(p).isDirectory()) {
      errors.push(`${field} does not exist or is not a directory: ${p}`)
    }
  }

  if (args.modulePath && (!existsSync(args.modulePath) || !statSync(args.modulePath).isDirectory())) {
    errors.push(`modulePath does not exist or is not a directory: ${args.modulePath}`)
  }

  if (errors.length > 0) return { valid: false, errors }
  return { valid: true, args, errors: [] }
}
