/**
 * Scan Depth Profile Validation
 * Validates that local/verified/deep modes work correctly
 */

import { runLayer1Scan } from '../../detect/secrets'
import { runLayer2Scan } from '../../detect/structural'
import { getTierForCategory, isTierVisibleAtDepth, formatTierStats, computeTierStats } from '../../tiers'
import type { ScanFile, ScanDepth, Vulnerability } from '../../shared/types'

// Test fixture with various vulnerability types
const testFile: ScanFile = {
  path: 'src/api/test-route.ts',
  content: `
// This file contains patterns from different tiers for testing

// Tier A (core): Hardcoded secret - always visible
const API_KEY = "sk_live_abc123def456ghi789jkl012mno345pqr678"

// Tier A (core): Dangerous function - always visible
export function executeQuery(input: string) {
  return db.query(\`SELECT * FROM users WHERE id = '\${input}'\`)
}

// Tier B (ai_assisted): AI pattern - needs validation in validated/deep modes
// TODO: This was AI generated and needs review
const placeholder = "implementation goes here"

// Tier C (experimental): Should always be hidden
const suspiciousVar = "possibly_risky"

export async function GET() {
  // Missing auth pattern (Tier B)
  const data = await db.query('SELECT * FROM data')
  return NextResponse.json(data)
}
`,
  language: 'typescript',
  size: 700,
}

// Helper to classify findings by tier
function classifyFindings(findings: Vulnerability[]): {
  core: Vulnerability[]
  ai_assisted: Vulnerability[]
  experimental: Vulnerability[]
} {
  const result: {
    core: Vulnerability[]
    ai_assisted: Vulnerability[]
    experimental: Vulnerability[]
  } = { core: [], ai_assisted: [], experimental: [] }

  for (const f of findings) {
    const tier = getTierForCategory(f.category, f.layer)
    result[tier].push(f)
  }

  return result
}

