/**
 * GFS Supervision Framework — Central Export
 * 
 * Implements the 5 Core Supervision Skills for AI Agent Management:
 *   1. Save Points (save-points.ts)
 *   2. Context Hygiene / Fresh Starts (context-hygiene.ts)
 *   3. Standing Orders (standing-orders.ts + STANDING_ORDERS.md)
 *   4. Blast Radius / Small Bets (blast-radius.ts)
 *   5. Pre-Answered Questions (pre-answered-questions.ts)
 * 
 * Reference: "Claude Code Wiped 2.5 Years of Data" — Nate B Jones
 * https://www.youtube.com/watch?v=8lwnJZy4cO0
 */

import { createSavePoint, restoreFromSavePoint } from './save-points';
import type { SavePoint, SavePointResult } from './save-points';
import { loadStandingOrders, getStandingOrdersPrompt, validateAction, resetStandingOrdersCache } from './standing-orders';
import type { StandingOrders, StandingRule } from './standing-orders';
import { checkBlastRadius, createBatchPlan } from './blast-radius';
import type { BlastRadiusConfig, ScopeCheck } from './blast-radius';
import { checkContextHealth, generateSessionSummary, estimateTokens } from './context-hygiene';
import type { SessionState, ContextCheck } from './context-hygiene';
import { PRE_ANSWERED_QUESTIONS, getPreAnsweredQuestionsPrompt, checkPreAnsweredRules } from './pre-answered-questions';
import type { PreAnsweredQuestion } from './pre-answered-questions';

// Re-export everything
export { createSavePoint, restoreFromSavePoint };
export type { SavePoint, SavePointResult };
export { loadStandingOrders, getStandingOrdersPrompt, validateAction, resetStandingOrdersCache };
export type { StandingOrders, StandingRule };
export { checkBlastRadius, createBatchPlan };
export type { BlastRadiusConfig, ScopeCheck };
export { checkContextHealth, generateSessionSummary, estimateTokens };
export type { SessionState, ContextCheck };
export { PRE_ANSWERED_QUESTIONS, getPreAnsweredQuestionsPrompt, checkPreAnsweredRules };
export type { PreAnsweredQuestion };

/**
 * Master supervision check — runs all 5 safety layers.
 * Call this before any agent operation.
 */
export function runSupervisionCheck(context: {
  operation: {
    type: string;
    entityType: string;
    entityCount: number;
    description: string;
    affectedComponents?: string[];
    fileChanges?: number;
  };
  session: {
    sessionId: string;
    agentId: string;
    startedAt: Date;
    tokenCount: number;
    taskCount: number;
    lastCheckpointAt: Date | null;
    checkpointCount: number;
  };
  flags?: {
    involvesPII?: boolean;
    isProduction?: boolean;
    isExternalAPI?: boolean;
    riskScore?: number;
    hasSavePoint?: boolean;
    hasHumanApproval?: boolean;
    touchesAuth?: boolean;
  };
}): {
  proceed: boolean;
  actions: string[];
  violations: string[];
  warnings: string[];
} {
  const actions: string[] = [];
  const allViolations: string[] = [];
  const allWarnings: string[] = [];

  // 1. Context health check
  const contextCheck = checkContextHealth(context.session);
  if (!contextCheck.healthy) {
    actions.push(contextCheck.action);
    if (contextCheck.reason) allWarnings.push(contextCheck.reason);
  }

  // 2. Blast radius check
  const scopeCheck = checkBlastRadius(context.operation);
  if (!scopeCheck.allowed) {
    allViolations.push(...scopeCheck.violations);
  }
  if (scopeCheck.recommendations.length > 0) {
    allWarnings.push(...scopeCheck.recommendations);
  }

  // 3. Standing orders validation
  const standingCheck = validateAction({
    type: context.operation.type as 'create' | 'update' | 'delete' | 'bulk_delete' | 'schema_change' | 'read',
    entityCount: context.operation.entityCount,
    hasSavePoint: context.flags?.hasSavePoint,
    hasHumanApproval: context.flags?.hasHumanApproval,
    touchesAuth: context.flags?.touchesAuth,
    touchesPII: context.flags?.involvesPII,
  });
  if (!standingCheck.allowed) {
    allViolations.push(...standingCheck.violations);
  }

  // 4. Pre-answered questions check
  const paqCheck = checkPreAnsweredRules({
    type: context.operation.type,
    description: context.operation.description,
    involvesPII: context.flags?.involvesPII,
    isProduction: context.flags?.isProduction,
    isExternalAPI: context.flags?.isExternalAPI,
    riskScore: context.flags?.riskScore,
  });
  if (paqCheck.blocked) {
    allViolations.push(...paqCheck.warnings.filter((w: string) => w.includes('BLOCKED')));
  }
  allWarnings.push(...paqCheck.warnings.filter((w: string) => !w.includes('BLOCKED')));

  const proceed = allViolations.length === 0 &&
    !actions.includes('force_restart');

  return {
    proceed,
    actions,
    violations: allViolations,
    warnings: allWarnings,
  };
}
