/**
 * audit-dev-frontend/validate.ts — Args validation (Zod + projectPath sanity check).
 * No file I/O beyond verifying paths exist and look like the right shape.
 */
import { existsSync, statSync } from 'node:fs';
import path from 'node:path';
import { AuditDevFrontendArgsSchema, type AuditDevFrontendArgs } from './types.js';

export interface ArgsValidationResult {
  valid: boolean;
  args: AuditDevFrontendArgs | null;
  errors: string[];
}

export function validateArgs(raw: unknown): ArgsValidationResult {
  const parsed = AuditDevFrontendArgsSchema.safeParse(raw);
  if (!parsed.success) {
    return {
      valid: false,
      args: null,
      errors: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
    };
  }

  const args = parsed.data;
  const errors: string[] = [];

  // projectPath must exist and contain a `src` directory.
  const abs = path.resolve(args.projectPath);
  if (!existsSync(abs)) {
    errors.push(`projectPath does not exist: ${abs}`);
  } else if (!statSync(abs).isDirectory()) {
    errors.push(`projectPath is not a directory: ${abs}`);
  } else if (!existsSync(path.join(abs, 'src'))) {
    errors.push(`projectPath has no "src" folder — are you sure this is a React app root? ${abs}`);
  }

  // PRD slice path must exist if provided.
  if (args.prdSlice) {
    const prdAbs = path.resolve(args.prdSlice);
    if (!existsSync(prdAbs)) {
      errors.push(`prdSlice does not exist: ${prdAbs}`);
    }
  }

  // Inventory path must exist if provided.
  if (args.inventory) {
    const invAbs = path.resolve(args.inventory);
    if (!existsSync(invAbs)) {
      errors.push(`inventory does not exist: ${invAbs}`);
    }
  }

  // Backend path must be a directory if provided.
  if (args.backendPath) {
    const beAbs = path.resolve(args.backendPath);
    if (!existsSync(beAbs)) {
      errors.push(`backendPath does not exist: ${beAbs}`);
    } else if (!statSync(beAbs).isDirectory()) {
      errors.push(`backendPath is not a directory: ${beAbs}`);
    }
  }

  // Core navigation seed path must be a file if provided.
  if (args.coreNavigationSeedPath) {
    const navAbs = path.resolve(args.coreNavigationSeedPath);
    if (!existsSync(navAbs)) {
      errors.push(`coreNavigationSeedPath does not exist: ${navAbs}`);
    }
  }

  // Rule codes must look like DEV-UI-NNN.
  for (const ruleId of args.rules) {
    if (!/^DEV-UI-\d{3}$/.test(ruleId)) {
      errors.push(`rule id "${ruleId}" must match /^DEV-UI-\\d{3}$/ (e.g. "DEV-UI-001")`);
    }
  }

  return { valid: errors.length === 0, args, errors };
}
