/**
 * SDK State Types
 *
 * Type definitions for the SDK's state management system
 */

import type {
  SubscriptionTier,
  UserPreferences,
  Risk,
  CommandHistory,
  CheckpointStatus,
} from './base'
import type {
  ConsentRecord,
  DSRConfig,
  DSRRequest,
  CookieBannerConfig,
  ProcessingActivity,
  DSFA,
  TOM,
  RetentionPolicy,
  EscalationWorkflow,
  LegalDocument,
} from './dsgvo'
import type {
  Control,
  Evidence,
  Requirement,
  ServiceModule,
  Obligation,
  AIActResult,
  ChecklistItem,
} from './compliance'
import type { SBOM, SecurityIssue, BacklogItem, SecurityScanResult } from './security'

// =============================================================================
// SDK FLOW & NAVIGATION
// =============================================================================

export type SDKPhase = 1 | 2

export interface SDKStep {
  id: string
  phase: SDKPhase
  order: number
  name: string
  nameShort: string
  description: string
  url: string
  checkpointId: string
  prerequisiteSteps: string[]
  isOptional: boolean
}

export const SDK_STEPS: SDKStep[] = [
  // Phase 1: Automatisches Compliance Assessment
  {
    id: 'use-case-workshop',
    phase: 1,
    order: 1,
    name: 'Use Case Workshop',
    nameShort: 'Use Case',
    description: '5-Schritte-Wizard für Use Case Erfassung',
    url: '/sdk/advisory-board',
    checkpointId: 'CP-UC',
    prerequisiteSteps: [],
    isOptional: false,
  },
  {
    id: 'screening',
    phase: 1,
    order: 2,
    name: 'System Screening',
    nameShort: 'Screening',
    description: 'SBOM + Security Check',
    url: '/sdk/screening',
    checkpointId: 'CP-SCAN',
    prerequisiteSteps: ['use-case-workshop'],
    isOptional: false,
  },
  {
    id: 'modules',
    phase: 1,
    order: 3,
    name: 'Compliance Modules',
    nameShort: 'Module',
    description: 'Abgleich welche Regulierungen gelten',
    url: '/sdk/modules',
    checkpointId: 'CP-MOD',
    prerequisiteSteps: ['screening'],
    isOptional: false,
  },
  {
    id: 'requirements',
    phase: 1,
    order: 4,
    name: 'Requirements',
    nameShort: 'Anforderungen',
    description: 'Prüfaspekte aus Regulierungen ableiten',
    url: '/sdk/requirements',
    checkpointId: 'CP-REQ',
    prerequisiteSteps: ['modules'],
    isOptional: false,
  },
  {
    id: 'controls',
    phase: 1,
    order: 5,
    name: 'Controls',
    nameShort: 'Controls',
    description: 'Erforderliche Maßnahmen ermitteln',
    url: '/sdk/controls',
    checkpointId: 'CP-CTRL',
    prerequisiteSteps: ['requirements'],
    isOptional: false,
  },
  {
    id: 'evidence',
    phase: 1,
    order: 6,
    name: 'Evidence',
    nameShort: 'Nachweise',
    description: 'Nachweise dokumentieren',
    url: '/sdk/evidence',
    checkpointId: 'CP-EVI',
    prerequisiteSteps: ['controls'],
    isOptional: false,
  },
  {
    id: 'audit-checklist',
    phase: 1,
    order: 7,
    name: 'Audit Checklist',
    nameShort: 'Checklist',
    description: 'Prüfliste generieren',
    url: '/sdk/audit-checklist',
    checkpointId: 'CP-CHK',
    prerequisiteSteps: ['evidence'],
    isOptional: false,
  },
  {
    id: 'risks',
    phase: 1,
    order: 8,
    name: 'Risk Matrix',
    nameShort: 'Risiken',
    description: 'Risikobewertung & Residual Risk',
    url: '/sdk/risks',
    checkpointId: 'CP-RISK',
    prerequisiteSteps: ['audit-checklist'],
    isOptional: false,
  },
  // Phase 2: Dokumentengenerierung
  {
    id: 'ai-act',
    phase: 2,
    order: 1,
    name: 'AI Act Klassifizierung',
    nameShort: 'AI Act',
    description: 'Risikostufe nach EU AI Act',
    url: '/sdk/ai-act',
    checkpointId: 'CP-AI',
    prerequisiteSteps: ['risks'],
    isOptional: false,
  },
  {
    id: 'obligations',
    phase: 2,
    order: 2,
    name: 'Pflichtenübersicht',
    nameShort: 'Pflichten',
    description: 'NIS2, DSGVO, AI Act Pflichten',
    url: '/sdk/obligations',
    checkpointId: 'CP-OBL',
    prerequisiteSteps: ['ai-act'],
    isOptional: false,
  },
  {
    id: 'dsfa',
    phase: 2,
    order: 3,
    name: 'DSFA',
    nameShort: 'DSFA',
    description: 'Datenschutz-Folgenabschätzung',
    url: '/sdk/dsfa',
    checkpointId: 'CP-DSFA',
    prerequisiteSteps: ['obligations'],
    isOptional: true,
  },
  {
    id: 'tom',
    phase: 2,
    order: 4,
    name: 'TOMs',
    nameShort: 'TOMs',
    description: 'Technische & Org. Maßnahmen',
    url: '/sdk/tom',
    checkpointId: 'CP-TOM',
    prerequisiteSteps: ['dsfa'],
    isOptional: false,
  },
  {
    id: 'loeschfristen',
    phase: 2,
    order: 5,
    name: 'Löschfristen',
    nameShort: 'Löschfristen',
    description: 'Aufbewahrungsrichtlinien',
    url: '/sdk/loeschfristen',
    checkpointId: 'CP-RET',
    prerequisiteSteps: ['tom'],
    isOptional: false,
  },
  {
    id: 'vvt',
    phase: 2,
    order: 6,
    name: 'Verarbeitungsverzeichnis',
    nameShort: 'VVT',
    description: 'Art. 30 DSGVO Dokumentation',
    url: '/sdk/vvt',
    checkpointId: 'CP-VVT',
    prerequisiteSteps: ['loeschfristen'],
    isOptional: false,
  },
  {
    id: 'consent',
    phase: 2,
    order: 7,
    name: 'Rechtliche Vorlagen',
    nameShort: 'Vorlagen',
    description: 'AGB, Datenschutz, Nutzungsbedingungen',
    url: '/sdk/consent',
    checkpointId: 'CP-DOC',
    prerequisiteSteps: ['vvt'],
    isOptional: false,
  },
  {
    id: 'cookie-banner',
    phase: 2,
    order: 8,
    name: 'Cookie Banner',
    nameShort: 'Cookies',
    description: 'Cookie-Consent Generator',
    url: '/sdk/cookie-banner',
    checkpointId: 'CP-COOK',
    prerequisiteSteps: ['consent'],
    isOptional: false,
  },
  {
    id: 'einwilligungen',
    phase: 2,
    order: 9,
    name: 'Einwilligungen',
    nameShort: 'Consents',
    description: 'Consent-Tracking Setup',
    url: '/sdk/einwilligungen',
    checkpointId: 'CP-CONS',
    prerequisiteSteps: ['cookie-banner'],
    isOptional: false,
  },
  {
    id: 'dsr',
    phase: 2,
    order: 10,
    name: 'DSR Portal',
    nameShort: 'DSR',
    description: 'Betroffenenrechte-Portal',
    url: '/sdk/dsr',
    checkpointId: 'CP-DSR',
    prerequisiteSteps: ['einwilligungen'],
    isOptional: false,
  },
  {
    id: 'escalations',
    phase: 2,
    order: 11,
    name: 'Escalations',
    nameShort: 'Eskalationen',
    description: 'Management-Workflows',
    url: '/sdk/escalations',
    checkpointId: 'CP-ESC',
    prerequisiteSteps: ['dsr'],
    isOptional: false,
  },
]

