/**
 * Compliance Training Engine Types
 * TypeScript definitions for the Training Matrix, Assignments, Quiz, and Content
 */

// =============================================================================
// ENUMS / CONSTANTS
// =============================================================================

export type RegulationArea = 'dsgvo' | 'nis2' | 'iso27001' | 'ai_act' | 'geschgehg' | 'hinschg'
export type FrequencyType = 'onboarding' | 'annual' | 'event_trigger' | 'micro'
export type AssignmentStatus = 'pending' | 'in_progress' | 'completed' | 'overdue' | 'expired'
export type TriggerType = 'onboarding' | 'annual' | 'event' | 'manual'
export type Difficulty = 'easy' | 'medium' | 'hard'
export type AuditAction = 'assigned' | 'started' | 'completed' | 'quiz_submitted' | 'escalated' | 'certificate_issued' | 'content_generated'

export const REGULATION_LABELS: Record<RegulationArea, string> = {
  dsgvo: 'DSGVO',
  nis2: 'NIS-2',
  iso27001: 'ISO 27001',
  ai_act: 'AI Act',
  geschgehg: 'GeschGehG',
  hinschg: 'HinSchG',
}

export const REGULATION_COLORS: Record<RegulationArea, { bg: string; text: string; border: string }> = {
  dsgvo: { bg: 'bg-blue-100', text: 'text-blue-700', border: 'border-blue-300' },
  nis2: { bg: 'bg-purple-100', text: 'text-purple-700', border: 'border-purple-300' },
  iso27001: { bg: 'bg-green-100', text: 'text-green-700', border: 'border-green-300' },
  ai_act: { bg: 'bg-orange-100', text: 'text-orange-700', border: 'border-orange-300' },
  geschgehg: { bg: 'bg-yellow-100', text: 'text-yellow-700', border: 'border-yellow-300' },
  hinschg: { bg: 'bg-red-100', text: 'text-red-700', border: 'border-red-300' },
}

export const FREQUENCY_LABELS: Record<FrequencyType, string> = {
  onboarding: 'Onboarding',
  annual: 'Jaehrlich',
  event_trigger: 'Ereignisbasiert',
  micro: 'Micro-Training',
}

export const STATUS_LABELS: Record<AssignmentStatus, string> = {
  pending: 'Ausstehend',
  in_progress: 'In Bearbeitung',
  completed: 'Abgeschlossen',
  overdue: 'Ueberfaellig',
  expired: 'Abgelaufen',
}

export const STATUS_COLORS: Record<AssignmentStatus, { bg: string; text: string }> = {
  pending: { bg: 'bg-gray-100', text: 'text-gray-700' },
  in_progress: { bg: 'bg-blue-100', text: 'text-blue-700' },
  completed: { bg: 'bg-green-100', text: 'text-green-700' },
  overdue: { bg: 'bg-red-100', text: 'text-red-700' },
  expired: { bg: 'bg-gray-200', text: 'text-gray-500' },
}

export const ROLE_LABELS: Record<string, string> = {
  R1: 'Geschaeftsfuehrung',
  R2: 'IT-Leitung',
  R3: 'Datenschutzbeauftragter',
  R4: 'Informationssicherheitsbeauftragter',
  R5: 'HR / Personal',
  R6: 'Einkauf / Beschaffung',
  R7: 'Fachabteilung',
  R8: 'IT-Administration',
  R9: 'Alle Mitarbeiter',
  R10: 'Behoerden / Oeffentlicher Dienst',
}

export const ALL_ROLES = ['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10'] as const

export const TARGET_AUDIENCE_LABELS: Record<string, string> = {
  enterprise: 'Unternehmen',
  authority: 'Behoerden',
  provider: 'IT-Dienstleister',
  all: 'Alle',
}

// =============================================================================
// MAIN ENTITIES
// =============================================================================

export interface TrainingModule {
  id: string
  tenant_id: string
  academy_course_id?: string
  module_code: string
  title: string
  description?: string
  regulation_area: RegulationArea
  nis2_relevant: boolean
  iso_controls: string[]
  frequency_type: FrequencyType
  validity_days: number
  risk_weight: number
  content_type: string
  duration_minutes: number
  pass_threshold: number
  is_active: boolean
  sort_order: number
  created_at: string
  updated_at: string
}

export interface TrainingMatrixEntry {
  id: string
  tenant_id: string
  role_code: string
  module_id: string
  is_mandatory: boolean
  priority: number
  created_at: string
  module_code?: string
  module_title?: string
}

export interface TrainingAssignment {
  id: string
  tenant_id: string
  module_id: string
  user_id: string
  user_name: string
  user_email: string
  role_code?: string
  trigger_type: TriggerType
  trigger_event?: string
  status: AssignmentStatus
  progress_percent: number
  quiz_score?: number
  quiz_passed?: boolean
  quiz_attempts: number
  started_at?: string
  completed_at?: string
  deadline: string
  certificate_id?: string
  escalation_level: number
  last_escalation_at?: string
  enrollment_id?: string
  created_at: string
  updated_at: string
  module_code?: string
  module_title?: string
}

export interface QuizQuestion {
  id: string
  question: string
  options: string[]
  difficulty: Difficulty
}

export interface QuizAttempt {
  id: string
  assignment_id: string
  user_id: string
  answers: QuizAnswer[]
  score: number
  passed: boolean
  correct_count: number
  total_count: number
  duration_seconds?: number
  attempted_at: string
}

