/**
 * Sandbox Manager — 沙箱执行环境
 *
 * 四层纵深防御：进程隔离、路径白名单、网络策略、资源限制。
 *
 * @see docs/生产级通用 AI Agent 智能体桌面应用：完整设计与构建指南.html — 第五章
 */

export interface SandboxConfig {
  allowedPaths?: string[];
  networkPolicy?: 'allowall' | 'deny-all' | 'allowlist';
  resourceLimits?: Partial<ResourceLimits>;
}

export interface ResourceLimits {
  maxMemoryMB: number;
  maxCpuSeconds: number;
  maxExecutionMs: number;
  maxOutputSizeKB: number;
}

export interface SandboxExecutionResult {
  success: boolean;
  output?: string;
  stderr?: string;
  exitCode?: number;
  error?: string;
  durationMs: number;
}

export class SandboxManager {
  private allowedPaths: Set<string> = new Set();
  private networkPolicy: 'allowall' | 'deny-all' | 'allowlist' = 'deny-all';
  private resourceLimits: ResourceLimits = {
    maxMemoryMB: 512,
    maxCpuSeconds: 30,
    maxExecutionMs: 60_000,
    maxOutputSizeKB: 1024,
  };

  constructor(private config: SandboxConfig) {
    this.allowedPaths = new Set(config.allowedPaths ?? []);
    this.networkPolicy = config.networkPolicy ?? 'allowlist';
  }

  /**
   * 校验文件路径是否在白名单内
   */
  validatePath(requestedPath: string): { allowed: boolean; resolvedPath: string; reason?: string } {
    const { resolve } = require('path');
    const resolved = resolve(requestedPath);

    if (requestedPath.includes('..')) {
      return { allowed: false, resolvedPath: resolved, reason: 'Path traversal detected' };
    }

    if (this.allowedPaths.size > 0) {
      const isAllowed = Array.from(this.allowedPaths).some((allowed) => resolved.startsWith(allowed));
      if (!isAllowed) {
        return { allowed: false, resolvedPath: resolved, reason: 'Path not in allowed list' };
      }
    }

    return { allowed: true, resolvedPath: resolved };
  }

  /**
   * 静态代码安全扫描
   */
  scanCode(code: string): { safe: boolean; reason?: string } {
    const dangerousPatterns = [
      /require\s*\(\s*['"]child_process['"]\s*\)/,
      /eval\s*\(/,
      /process\.exit/,
      /import\s+.*from\s+['"]fs['"]/,
      /\.\.\//,
      /rm\s+-rf/,
      />\s*\/dev\/null/,
      /curl.*\|\s*bash/,
      /wget.*\|\s*sh/,
    ];

    for (const pattern of dangerousPatterns) {
      if (pattern.test(code)) {
        return { safe: false, reason: `Dangerous pattern detected: ${pattern.source}` };
      }
    }

    return { safe: true };
  }
}