// =============================================================================
// USE CASE ASSESSMENT
// =============================================================================

export interface UseCaseStep {
  id: string
  name: string
  completed: boolean
  data: Record<string, unknown>
}

export interface AssessmentResult {
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
  applicableRegulations: string[]
  recommendedControls: string[]
  dsfaRequired: boolean
  aiActClassification: string
}

export interface UseCaseAssessment {
  id: string
  name: string
  description: string
  category: string
  stepsCompleted: number
  steps: UseCaseStep[]
  assessmentResult: AssessmentResult | null
  createdAt: Date
  updatedAt: Date
}

// =============================================================================
// SCREENING RESULT
// =============================================================================

export interface ScreeningResult {
  id: string
  status: 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED'
  startedAt: Date
  completedAt: Date | null
  sbom: SBOM | null
  securityScan: SecurityScanResult | null
  error: string | null
}

// =============================================================================
// SDK STATE
// =============================================================================

export interface SDKState {
  // Metadata
  version: string
  lastModified: Date

  // Tenant & User
  tenantId: string
  userId: string
  subscription: SubscriptionTier

  // Progress
  currentPhase: SDKPhase
  currentStep: string
  completedSteps: string[]
  checkpoints: Record<string, CheckpointStatus>

  // Phase 1 Data
  useCases: UseCaseAssessment[]
  activeUseCase: string | null
  screening: ScreeningResult | null
  modules: ServiceModule[]
  requirements: Requirement[]
  controls: Control[]
  evidence: Evidence[]
  checklist: ChecklistItem[]
  risks: Risk[]

