// ═══════════════════════════════════════════════════════════
// Feedback & Modal Types — from CONTRACTS.md §3 & §6
// ═══════════════════════════════════════════════════════════

import type { PipelineStage } from "./pipeline.js";
import type { TestResults, DiffSummary } from "./task.js";

// ─── Modal Messages (postMessage API) ───

export type ModalMessage =
  | ModalResponse
  | ModalReady
  | ModalResize
  | ModalClose
  | ModalError;

export interface ModalReady {
  type: "factory_modal_ready";
  modalType: string;
  version: string;
}

export interface ModalResize {
  type: "factory_modal_resize";
  width?: number;
  height: number;
}

export interface ModalClose {
  type: "factory_modal_close";
  reason: "cancelled" | "timeout" | "error";
}

export interface ModalError {
  type: "factory_modal_error";
  error: string;
  details?: unknown;
}

export interface ModalResponse {
  type: "factory_modal_response";
  modalType: string;
  modalVersion: string;
  pipelineId: string;
  itemId: string;
  sessionId: string;
  timestamp: string;
  responseTimeMs: number;
  feedback: FeedbackPayload;
  meta: ModalMetrics;
}

// ─── Feedback Payload ───

export interface FeedbackPayload {
  decision?: DecisionFeedback;
  scores?: DimensionScore[];
  freeText?: FreeTextFeedback;
  comparison?: ComparisonFeedback;
  annotations?: Annotation[];
  confidence?: ConfidenceFeedback;
  estimation?: EstimationFeedback;
  batchDecisions?: BatchDecision[];
  retrospective?: RetrospectiveFeedback;
  ranking?: RankingFeedback;
  checklist?: ChecklistFeedback;
  temperature?: TemperatureFeedback;
  custom?: Record<string, unknown>;
}

// ─── The 8 Feedback Types ───

export interface DecisionFeedback {
  decision: "approved" | "rejected" | "needs_work" | "deferred" | "skipped";
  reason?: string;
  severity?: "minor" | "moderate" | "major" | "critical";
  blockers?: string[];
  suggestions?: string[];
  tags?: string[];
}

export type QualityDimension =
  | "code_quality"
  | "design_aesthetics"
  | "design_ux"
  | "test_coverage"
  | "documentation"
  | "architecture"
  | "error_handling"
  | "performance"
  | "security"
  | "creativity"
  | "completeness"
  | "naming"
  | "dx";

export interface DimensionScore {
  dimension: QualityDimension;
  score: number;
  weight?: number;
  comment?: string;
}

export interface FreeTextFeedback {
  liked?: string;
  disliked?: string;
  generalNotes?: string;
}

export interface ComparisonFeedback {
  preferred: "A" | "B" | "neither" | "both_good";
  reason?: string;
  preferenceStrength: "slight" | "moderate" | "strong" | "overwhelming";
  winningFactors?: string[];
  perDimension?: Array<{
    dimension: QualityDimension;
    winner: "A" | "B" | "tie";
  }>;
  timeOnA_ms?: number;
  timeOnB_ms?: number;
}

export interface Annotation {
  type: "praise" | "criticism" | "question" | "suggestion";
  target: {
    file?: string;
    lineStart?: number;
    lineEnd?: number;
    charStart?: number;
    charEnd?: number;
    selector?: string;
    region?: string;
  };
  text: string;
  severity?: "nit" | "minor" | "major" | "critical";
  category?: string;
}

export interface ConfidenceFeedback {
  confidencePercent: number;
  zone: "guess" | "educated_guess" | "confident" | "certain";
  wouldDelegateToAI: boolean;
  needsExpertReview: boolean;
  lowConfidenceReason?: string;
  isTrainingExample?: boolean;
}

export interface EstimationFeedback {
  estimate: number | "unknown" | "break";
  context?: string;
  hoveredValues?: number[];
}

export interface BatchDecision {
  itemId: string;
  decision: "approve" | "reject" | "love" | "skip";
  timeMs: number;
  flippedForDetails: boolean;
}

export interface RankingFeedback {
  finalRanking: string[];
  rankingChanges: number;
  lockedItems: string[];
  expandedItems: string[];
  perItemNotes?: Record<string, string>;
}

export interface RetrospectiveFeedback {
  start: RetrospectiveNote[];
  stop: RetrospectiveNote[];
  continue_: RetrospectiveNote[];
}

export interface RetrospectiveNote {
  text: string;
  priority?: "urgent" | "important" | "idea";
}

export interface ChecklistFeedback {
  checks: Record<string, boolean>;
  notes: Record<string, string>;
  checkOrder: string[];
  allClear: boolean;
  completionRate: number;
}

export interface TemperatureFeedback {
  temperature: number;
  zone: "freezing" | "cold" | "lukewarm" | "warm" | "hot" | "blazing";
  drivers: string[];
  dragJourney: number[];
}

// ─── Behavioral Metrics ───