export interface QuizAnswer {
  question_id: string
  selected_index: number
  correct: boolean
}

export interface ModuleContent {
  id: string
  module_id: string
  version: number
  content_format: string
  content_body: string
  summary?: string
  generated_by?: string
  llm_model?: string
  is_published: boolean
  reviewed_by?: string
  reviewed_at?: string
  created_at: string
  updated_at: string
}

export interface AuditLogEntry {
  id: string
  tenant_id: string
  user_id?: string
  action: AuditAction
  entity_type: string
  entity_id?: string
  details: Record<string, unknown>
  ip_address?: string
  created_at: string
}

export interface DeadlineInfo {
  assignment_id: string
  module_code: string
  module_title: string
  user_id: string
  user_name: string
  deadline: string
  days_left: number
  status: AssignmentStatus
}

export interface EscalationResult {
  assignment_id: string
  user_id: string
  user_name: string
  user_email: string
  module_title: string
  previous_level: number
  new_level: number
  days_overdue: number
  escalation_label: string
}

export interface TrainingStats {
  total_modules: number
  total_assignments: number
  completion_rate: number
  overdue_count: number
  pending_count: number
  in_progress_count: number
  completed_count: number
  avg_quiz_score: number
  avg_completion_days: number
  upcoming_deadlines: number
}

// =============================================================================
// API RESPONSES
// =============================================================================

export interface ModuleListResponse {
  modules: TrainingModule[]
  total: number
}

export interface AssignmentListResponse {
  assignments: TrainingAssignment[]
  total: number
}

export interface MatrixResponse {
  entries: Record<string, TrainingMatrixEntry[]>
  roles: Record<string, string>
}

export interface AuditLogResponse {
  entries: AuditLogEntry[]
  total: number
}

export interface EscalationResponse {
  results: EscalationResult[]
  total_checked: number
  escalated: number
}

export interface DeadlineListResponse {
  deadlines: DeadlineInfo[]
  total: number
}

export interface QuizSubmitResponse {
  attempt_id: string
  score: number
  passed: boolean
  correct_count: number
  total_count: number
  threshold: number
}

// =============================================================================
// MEDIA (Audio/Video)
// =============================================================================

export type MediaType = 'audio' | 'video' | 'interactive_video'
export type MediaStatus = 'processing' | 'completed' | 'failed'

export interface TrainingMedia {
  id: string
  module_id: string
  content_id?: string
  media_type: MediaType
  status: MediaStatus
  bucket: string
  object_key: string
  file_size_bytes: number
  duration_seconds: number
  mime_type: string
  voice_model: string
  language: string
  metadata: Record<string, unknown>
  error_message?: string
  generated_by: string
  is_published: boolean
  created_at: string
  updated_at: string
}

export interface VideoScript {
  title: string
  sections: VideoScriptSection[]
}

export interface VideoScriptSection {
  heading: string
  text: string
  bullet_points: string[]
}

// =============================================================================
// TRAINING BLOCKS (Controls → Schulungsmodule)
// =============================================================================

export interface TrainingBlockConfig {
  id: string
  tenant_id: string
  name: string
  description?: string
  domain_filter?: string
  category_filter?: string
  severity_filter?: string
  target_audience_filter?: string
  regulation_area: RegulationArea
  module_code_prefix: string
  frequency_type: FrequencyType
  duration_minutes: number
  pass_threshold: number
  max_controls_per_module: number
  is_active: boolean
  last_generated_at?: string
  created_at: string
  updated_at: string
}

export interface CanonicalControlSummary {
  control_id: string
  title: string
  objective: string
  rationale: string
  requirements: string[]
  severity: string
  category: string
  target_audience: string
  tags: string[]
}

export interface CanonicalControlMeta {
  domains: { domain: string; count: number }[]
  categories: { category: string; count: number }[]
  audiences: { audience: string; count: number }[]
  total: number
}

export interface BlockPreview {
  control_count: number
  module_count: number
  controls: CanonicalControlSummary[]
  proposed_roles: string[]
}

export interface BlockGenerateResult {
  modules_created: number
  controls_linked: number
  matrix_entries_created: number
  content_generated: number
  errors?: string[]
}

export interface TrainingBlockControlLink {
  id: string
  block_config_id: string
  module_id: string
  control_id: string
  control_title: string
  control_objective: string
  control_requirements: string[]
  sort_order: number
  created_at: string
}

// =============================================================================
// INTERACTIVE VIDEO / CHECKPOINTS
// =============================================================================

export interface InteractiveVideoManifest {
  media_id: string
  stream_url: string
  checkpoints: CheckpointEntry[]
}

export interface CheckpointEntry {
  checkpoint_id: string
  index: number
  title: string
  timestamp_seconds: number
  questions: CheckpointQuestion[]
  progress?: CheckpointProgress
}

export interface CheckpointQuestion {
  question: string
  options: string[]
  correct_index: number
  explanation: string
}

export interface CheckpointProgress {
  id: string
  assignment_id: string
  checkpoint_id: string
  passed: boolean
  attempts: number
  last_attempt_at?: string
}

export interface CheckpointQuizResult {
  passed: boolean
  score: number
  feedback: CheckpointQuizFeedback[]
}

export interface CheckpointQuizFeedback {
  question: string
  correct: boolean
  explanation: string
}