  // Phase 2 Data
  aiActClassification: AIActResult | null
  obligations: Obligation[]
  dsfa: DSFA | null
  toms: TOM[]
  retentionPolicies: RetentionPolicy[]
  vvt: ProcessingActivity[]
  documents: LegalDocument[]
  cookieBanner: CookieBannerConfig | null
  consents: ConsentRecord[]
  dsrConfig: DSRConfig | null
  dsrRequests: DSRRequest[]
  escalationWorkflows: EscalationWorkflow[]

  // Security
  sbom: SBOM | null
  securityIssues: SecurityIssue[]
  securityBacklog: BacklogItem[]

  // UI State
  commandBarHistory: CommandHistory[]
  recentSearches: string[]
  preferences: UserPreferences
}

// =============================================================================
// SDK ACTIONS
// =============================================================================

export type SDKAction =
  | { type: 'SET_STATE'; payload: Partial<SDKState> }
  | { type: 'SET_CURRENT_STEP'; payload: string }
  | { type: 'COMPLETE_STEP'; payload: string }
  | { type: 'SET_CHECKPOINT_STATUS'; payload: { id: string; status: CheckpointStatus } }
  | { type: 'ADD_USE_CASE'; payload: UseCaseAssessment }
  | { type: 'UPDATE_USE_CASE'; payload: { id: string; data: Partial<UseCaseAssessment> } }
  | { type: 'DELETE_USE_CASE'; payload: string }
  | { type: 'SET_ACTIVE_USE_CASE'; payload: string | null }
  | { type: 'SET_SCREENING'; payload: ScreeningResult }
  | { type: 'ADD_MODULE'; payload: ServiceModule }
  | { type: 'UPDATE_MODULE'; payload: { id: string; data: Partial<ServiceModule> } }
  | { type: 'ADD_REQUIREMENT'; payload: Requirement }
  | { type: 'UPDATE_REQUIREMENT'; payload: { id: string; data: Partial<Requirement> } }
  | { type: 'ADD_CONTROL'; payload: Control }
  | { type: 'UPDATE_CONTROL'; payload: { id: string; data: Partial<Control> } }
  | { type: 'ADD_EVIDENCE'; payload: Evidence }
  | { type: 'UPDATE_EVIDENCE'; payload: { id: string; data: Partial<Evidence> } }
  | { type: 'DELETE_EVIDENCE'; payload: string }
  | { type: 'ADD_RISK'; payload: Risk }
  | { type: 'UPDATE_RISK'; payload: { id: string; data: Partial<Risk> } }
  | { type: 'DELETE_RISK'; payload: string }
  | { type: 'SET_AI_ACT_RESULT'; payload: AIActResult }
  | { type: 'ADD_OBLIGATION'; payload: Obligation }
  | { type: 'UPDATE_OBLIGATION'; payload: { id: string; data: Partial<Obligation> } }
  | { type: 'SET_DSFA'; payload: DSFA }
  | { type: 'ADD_TOM'; payload: TOM }
  | { type: 'UPDATE_TOM'; payload: { id: string; data: Partial<TOM> } }
  | { type: 'ADD_RETENTION_POLICY'; payload: RetentionPolicy }
  | { type: 'UPDATE_RETENTION_POLICY'; payload: { id: string; data: Partial<RetentionPolicy> } }
  | { type: 'ADD_PROCESSING_ACTIVITY'; payload: ProcessingActivity }
  | { type: 'UPDATE_PROCESSING_ACTIVITY'; payload: { id: string; data: Partial<ProcessingActivity> } }
  | { type: 'ADD_DOCUMENT'; payload: LegalDocument }
  | { type: 'UPDATE_DOCUMENT'; payload: { id: string; data: Partial<LegalDocument> } }
  | { type: 'SET_COOKIE_BANNER'; payload: CookieBannerConfig }
  | { type: 'SET_DSR_CONFIG'; payload: DSRConfig }
  | { type: 'ADD_DSR_REQUEST'; payload: DSRRequest }
  | { type: 'UPDATE_DSR_REQUEST'; payload: { id: string; data: Partial<DSRRequest> } }
  | { type: 'ADD_ESCALATION_WORKFLOW'; payload: EscalationWorkflow }
  | { type: 'UPDATE_ESCALATION_WORKFLOW'; payload: { id: string; data: Partial<EscalationWorkflow> } }
  | { type: 'ADD_SECURITY_ISSUE'; payload: SecurityIssue }
  | { type: 'UPDATE_SECURITY_ISSUE'; payload: { id: string; data: Partial<SecurityIssue> } }
  | { type: 'ADD_BACKLOG_ITEM'; payload: BacklogItem }
  | { type: 'UPDATE_BACKLOG_ITEM'; payload: { id: string; data: Partial<BacklogItem> } }
  | { type: 'ADD_COMMAND_HISTORY'; payload: CommandHistory }
  | { type: 'SET_PREFERENCES'; payload: Partial<UserPreferences> }
  | { type: 'RESET_STATE' }

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