export interface ModalMetrics {
  timeToFirstInteractionMs: number;
  timeToDecisionMs: number;
  fieldsModified: string[];
  scrollDepth?: number;
  revisits: number;
  totalInteractions: number;
  viewportSize: { width: number; height: number };
  deviceType: "desktop" | "mobile";
  hoverJourney?: Array<{ target: string; durationMs: number }>;
  hesitationPoints?: Array<{ target: string; durationMs: number }>;
}

// ─── Full Feedback Event (stored) ───

export interface FeedbackEvent {
  id: string;
  timestamp: string;
  sessionId: string;
  modalType: string;
  modalVersion: string;
  workProduct: WorkProductRef;
  pipelineId: string | null;
  pipelineStage: PipelineStage | null;
  mcpServerType?: string;
  feedback: FeedbackPayload;
  meta: ModalMetrics & EnrichedMeta;
}

export interface WorkProductRef {
  type: "mcp_server" | "code_module" | "design" | "test_suite" | "documentation" | "pipeline_config";
  id: string;
  version: string;
  path?: string;
  summary: string;
  bubaConfidence: number;
  bubaScorePrediction?: number;
  generationContext: {
    promptHash: string;
    memorySnapshot: string[];
    modelUsed: string;
    generationTimeMs: number;
    iterationCount: number;
  };
}

export type TimeOfDay = "morning" | "afternoon" | "evening" | "night";

export interface EnrichedMeta {
  timeOfDay: TimeOfDay;
  dayOfWeek: string;
  sessionFatigue: number;
  concurrentModals: number;
  extractedThemes?: string[];
  sentiment?: number;
  actionableItems?: string[];
  predictionDelta?: number;
}

// ─── Enriched Event ───

export interface EnrichedFeedbackEvent extends FeedbackEvent {
  _enriched: true;
  _themes?: string[];
  _sentiment?: number;
  _actionableItems?: string[];
  _predictionDelta?: number;
  _pipelineContext?: {
    stage: PipelineStage;
    stagesCompleted: number;
    totalDuration: number;
  };
}

// ─── Modal Context (host → modal) ───

export interface FactoryModalContext {
  modalType: string;
  modalVersion: string;
  sessionId: string;
  pipelineId: string;
  pipelineName: string;
  itemId: string;
  itemName: string;
  deliverablePreview?: string;
  deliverableContent?: string;
  contentBefore?: string;
  contentAfter?: string;
  testResults?: TestResults;
  diffSummary?: DiffSummary;
  metrics?: Record<string, number>;
  items?: ModalItem[];
  dimensions?: ModalDimension[];
  checklistItems?: ChecklistItem[];
  estimationQuestion?: string;
  persona?: ModalPersona;
  timerSeconds?: number;
  theme: "dark" | "light";
  accentColor: string;
}

export interface ModalItem {
  id: string;
  name: string;
  preview: string;
  content?: string;
  metadata?: Record<string, unknown>;
}

export interface ModalDimension {
  id: string;
  name: string;
  description?: string;
  weight: number;
}

export interface ChecklistItem {
  id: string;
  label: string;
  description?: string;
  aiAssessment?: string;
  aiPasses?: boolean;
}

export interface ModalPersona {
  name: string;
  role: string;
  context: string;
  avatarEmoji: string;
}

// ─── Modal Registration ───

export type ModalUseCase =
  | "binary_decision"
  | "batch_review"
  | "multi_dimensional"
  | "comparison"
  | "subjective"
  | "high_stakes"
  | "annotation"
  | "estimation"
  | "triage"
  | "retrospective"
  | "verification";

export interface ModalRegistration {
  id: string;
  name: string;
  description: string;
  version: string;
  suitableFor: ModalUseCase[];
  requiredContext: string[];
  optionalContext: string[];
  outputSchema: {
    feedbackTypes: string[];
    capturesMetrics: string[];
  };
  display: {
    preferredType: "inline" | "sidecar";
    minWidth: number;
    minHeight: number;
    supportsDarkMode: boolean;
    supportsMobile: boolean;
  };
}

// ─── Learning System Types (§6) ───

export interface FeedbackStats {
  totalEvents: number;
  last30Days: {
    approvalRate: number;
    avgQualityScore: number;
    avgTimeToDecisionMs: number;
    predictionAccuracy: number;
    autoApproveRate: number;
    feedbackVolume: number;
  };
  trends: {
    approvalRate: "improving" | "stable" | "declining";
    qualityScore: "improving" | "stable" | "declining";
    decisionSpeed: "improving" | "stable" | "declining";
  };
  activeRules: number;
  autonomyLevels: Record<string, number>;
}

export interface CalibrationCurve {
  lastUpdated: string;
  totalDataPoints: number;
  buckets: CalibrationBucket[];
  expectedCalibrationError: number;
}

export interface CalibrationBucket {
  rawConfidenceLow: number;
  rawConfidenceHigh: number;
  avgPredictedConfidence: number;
  avgActualApprovalRate: number;
  sampleCount: number;
  correctionDelta: number;
  calibratedConfidence: number;
}