async function runValidation() {
  console.log('=' .repeat(70))
  console.log('SCAN DEPTH PROFILE VALIDATION')
  console.log('=' .repeat(70))

  // Run scans
  console.log('\n📋 Running Layer 1 + Layer 2 scans...')
  const startScan = Date.now()
  const l1 = await runLayer1Scan([testFile])
  const l2 = await runLayer2Scan([testFile])
  const scanDuration = Date.now() - startScan

  const allFindings = [...l1.vulnerabilities, ...l2.vulnerabilities]
  const classified = classifyFindings(allFindings)

  console.log(`\n⏱️  Scan duration: ${scanDuration}ms`)
  console.log(`\n📊 Total findings: ${allFindings.length}`)
  console.log(`   Tier A (core): ${classified.core.length}`)
  console.log(`   Tier B (ai_assisted): ${classified.ai_assisted.length}`)
  console.log(`   Tier C (experimental): ${classified.experimental.length}`)

  // Show tier stats
  const tierStats = computeTierStats(
    allFindings.map(v => ({ category: v.category, layer: v.layer }))
  )
  console.log(`\n📈 ${formatTierStats(tierStats)}`)

  // Test each depth mode
  const depths: ScanDepth[] = ['local', 'verified', 'deep']

  console.log('\n' + '-'.repeat(70))
  console.log('DEPTH MODE BEHAVIOR')
  console.log('-'.repeat(70))

  for (const depth of depths) {
    console.log(`\n🎚️  ${depth.toUpperCase()} mode:`)

    const coreVisible = isTierVisibleAtDepth('core', depth)
    const aiAssistedVisible = isTierVisibleAtDepth('ai_assisted', depth)
    const experimentalVisible = isTierVisibleAtDepth('experimental', depth)

    console.log(`   Tier A (core): ${coreVisible ? '✅ VISIBLE' : '❌ hidden'}`)
    console.log(`   Tier B (ai_assisted): ${aiAssistedVisible ? '✅ VISIBLE (via AI validation)' : '❌ hidden'}`)
    console.log(`   Tier C (experimental): ${experimentalVisible ? '✅ VISIBLE' : '❌ hidden'}`)

    // Calculate what would be surfaced
    let surfaced = 0
    let validated = 0
    let hidden = 0

    if (coreVisible) surfaced += classified.core.length
    else hidden += classified.core.length

    if (aiAssistedVisible) validated += classified.ai_assisted.length
    else hidden += classified.ai_assisted.length

    hidden += classified.experimental.length // Always hidden

    console.log(`   → ${surfaced} surfaced directly, ${validated} to AI validation, ${hidden} hidden`)

    // Show expected behavior
    switch (depth) {
      case 'local':
        console.log(`   → AI validation: SKIPPED`)
        console.log(`   → Layer 3: SKIPPED`)
        console.log(`   → Target time: <5s for typical PRs`)
        break
      case 'verified':
        console.log(`   → AI validation: ENABLED`)
        console.log(`   → Layer 3: SKIPPED`)
        console.log(`   → Target time: <15s with <10 AI calls`)
        break
      case 'deep':
        console.log(`   → AI validation: ENABLED`)
        console.log(`   → Layer 3: ENABLED`)
        console.log(`   → Target time: Thorough analysis`)
        break
    }
  }

  // Performance test
  console.log('\n' + '-'.repeat(70))
  console.log('PERFORMANCE VALIDATION')
  console.log('-'.repeat(70))

  // Test with 10 files
  const files10 = Array.from({ length: 10 }, (_, i) => ({
    ...testFile,
    path: `src/api/test-route-${i}.ts`,
  }))

  console.log('\n⏱️  Testing with 10 files (local mode, no AI)...')
  const start10 = Date.now()
  await runLayer1Scan(files10)
  await runLayer2Scan(files10)
  const duration10 = Date.now() - start10
  console.log(`   Duration: ${duration10}ms`)
  console.log(`   ${duration10 < 5000 ? '✅' : '❌'} Target: <5000ms`)

  // Test with 50 files
  const files50 = Array.from({ length: 50 }, (_, i) => ({
    ...testFile,
    path: `src/api/test-route-${i}.ts`,
  }))

  console.log('\n⏱️  Testing with 50 files (local mode, no AI)...')
  const start50 = Date.now()
  await runLayer1Scan(files50)
  await runLayer2Scan(files50)
  const duration50 = Date.now() - start50
  console.log(`   Duration: ${duration50}ms`)
  console.log(`   ${duration50 < 10000 ? '✅' : '❌'} Target: <10000ms`)
  console.log(`   Rate: ${Math.round(50000 / duration50)} files/sec`)

  // Summary
  console.log('\n' + '=' .repeat(70))
  console.log('VALIDATION SUMMARY')
  console.log('=' .repeat(70))

  const allPassed =
    classified.core.length > 0 &&  // Should have some Tier A findings
    duration10 < 5000 &&           // 10 files under 5s
    duration50 < 10000             // 50 files under 10s

  if (allPassed) {
    console.log('\n✅ ALL DEPTH PROFILE VALIDATIONS PASSED')
  } else {
    console.log('\n❌ SOME VALIDATIONS FAILED')
  }

  console.log('\nWorkflow Profile Recommendations:')
  console.log('┌─────────────────┬──────────────┬────────────────────────────────────┐')
  console.log('│ Workflow        │ Default Depth│ Rationale                          │')
  console.log('├─────────────────┼──────────────┼────────────────────────────────────┤')
  console.log('│ GitHub PR       │ local        │ Fast feedback, high-signal findings│')
  console.log('│ VS Code         │ verified     │ Interactive, balance depth + speed │')
  console.log('│ CLI (default)   │ local        │ Fast local scans                   │')
  console.log('│ CLI --deep      │ deep         │ Thorough analysis when requested   │')
  console.log('│ Onboarding      │ deep         │ Full picture on first scan         │')
  console.log('└─────────────────┴──────────────┴────────────────────────────────────┘')

  console.log('\n')
}

runValidation().catch(console.error)