export function getStepById(stepId: string): SDKStep | undefined {
  return SDK_STEPS.find(s => s.id === stepId)
}

export function getStepByUrl(url: string): SDKStep | undefined {
  return SDK_STEPS.find(s => s.url === url)
}

export function getStepsForPhase(phase: SDKPhase): SDKStep[] {
  return SDK_STEPS.filter(s => s.phase === phase).sort((a, b) => a.order - b.order)
}

export function getNextStep(currentStepId: string): SDKStep | undefined {
  const currentStep = getStepById(currentStepId)
  if (!currentStep) return undefined

  const stepsInPhase = getStepsForPhase(currentStep.phase)
  const currentIndex = stepsInPhase.findIndex(s => s.id === currentStepId)

  if (currentIndex < stepsInPhase.length - 1) {
    return stepsInPhase[currentIndex + 1]
  }

  if (currentStep.phase === 1) {
    return getStepsForPhase(2)[0]
  }

  return undefined
}

export function getPreviousStep(currentStepId: string): SDKStep | undefined {
  const currentStep = getStepById(currentStepId)
  if (!currentStep) return undefined

  const stepsInPhase = getStepsForPhase(currentStep.phase)
  const currentIndex = stepsInPhase.findIndex(s => s.id === currentStepId)

  if (currentIndex > 0) {
    return stepsInPhase[currentIndex - 1]
  }

  if (currentStep.phase === 2) {
    const phase1Steps = getStepsForPhase(1)
    return phase1Steps[phase1Steps.length - 1]
  }

  return undefined
}

export function getCompletionPercentage(state: SDKState): number {
  const totalSteps = SDK_STEPS.length
  const completedSteps = state.completedSteps.length
  return Math.round((completedSteps / totalSteps) * 100)
}

export function getPhaseCompletionPercentage(state: SDKState, phase: SDKPhase): number {
  const phaseSteps = getStepsForPhase(phase)
  const completedPhaseSteps = phaseSteps.filter(s => state.completedSteps.includes(s.id))
  return Math.round((completedPhaseSteps.length / phaseSteps.length) * 100)
}
