/**
 * Claude Code IDE Integration
 * Generates CLAUDE.md section format
 */

import type { ScanResult, Vulnerability, VulnerabilityCategory } from '../../../shared/types'
import { sortBySeverity } from '../grouping'

/** Start marker for Oculum section in CLAUDE.md */
export const OCULUM_SECTION_START = '<!-- OCULUM_SECURITY_START -->'

/** End marker for Oculum section in CLAUDE.md */
export const OCULUM_SECTION_END = '<!-- OCULUM_SECURITY_END -->'

/**
 * Get "ALWAYS" rule for a category
 */
function getAlwaysRule(category: VulnerabilityCategory): string | null {
  const rules: Partial<Record<VulnerabilityCategory, string>> = {
    sql_injection: 'Use parameterized queries for all database operations',
    xss: 'Escape or sanitize user input before rendering in HTML',
    hardcoded_secret: 'Use environment variables for secrets and API keys',
    high_entropy_string: 'Store credentials in secure vaults, not in code',
    missing_auth: 'Add authentication middleware to API endpoints',
    dangerous_function: 'Avoid eval() and exec() - use safe alternatives',
    command_injection: 'Sanitize all input passed to shell commands',
    data_exposure: 'Never log sensitive data or expose it in responses',
    weak_crypto: 'Use modern cryptographic algorithms (SHA-256+, AES-256)',
    ai_prompt_injection: 'Sanitize user input before including in prompts',
    ai_unsafe_execution: 'Validate AI-generated code before execution',
  }

  return rules[category] || null
}

/**
 * Format scan result as CLAUDE.md section
 *
 * @param result - The scan result to format
 * @returns Markdown string with markers for CLAUDE.md
 */
export function formatClaudeCodeSection(result: ScanResult): string {
  const { vulnerabilities, timestamp } = result

  // Sort by severity
  const sorted = sortBySeverity(vulnerabilities)

  let md = ''

  // Section markers
  md += `${OCULUM_SECTION_START}\n`
  md += `## Security Issues (Auto-Generated)\n\n`
  md += `> Last scan: ${timestamp}\n\n`

  // No findings case
  if (vulnerabilities.length === 0) {
    md += `No security issues detected.\n\n`
    md += `Run \`oculum scan\` to scan for vulnerabilities.\n`
    md += `${OCULUM_SECTION_END}\n`
    return md
  }

  // Summary
  const { severityCounts, hasBlockingIssues } = result
  if (hasBlockingIssues) {
    md += `**BLOCKING ISSUES:** ${severityCounts.critical + severityCounts.high} issues must be fixed.\n\n`
  }

  // DO NOT section - list findings
  md += `**DO NOT** ignore these findings:\n\n`

  let count = 0
  for (const vuln of sorted.slice(0, 10)) {
    count++
    const severityLabel =
      vuln.severity === 'critical' ? 'CRITICAL' :
      vuln.severity === 'high' ? 'HIGH' :
      vuln.severity.toUpperCase()

    md += `${count}. **${vuln.title}** [${severityLabel}] in \`${vuln.filePath}:${vuln.lineNumber}\`\n`
  }

  if (sorted.length > 10) {
    md += `\n... and ${sorted.length - 10} more issues.\n`
  }
  md += '\n'

  // ALWAYS section - best practices
  const alwaysRules = new Set<string>()
  for (const vuln of vulnerabilities) {
    const rule = getAlwaysRule(vuln.category)
    if (rule) {
      alwaysRules.add(rule)
    }
  }

  if (alwaysRules.size > 0) {
    md += `**ALWAYS:**\n`
    for (const rule of alwaysRules) {
      md += `- ${rule}\n`
    }
    md += '\n'
  }

  // Verification instructions
  md += `Run \`oculum scan\` to verify fixes.\n`
  md += `${OCULUM_SECTION_END}\n`

  return md
}
