/**
 * Pre-Answered Questions — "Questions Your Agent Will Never Ask"
 * 
 * Hard-codes the answers to critical safety and policy questions
 * that an AI agent will never think to ask on its own.
 * 
 * Reference: Nate B Jones — "5 Management Skills for AI Agent Builders"
 * Skill #5: Questions Your Agent Will Never Ask
 */

export interface PreAnsweredQuestion {
  id: string;
  question: string;
  answer: string;
  enforcementLevel: 'hard_block' | 'soft_warn' | 'log_only';
  category: 'data_safety' | 'security' | 'compliance' | 'operations' | 'ethics';
}

/**
 * The canonical list of pre-answered questions.
 * These are injected into agent system prompts and enforced at runtime.
 */
export const PRE_ANSWERED_QUESTIONS: PreAnsweredQuestion[] = [
  {
    id: 'paq-001',
    question: 'Is it safe to delete this data?',
    answer: 'No. Create a save-point backup first, then soft-delete only. ' +
      'Hard deletes require explicit human approval via the Human Gate.',
    enforcementLevel: 'hard_block',
    category: 'data_safety',
  },
  {
    id: 'paq-002',
    question: 'Should I log this customer email or PII?',
    answer: 'Hash all PII before writing to logs. Store raw PII only in ' +
      'encrypted database fields. Never log passwords, SSNs, or payment info.',
    enforcementLevel: 'hard_block',
    category: 'compliance',
  },
  {
    id: 'paq-003',
    question: 'Can I access production directly?',
    answer: 'No. All changes go through the staging pipeline first. ' +
      'Production writes require Human Gate approval.',
    enforcementLevel: 'hard_block',
    category: 'security',
  },
  {
    id: 'paq-004',
    question: 'Should I retry this failed operation?',
    answer: 'Only for transient failures (network timeout, rate limit). ' +
      'For logic errors, data integrity errors, or auth failures: HALT and escalate.',
    enforcementLevel: 'soft_warn',
    category: 'operations',
  },
  {
    id: 'paq-005',
    question: 'Is this user authorized for this action?',
    answer: 'Always verify. Check RBAC roles, validate session, enforce ' +
      'rate limits. Never assume authorization based on identity alone.',
    enforcementLevel: 'hard_block',
    category: 'security',
  },
  {
    id: 'paq-006',
    question: 'Can I modify my own rules or configuration?',
    answer: 'ABSOLUTELY NOT. Standing orders and system rules are immutable ' +
      'at runtime. Only human operators can modify rule files.',
    enforcementLevel: 'hard_block',
    category: 'security',
  },
  {
    id: 'paq-007',
    question: 'Should I expose this API key or secret in the response?',
    answer: 'Never. Secrets are server-side only. Return masked versions ' +
      '(e.g., sk_***abc) in responses. Log access but not values.',
    enforcementLevel: 'hard_block',
    category: 'security',
  },
  {
    id: 'paq-008',
    question: 'Can I run this task that touches multiple systems at once?',
    answer: 'Break it into single-system tasks. Each task targets one ' +
      'endpoint, one table, or one component. Execute sequentially with ' +
      'verification between steps.',
    enforcementLevel: 'soft_warn',
    category: 'operations',
  },
  {
    id: 'paq-009',
    question: 'What should I do if context is getting large?',
    answer: 'Checkpoint immediately. Summarize completed work, save state, ' +
      'and start a fresh session with only the summary + standing orders.',
    enforcementLevel: 'soft_warn',
    category: 'operations',
  },
  {
    id: 'paq-010',
    question: 'Can I send customer data to external APIs?',
    answer: 'Only to approved integrations listed in the integration registry. ' +
      'All external calls must be logged in the audit trail. PII must be ' +
      'anonymized before transmission unless the integration is HIPAA/SOC2 compliant.',
    enforcementLevel: 'hard_block',
    category: 'compliance',
  },
  {
    id: 'paq-011',
    question: 'Should I auto-approve this high-risk change?',
    answer: 'Never. Risk scores > 60 always require human approval via the ' +
      'Human Gate. Do not attempt to bypass or reduce risk scores.',
    enforcementLevel: 'hard_block',
    category: 'data_safety',
  },
  {
    id: 'paq-012',
    question: 'Can I deploy directly to production?',
    answer: 'No. All deployments go through staging first, then require ' +
      'explicit promotion approval. Emergency hotfixes still need at least ' +
      'one human reviewer.',
    enforcementLevel: 'hard_block',
    category: 'operations',
  },
];

/**
 * Get the pre-answered questions as a system prompt section.
 * This is appended to every agent's system prompt.
 */
export function getPreAnsweredQuestionsPrompt(): string {
  const hardBlocks = PRE_ANSWERED_QUESTIONS.filter(
    q => q.enforcementLevel === 'hard_block'
  );

  return [
    '',
    '=== PRE-ANSWERED SAFETY QUESTIONS ===',
    'These answers are FINAL. Do not override them.',
    '',
    ...hardBlocks.map(
      q => `Q: "${q.question}"\n   A: ${q.answer}\n`
    ),
    '=== END PRE-ANSWERED QUESTIONS ===',
  ].join('\n');
}

/**
 * Check if an operation matches any pre-answered question
 * and return the enforcement action.
 */
export function checkPreAnsweredRules(operation: {
  type: string;
  description: string;
  involvesPII?: boolean;
  isProduction?: boolean;
  isExternalAPI?: boolean;
  riskScore?: number;
}): {
  blocked: boolean;
  warnings: string[];
  applicableRules: PreAnsweredQuestion[];
} {
  const applicableRules: PreAnsweredQuestion[] = [];
  const warnings: string[] = [];
  let blocked = false;

  // Check PII handling
  if (operation.involvesPII) {
    const rule = PRE_ANSWERED_QUESTIONS.find(q => q.id === 'paq-002')!;
    applicableRules.push(rule);
    warnings.push(`[${rule.id}] ${rule.answer}`);
  }

  // Check production access
  if (operation.isProduction) {
    const rule = PRE_ANSWERED_QUESTIONS.find(q => q.id === 'paq-003')!;
    applicableRules.push(rule);
    blocked = true;
    warnings.push(`[${rule.id}] BLOCKED: ${rule.answer}`);
  }

  // Check external API calls
  if (operation.isExternalAPI) {
    const rule = PRE_ANSWERED_QUESTIONS.find(q => q.id === 'paq-010')!;
    applicableRules.push(rule);
    warnings.push(`[${rule.id}] ${rule.answer}`);
  }

  // Check high-risk auto-approval
  if (operation.riskScore && operation.riskScore > 60) {
    const rule = PRE_ANSWERED_QUESTIONS.find(q => q.id === 'paq-011')!;
    applicableRules.push(rule);
    blocked = true;
    warnings.push(`[${rule.id}] BLOCKED: ${rule.answer}`);
  }

  // Check delete operations
  if (operation.type === 'delete' || operation.type === 'bulk_delete') {
    const rule = PRE_ANSWERED_QUESTIONS.find(q => q.id === 'paq-001')!;
    applicableRules.push(rule);
    warnings.push(`[${rule.id}] ${rule.answer}`);
  }

  return { blocked, warnings, applicableRules };
}
