/**
 * AI Execution Sinks Test Fixtures
 * Tests for detecting unsafe execution of LLM-generated code
 *
 * OWASP Reference: LLM02 - Insecure Output Handling
 * Attack Chain: Prompt Injection -> LLM generates malicious output -> Dangerous Sink -> RCE/SQLi/XSS/SSRF
 *
 * Test Groups:
 * 1. Code Execution Sinks (eval, Function, vm)
 * 2. Shell Command Sinks (exec, spawn, child_process)
 * 3. SQL Injection Sinks (query, execute, raw)
 * 4. DOM/XSS Sinks (innerHTML, dangerouslySetInnerHTML)
 * 5. Network/SSRF Sinks (fetch, axios, HTTP clients)
 * 6. Redirect Sinks (res.redirect, window.location)
 * 7. Header Injection Sinks (setHeader, cookie)
 * 8. File System Sinks (readFile, writeFile, path.join)
 * 9. Dynamic Import Sinks (import(), require())
 * 10. Python-Specific Sinks (eval, exec, pickle, subprocess)
 */

import type { TestGroup } from '../../types'

export const aiExecutionSinksTests: TestGroup = {
  name: 'AI Execution Sinks',
  tier: 'A',
  layer: 2,
  description: 'Detection of unsafe execution of LLM-generated code, SQL, and commands',

  truePositives: [
    // ============================================================================
    // Test Group 1: Code Execution Sinks
    // ============================================================================
    {
      name: 'Code Execution Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution', 'dangerous_function'],
      description: 'Code execution sinks that MUST be detected',
      file: {
        path: 'src/api/ai/code-executor.ts',
        content: `
import OpenAI from 'openai'
import vm from 'vm'

const openai = new OpenAI()

// 1. eval() with LLM output - CRITICAL
export async function evalAICode(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const code = response.choices[0].message.content
  return eval(code)  // CRITICAL: Direct code execution
}

// 2. Function constructor - CRITICAL
export async function createAIFunction(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  return new Function(response.choices[0].message.content)
}

// 3. vm.runInContext without proper sandbox - HIGH
export async function runInVMContext(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const context = vm.createContext({ console })
  return vm.runInContext(response.choices[0].message.content, context)
}

// 4. setTimeout with string (indirect eval) - HIGH
export async function delayedExecution(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  setTimeout(response.choices[0].message.content, 1000)  // String arg = eval
}

// 5. Indirect eval via global - CRITICAL
export async function indirectEval(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  globalThis.eval(response.choices[0].message.content)
}
`,
        language: 'typescript',
        size: 1600,
      },
    },

    // ============================================================================
    // Test Group 2: Shell Command Sinks
    // ============================================================================
    {
      name: 'Shell Command Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution'],
      description: 'Shell command sinks that MUST be detected',
      file: {
        path: 'src/api/ai/shell-executor.ts',
        content: `
import OpenAI from 'openai'
import { exec, execSync, spawn } from 'child_process'
import execa from 'execa'

const openai = new OpenAI()

// 1. exec() with LLM command - CRITICAL
export async function executeAICommand(task: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: \`Generate a shell command to: \${task}\` }]
  })
  const command = response.choices[0].message.content
  exec(command, (err, stdout) => console.log(stdout))
}

// 2. spawn() with LLM command - CRITICAL
export async function spawnAIProcess(task: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: task }]
  })
  const completion = response.choices[0].message
  spawn(completion.content, [])
}

// 3. execSync with interpolation - CRITICAL
export async function execSyncAI(userPath: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: \`Process path: \${userPath}\` }]
  })
  execSync(\`ls \${response.choices[0].message.content}\`)
}

// 4. child_process.exec with AI - CRITICAL
export async function childProcessExec(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const child_process = require('child_process')
  child_process.exec(response.choices[0].message.content)
}

// 5. execa with LLM command - CRITICAL
export async function execaAI(task: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: task }]
  })
  await execa(response.choices[0].message.content, [])
}
`,
        language: 'typescript',
        size: 1600,
      },
    },

    // ============================================================================
    // Test Group 3: SQL Injection Sinks
    // ============================================================================
    {
      name: 'SQL Injection Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution', 'dangerous_function'],
      description: 'SQL injection sinks that MUST be detected',
      file: {
        path: 'src/api/ai/sql-executor.ts',
        content: `
import OpenAI from 'openai'
import { PrismaClient } from '@prisma/client'
import Sequelize from 'sequelize'
import knex from 'knex'

const openai = new OpenAI()
const prisma = new PrismaClient()
const sequelize = new Sequelize('database')
const db = knex({ client: 'pg' })

// 1. Raw query with LLM SQL - CRITICAL
export async function executeAIQuery(userQuestion: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'system', content: 'Convert to SQL' }, { role: 'user', content: userQuestion }]
  })
  const sql = response.choices[0].message.content
  return db.query(sql)
}

// 2. Template interpolation - CRITICAL
export async function templateSQLInjection(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  return db.execute(\`SELECT * FROM \${response.choices[0].message.content}\`)
}

// 3. Prisma $queryRaw - CRITICAL
export async function prismaRawQuery(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const completion = response.choices[0].message
  return prisma.$queryRaw(completion.content)
}

// 4. Sequelize literal - CRITICAL
export async function sequelizeQuery(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const generatedSql = response.choices[0].message.content
  return sequelize.query(generatedSql)
}

// 5. Knex raw - CRITICAL
export async function knexRawQuery(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const aiQuery = response.choices[0].message.content
  return knex.raw(aiQuery)
}
`,
        language: 'typescript',
        size: 1800,
      },
    },

    // ============================================================================
    // Test Group 4: DOM/XSS Sinks
    // ============================================================================
    {
      name: 'DOM XSS Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution', 'dangerous_function'],
      description: 'DOM/XSS sinks that MUST be detected',
      file: {
        path: 'src/components/ai/chat-renderer.tsx',
        content: `
import OpenAI from 'openai'

const openai = new OpenAI()

// 1. innerHTML with LLM content - HIGH
export async function renderAIContent(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  document.getElementById('content').innerHTML = response.choices[0].message.content
}

// 2. dangerouslySetInnerHTML - HIGH
export async function DangerousAIComponent({ prompt }) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const completion = response.choices[0].message
  return <div dangerouslySetInnerHTML={{ __html: completion.content }} />
}

// 3. document.write - HIGH
export async function documentWriteAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  document.write(response.choices[0].message.content)
}

// 4. outerHTML - HIGH
export async function outerHTMLAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const generated = response.choices[0].message.content
  document.getElementById('container').outerHTML = generated
}

// 5. insertAdjacentHTML - HIGH
export async function insertAdjacentAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  document.body.insertAdjacentHTML('beforeend', response.choices[0].message.content)
}
`,
        language: 'typescript',
        size: 1600,
      },
    },

    // ============================================================================
    // Test Group 5: Network/SSRF Sinks
    // ============================================================================
    {
      name: 'Network SSRF Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution'],
      description: 'Network/SSRF sinks that MUST be detected',
      file: {
        path: 'src/api/ai/network-handler.ts',
        content: `
import OpenAI from 'openai'
import axios from 'axios'
import got from 'got'

const openai = new OpenAI()

// 1. fetch() with LLM URL - CRITICAL
export async function fetchAIUrl(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  return fetch(response.choices[0].message.content)
}

// 2. axios with LLM URL - CRITICAL
export async function axiosAIGet(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const completion = response.choices[0].message
  return axios.get(completion.content)
}

// 3. axios.post with AI URL - CRITICAL
export async function axiosAIPost(prompt: string, data: any) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const aiUrl = response.choices[0].message.content
  return axios.post(aiUrl, data)
}

// 4. got with LLM URL - CRITICAL
export async function gotAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  return got(response.choices[0].message.content)
}

// 5. URL in options object - CRITICAL
export async function axiosConfigAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const completion = response.choices[0].message
  return axios({ url: completion.content, method: 'POST' })
}
`,
        language: 'typescript',
        size: 1500,
      },
    },

    // ============================================================================
    // Test Group 6: Redirect Sinks
    // ============================================================================
    {
      name: 'Redirect Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution'],
      description: 'Redirect sinks that MUST be detected',
      file: {
        path: 'src/api/ai/redirect-handler.ts',
        content: `
import OpenAI from 'openai'
import { redirect } from 'next/navigation'

const openai = new OpenAI()

// 1. Server redirect with LLM URL - HIGH
export async function handleAIRedirect(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  res.redirect(response.choices[0].message.content)
}

// 2. Client navigation - HIGH
export async function clientNavigateAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const completion = response.choices[0].message
  window.location.href = completion.content
}

// 3. location.assign - HIGH
export async function locationAssignAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const aiUrl = response.choices[0].message.content
  location.assign(aiUrl)
}

// 4. location.replace - HIGH
export async function locationReplaceAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const generatedUrl = response.choices[0].message.content
  location.replace(generatedUrl)
}

// 5. Next.js redirect - HIGH
export async function nextRedirectAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  redirect(response.choices[0].message.content)
}
`,
        language: 'typescript',
        size: 1400,
      },
    },

    // ============================================================================
    // Test Group 7: Header Injection Sinks
    // ============================================================================
    {
      name: 'Header Injection Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution'],
      description: 'Header injection sinks that MUST be detected',
      file: {
        path: 'src/api/ai/header-handler.ts',
        content: `
import OpenAI from 'openai'

const openai = new OpenAI()

// 1. setHeader with LLM value - HIGH
export async function setAIHeader(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  res.setHeader('X-Custom', response.choices[0].message.content)
}

// 2. Set-Cookie with LLM value - HIGH
export async function setCookieAI(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const completion = response.choices[0].message
  res.cookie('session', completion.content)
}

// 3. Header with potential CRLF - HIGH
export async function headerCRLF(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const aiUrl = response.choices[0].message.content
  res.set('Location', aiUrl)  // CRLF can inject headers
}

// 4. Content-Type manipulation - HIGH
export async function contentTypeAI(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  res.type(response.choices[0].message.content)
}
`,
        language: 'typescript',
        size: 1200,
      },
    },

    // ============================================================================
    // Test Group 8: File System Sinks
    // ============================================================================
    {
      name: 'File System Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution'],
      description: 'File system sinks that MUST be detected',
      file: {
        path: 'src/api/ai/file-handler.ts',
        content: `
import OpenAI from 'openai'
import fs from 'fs'
import path from 'path'

const openai = new OpenAI()

// 1. Path from LLM - readFile - CRITICAL
export async function readAIFile(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  return fs.readFileSync(response.choices[0].message.content, 'utf-8')
}

// 2. writeFile with LLM path - CRITICAL
export async function writeAIFile(prompt: string, data: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const completion = response.choices[0].message
  fs.writeFileSync(completion.content, data)
}

// 3. Path traversal risk - path.join with LLM - HIGH
export async function pathJoinAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const file = path.join('/base', response.choices[0].message.content)
  return fs.readFile(file, 'utf-8')
}

// 4. Unlink with LLM path - CRITICAL
export async function deleteAIFile(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const aiPath = response.choices[0].message.content
  fs.unlinkSync(aiPath)
}

// 5. rmSync with LLM path - CRITICAL
export async function recursiveDeleteAI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const generated = response.choices[0].message.content
  fs.rmSync(generated, { recursive: true })
}

// 6. mkdir with LLM path - HIGH
export async function createAIDir(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  fs.mkdirSync(response.choices[0].message.content)
}
`,
        language: 'typescript',
        size: 1800,
      },
    },

    // ============================================================================
    // Test Group 9: Dynamic Import Sinks
    // ============================================================================
    {
      name: 'Dynamic Import Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution'],
      description: 'Dynamic import sinks that MUST be detected',
      file: {
        path: 'src/api/ai/plugin-loader.ts',
        content: `
import OpenAI from 'openai'

const openai = new OpenAI()

// 1. import() with LLM module - CRITICAL
export async function loadAIModule(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const moduleName = response.choices[0].message.content
  return import(moduleName)
}

// 2. require() with LLM path - CRITICAL
export async function requireAIPlugin(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const completion = response.choices[0].message
  return require(completion.content)
}

// 3. require.resolve - HIGH
export async function resolveAIModule(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })
  const moduleName = response.choices[0].message.content
  return require.resolve(moduleName)
}
`,
        language: 'typescript',
        size: 900,
      },
    },

    // ============================================================================
    // Test Group 10: Python-Specific Sinks
    // ============================================================================
    {
      name: 'Python Sinks - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_unsafe_execution', 'dangerous_function'],
      description: 'Python-specific sinks that MUST be detected',
      file: {
        path: 'src/api/ai/python_executor.py',
        content: `
import openai
import pickle
import subprocess
import os
import sqlite3

client = openai.OpenAI()

# 1. eval with LLM code - CRITICAL
def eval_ai_code(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )
    code = response.choices[0].message.content
    return eval(code)

# 2. exec with LLM code - CRITICAL
def exec_ai_code(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )
    completion = response.choices[0].message
    exec(completion.content)

# 3. pickle.loads with LLM data - CRITICAL
def unpickle_ai_data(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )
    serialized = response.choices[0].message.content.encode()
    return pickle.loads(serialized)

# 4. subprocess with shell=True - CRITICAL
def subprocess_ai(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )
    ai_command = response.choices[0].message.content
    subprocess.run(ai_command, shell=True)

# 5. os.system - CRITICAL
def os_system_ai(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )
    generated_cmd = response.choices[0].message.content
    os.system(generated_cmd)

# 6. SQL with f-string - CRITICAL
def sql_fstring_ai(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )
    conn = sqlite3.connect("db.sqlite")
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM {response.choices[0].message.content}")
`,
        language: 'python',
        size: 1600,
      },
    },
  ],

  falseNegatives: [
    // ============================================================================
    // False Negatives Group 1: Safe Code Execution
    // ============================================================================
    {
      name: 'Safe Code Execution - False Negatives',
      expectFindings: false,
      description: 'Safe code execution patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'suspicious_package',
          maxCount: 2,
          reason: 'vm2 and isolated-vm are security sandbox packages',
        },
        {
          category: 'ai_pattern',
          maxCount: 2,
          reason: 'AI console.log debugging is info-level',
        },
      ],
      file: {
        path: 'src/api/ai/safe-code-executor.ts',
        content: `
import OpenAI from 'openai'
import { VM } from 'vm2'
import ivm from 'isolated-vm'
import * as acorn from 'acorn'

const openai = new OpenAI()

// 1. Sandboxed execution with vm2 - SAFE
export async function executeSandboxed(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const vm = new VM({
    timeout: 1000,
    sandbox: {}
  })
  return vm.run(response.choices[0].message.content)
}

// 2. Sandboxed execution with isolated-vm - SAFE
export async function executeIsolated(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const isolate = new ivm.Isolate({ memoryLimit: 128 })
  const context = await isolate.createContext()
  const script = await isolate.compileScript(response.choices[0].message.content)
  return script.run(context)
}

// 3. AST-parsed code (safe transformation) - SAFE
export async function parseCode(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // Only parsing the AST, not executing
  const ast = acorn.parse(response.choices[0].message.content, { ecmaVersion: 2020 })
  return analyzeAST(ast)
}

// 4. Static strings that contain 'eval' - SAFE
export function getDocumentation() {
  const docs = "Don't use eval() in production code"
  const warning = "The eval function is dangerous"
  return { docs, warning }
}

// 5. Display only - SAFE
export async function displayAICode(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  console.log('Generated code:', response.choices[0].message.content)
  return { code: response.choices[0].message.content }
}

function analyzeAST(ast: any) {
  return { type: ast.type, bodyLength: ast.body?.length }
}
`,
        language: 'typescript',
        size: 1800,
      },
    },

    // ============================================================================
    // False Negatives Group 2: Safe Shell Execution
    // ============================================================================
    {
      name: 'Safe Shell Execution - False Negatives',
      expectFindings: false,
      description: 'Safe shell execution patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'AI context visible but execution is safe',
        },
      ],
      file: {
        path: 'src/api/ai/safe-shell-executor.ts',
        content: `
import OpenAI from 'openai'
import { execFile } from 'child_process'

const openai = new OpenAI()

// 1. Hardcoded command with AI args (allowlisted) - SAFE
export async function safeExecFile(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const allowedArgs = ['--verbose', '--dry-run', '--help']
  const aiArg = response.choices[0].message.content.trim()

  if (allowedArgs.includes(aiArg)) {
    execFile('git', ['status', aiArg], (err, stdout) => console.log(stdout))
  }
}

// 2. Command palette display (not execution) - SAFE
export async function getCommandSuggestions(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const suggestions = response.choices[0].message.content.split('\\n')
  return suggestions.map(cmd => ({
    id: \`run-\${cmd}\`,
    label: cmd,
    description: 'Suggested command'
  }))
}

// 3. Sanitized command argument - SAFE
export async function sanitizedExec(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // Strict sanitization - only alphanumeric
  const sanitized = response.choices[0].message.content.replace(/[^a-z0-9]/gi, '')
  execFile('echo', [sanitized], (err, stdout) => console.log(stdout))
}
`,
        language: 'typescript',
        size: 1300,
      },
    },

    // ============================================================================
    // False Negatives Group 3: Safe SQL Queries
    // ============================================================================
    {
      name: 'Safe SQL Queries - False Negatives',
      expectFindings: false,
      description: 'Safe SQL query patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'dangerous_function',
          maxCount: 1,
          reason: 'Parameterized query with whitelist is safe',
        },
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'AI context visible but query is parameterized',
        },
      ],
      file: {
        path: 'src/api/ai/safe-sql-executor.ts',
        content: `
import OpenAI from 'openai'
import { PrismaClient } from '@prisma/client'

const openai = new OpenAI()
const prisma = new PrismaClient()

// 1. Parameterized query - SAFE
export async function safeParameterized(userId: string) {
  // AI not involved in query construction
  const result = await prisma.$queryRaw\`SELECT * FROM users WHERE id = \${userId}\`
  return result
}

// 2. Allowlisted columns with AI - SAFE
export async function safeAIColumns(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const allowedColumns = ['id', 'name', 'email', 'created_at']
  const requestedColumns = response.choices[0].message.content.split(',').map(c => c.trim())
  const safeColumns = requestedColumns.filter(c => allowedColumns.includes(c))

  if (safeColumns.length === 0) {
    throw new Error('No valid columns requested')
  }

  // Using validated columns with parameterized WHERE
  return db.query(\`SELECT \${safeColumns.join(', ')} FROM users WHERE id = $1\`, [userId])
}

// 3. ORM methods (not raw SQL) - SAFE
export async function safeORMQuery(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // ORM handles escaping
  const aiName = response.choices[0].message.content
  return prisma.user.findMany({
    where: { name: aiName }
  })
}

// 4. Schema-validated AI output - SAFE
export async function schemaValidatedQuery(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // Validate structure before use
  const schema = z.object({
    table: z.enum(['users', 'posts', 'comments']),
    column: z.enum(['id', 'name', 'email']),
    value: z.string().max(100)
  })

  const parsed = schema.parse(JSON.parse(response.choices[0].message.content))
  return db.query(\`SELECT * FROM \${parsed.table} WHERE \${parsed.column} = $1\`, [parsed.value])
}
`,
        language: 'typescript',
        size: 1700,
      },
    },

    // ============================================================================
    // False Negatives Group 4: Safe DOM/XSS Handling
    // ============================================================================
    {
      name: 'Safe DOM XSS Handling - False Negatives',
      expectFindings: false,
      description: 'Safe DOM/XSS handling patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 2,
          reason: 'AI context visible but output is sanitized',
        },
      ],
      file: {
        path: 'src/components/ai/safe-chat-renderer.tsx',
        content: `
import OpenAI from 'openai'
import DOMPurify from 'dompurify'
import ReactMarkdown from 'react-markdown'

const openai = new OpenAI()

// 1. DOMPurify sanitization - SAFE
export async function sanitizedInnerHTML(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const sanitized = DOMPurify.sanitize(response.choices[0].message.content)
  document.getElementById('content').innerHTML = sanitized
}

// 2. textContent (safe) - SAFE
export async function safeTextContent(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  document.getElementById('content').textContent = response.choices[0].message.content
}

// 3. React auto-escaping - SAFE
export async function SafeReactComponent({ prompt }) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // React auto-escapes this
  return <div>{response.choices[0].message.content}</div>
}

// 4. Markdown renderer with sanitization - SAFE
export async function SafeMarkdownComponent({ prompt }) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  return <ReactMarkdown>{response.choices[0].message.content}</ReactMarkdown>
}

// 5. Sanitized dangerouslySetInnerHTML - SAFE
export async function SafeDangerousComponent({ prompt }) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  return (
    <div
      dangerouslySetInnerHTML={{
        __html: DOMPurify.sanitize(response.choices[0].message.content)
      }}
    />
  )
}
`,
        language: 'typescript',
        size: 1700,
      },
    },

    // ============================================================================
    // False Negatives Group 5: Safe Network Requests
    // ============================================================================
    {
      name: 'Safe Network Requests - False Negatives',
      expectFindings: false,
      description: 'Safe network request patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'AI context visible but URL is validated',
        },
      ],
      file: {
        path: 'src/api/ai/safe-network-handler.ts',
        content: `
import OpenAI from 'openai'

const openai = new OpenAI()

// 1. URL validation with allowlist - SAFE
export async function validatedFetch(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiUrl = response.choices[0].message.content
  const allowedHosts = ['api.example.com', 'cdn.example.com']

  if (allowedHosts.includes(new URL(aiUrl).host)) {
    return fetch(aiUrl)
  }
  throw new Error('Invalid host')
}

// 2. Hardcoded URL with AI parameters - SAFE
export async function safeApiCall(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const query = encodeURIComponent(response.choices[0].message.content)
  return fetch(\`https://api.example.com/search?q=\${query}\`)
}

// 3. Internal API with validated path - SAFE
export async function validatedInternalAPI(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiPath = response.choices[0].message.content
  // Only allow alphanumeric paths
  const safePath = aiPath.replace(/[^a-z0-9]/gi, '')
  return fetch(\`/api/internal/\${safePath}\`)
}

// 4. Blocked private IPs - SAFE
export async function blockedPrivateIPs(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiUrl = response.choices[0].message.content
  const url = new URL(aiUrl)
  const blockedHosts = ['localhost', '127.0.0.1', '0.0.0.0']
  const privateIpPatterns = [/^10\\./, /^172\\.(1[6-9]|2[0-9]|3[0-1])\\./, /^192\\.168\\./]

  if (blockedHosts.includes(url.hostname) ||
      privateIpPatterns.some(p => p.test(url.hostname))) {
    throw new Error('Private IP blocked')
  }
  return fetch(aiUrl)
}
`,
        language: 'typescript',
        size: 1800,
      },
    },

    // ============================================================================
    // False Negatives Group 6: Safe Redirects
    // ============================================================================
    {
      name: 'Safe Redirects - False Negatives',
      expectFindings: false,
      description: 'Safe redirect patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'AI context visible but redirect is validated',
        },
      ],
      file: {
        path: 'src/api/ai/safe-redirect-handler.ts',
        content: `
import OpenAI from 'openai'

const openai = new OpenAI()

// 1. Relative URL validation - SAFE
export async function safeRelativeRedirect(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiUrl = response.choices[0].message.content
  if (aiUrl.startsWith('/') && !aiUrl.startsWith('//')) {
    res.redirect(aiUrl)
  } else {
    res.status(400).send('Invalid redirect URL')
  }
}

// 2. Same-origin check - SAFE
export async function sameOriginRedirect(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiUrl = response.choices[0].message.content
  const origin = window.location.origin
  const url = new URL(aiUrl, origin)

  if (url.origin === origin) {
    location.href = aiUrl
  }
}

// 3. Allowlisted domains - SAFE
export async function allowlistedRedirect(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiUrl = response.choices[0].message.content
  const safeDomains = ['example.com', 'trusted.org', 'partner.net']

  try {
    const url = new URL(aiUrl)
    if (safeDomains.includes(url.host)) {
      res.redirect(aiUrl)
    } else {
      res.status(400).send('Redirect blocked')
    }
  } catch {
    res.status(400).send('Invalid URL')
  }
}
`,
        language: 'typescript',
        size: 1400,
      },
    },

    // ============================================================================
    // False Negatives Group 7: Safe Header Setting
    // ============================================================================
    {
      name: 'Safe Header Setting - False Negatives',
      expectFindings: false,
      description: 'Safe header setting patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'AI context visible but headers are sanitized',
        },
      ],
      file: {
        path: 'src/api/ai/safe-header-handler.ts',
        content: `
import OpenAI from 'openai'
import crypto from 'crypto'

const openai = new OpenAI()

// 1. Sanitized header value - SAFE
export async function sanitizedHeader(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // Remove CRLF injection characters
  const safeValue = response.choices[0].message.content.replace(/[\\r\\n]/g, '')
  res.setHeader('X-Custom', safeValue)
}

// 2. Allowlisted content types - SAFE
export async function allowlistedContentType(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const allowedTypes = ['json', 'html', 'text', 'xml']
  const aiType = response.choices[0].message.content.trim().toLowerCase()

  if (allowedTypes.includes(aiType)) {
    res.type(aiType)
  } else {
    res.type('text')  // Default fallback
  }
}

// 3. Server-generated tokens - SAFE
export async function serverGeneratedCookie(req, res) {
  // Cookie value NOT from AI - generated server-side
  const sessionToken = crypto.randomUUID()
  res.cookie('session', sessionToken, {
    httpOnly: true,
    secure: true,
    sameSite: 'strict'
  })
}

// 4. Validated header name and value - SAFE
export async function validatedHeader(req, res, prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiValue = response.choices[0].message.content

  // Validate: only alphanumeric and safe characters
  if (/^[a-zA-Z0-9\\-_. ]+$/.test(aiValue) && aiValue.length <= 256) {
    res.setHeader('X-AI-Response', aiValue)
  }
}
`,
        language: 'typescript',
        size: 1600,
      },
    },

    // ============================================================================
    // False Negatives Group 8: Safe File Operations
    // ============================================================================
    {
      name: 'Safe File Operations - False Negatives',
      expectFindings: false,
      description: 'Safe file operation patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'AI context visible but paths are validated',
        },
      ],
      file: {
        path: 'src/api/ai/safe-file-handler.ts',
        content: `
import OpenAI from 'openai'
import fs from 'fs'
import path from 'path'

const openai = new OpenAI()
const SAFE_BASE_DIR = '/app/data/user-files'

// 1. Path validation - SAFE
export async function validatedFilePath(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiPath = response.choices[0].message.content
  const resolved = path.resolve(SAFE_BASE_DIR, aiPath)

  // Validate path is within safe directory
  if (!resolved.startsWith(SAFE_BASE_DIR)) {
    throw new Error('Invalid path - directory traversal attempt')
  }

  return fs.readFileSync(resolved, 'utf-8')
}

// 2. Allowlisted extensions - SAFE
export async function allowlistedExtensions(prompt: string, data: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiFile = response.choices[0].message.content
  const allowedExtensions = ['.txt', '.md', '.json', '.csv']
  const ext = path.extname(aiFile).toLowerCase()

  if (allowedExtensions.includes(ext)) {
    const safePath = path.join(SAFE_BASE_DIR, path.basename(aiFile))
    fs.writeFileSync(safePath, data)
  }
}

// 3. Internal file operations (not AI-controlled) - SAFE
export async function internalFileOps(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // File path is hardcoded, AI only provides content
  const filePath = '/app/logs/ai-responses.log'
  fs.appendFileSync(filePath, response.choices[0].message.content + '\\n')
}

// 4. Sanitized filename - SAFE
export async function sanitizedFilename(prompt: string, data: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // Remove all path traversal characters
  const aiFile = response.choices[0].message.content
  const sanitized = aiFile.replace(/[\\\\/\\x00-\\x1f]/g, '').replace(/\\.\\./g, '')

  if (sanitized.length > 0 && sanitized.length <= 255) {
    const safePath = path.join(SAFE_BASE_DIR, sanitized)
    fs.writeFileSync(safePath, data)
  }
}
`,
        language: 'typescript',
        size: 1900,
      },
    },

    // ============================================================================
    // False Negatives Group 9: Safe Dynamic Imports
    // ============================================================================
    {
      name: 'Safe Dynamic Imports - False Negatives',
      expectFindings: false,
      description: 'Safe dynamic import patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'AI context visible but imports are allowlisted',
        },
      ],
      file: {
        path: 'src/api/ai/safe-plugin-loader.ts',
        content: `
import OpenAI from 'openai'

const openai = new OpenAI()

// Plugin registry with allowlisted modules
const ALLOWED_PLUGINS = {
  'lodash': () => import('lodash'),
  'moment': () => import('moment'),
  'date-fns': () => import('date-fns'),
  'uuid': () => import('uuid'),
}

// 1. Allowlisted modules - SAFE
export async function loadAllowlistedPlugin(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const aiModule = response.choices[0].message.content.trim()
  const loader = ALLOWED_PLUGINS[aiModule]

  if (loader) {
    return loader()
  }
  throw new Error(\`Plugin "\${aiModule}" not in allowlist\`)
}

// 2. Hardcoded with AI config - SAFE
export async function configuredPlugin(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // AI only selects from predefined options
  const pluginName = response.choices[0].message.content.trim()

  // Sanitize - only alphanumeric
  const sanitized = pluginName.replace(/[^a-z0-9-]/gi, '')

  // Import from known safe directory
  const mod = await import(\`./plugins/\${sanitized}\`)
  return mod.default
}

// 3. Import map resolution - SAFE
export async function importMapPlugin(prompt: string) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  const importMap = {
    'math': './lib/math.js',
    'string': './lib/string.js',
    'array': './lib/array.js',
  }

  const aiKey = response.choices[0].message.content.trim()

  // AI key validated against map keys
  if (aiKey in importMap) {
    return require(importMap[aiKey])
  }
}
`,
        language: 'typescript',
        size: 1600,
      },
    },

    // ============================================================================
    // False Negatives Group 10: Safe Python Operations
    // ============================================================================
    {
      name: 'Safe Python Operations - False Negatives',
      expectFindings: false,
      description: 'Safe Python patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 1,
          reason: 'AI context visible but operations are safe',
        },
      ],
      file: {
        path: 'src/api/ai/safe_python_executor.py',
        content: `
import openai
import ast
import yaml
import subprocess
import sqlite3

client = openai.OpenAI()

# 1. Parameterized SQL - SAFE
def safe_parameterized_query(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )

    # Parameterized query - AI provides only values
    user_id = response.choices[0].message.content
    conn = sqlite3.connect("db.sqlite")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users WHERE id = ?", [user_id])
    return cursor.fetchall()

# 2. ast.literal_eval (safe subset) - SAFE
def safe_literal_eval(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )

    # ast.literal_eval only evaluates literals - no code execution
    data = ast.literal_eval(response.choices[0].message.content)
    return data

# 3. SafeLoader YAML - SAFE
def safe_yaml_load(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )

    content = response.choices[0].message.content
    # SafeLoader prevents code execution
    data = yaml.load(content, Loader=yaml.SafeLoader)
    return data

# 4. Subprocess with list args (no shell) - SAFE
def safe_subprocess(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )

    # shell=False with list args is safe
    # But we don't even use AI output in the command
    result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True)
    return result.stdout.decode()

# 5. Display only - SAFE
def display_ai_response(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )

    # Only printing, not executing
    print("AI Response:", response.choices[0].message.content)
    return {"response": response.choices[0].message.content}

# 6. Validated JSON parsing - SAFE
def safe_json_parse(prompt: str):
    import json
    from pydantic import BaseModel

    class SafeOutput(BaseModel):
        name: str
        value: int

    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )

    # Schema validation with Pydantic
    data = json.loads(response.choices[0].message.content)
    validated = SafeOutput(**data)
    return validated
`,
        language: 'python',
        size: 2100,
      },
    },
  ],
}
