/**
 * Helper functions for SDK navigation, risk calculation, and package management.
 */

import type { SDKPhase, SDKPackageId, CustomerType, RiskLikelihood, RiskImpact, RiskSeverity } from './enums'
import type { SDKStep, SDKPackage } from './sdk-flow'
import type { SDKState } from './sdk-state'
import type { Risk } from './compliance'

import { SDK_PACKAGES as _SDK_PACKAGES } from './sdk-flow'
import { SDK_STEPS as _SDK_STEPS } from './sdk-steps'

// =============================================================================
// STEP HELPERS
// =============================================================================

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.seq - b.seq)
}

// Alle Steps global nach seq sortiert
function getAllStepsSorted(): SDKStep[] {
  return [..._SDK_STEPS].sort((a, b) => a.seq - b.seq)
}

// Sichtbare Steps (state-abhaengig)
export function getVisibleSteps(state: SDKState): SDKStep[] {
  return getAllStepsSorted().filter(step => {
    if (step.visibleWhen) return step.visibleWhen(state)
    return true
  })
}

// Naechster sichtbarer Step
export function getNextVisibleStep(currentStepId: string, state: SDKState): SDKStep | undefined {
  const visible = getVisibleSteps(state)
  const idx = visible.findIndex(s => s.id === currentStepId)
  if (idx >= 0 && idx < visible.length - 1) return visible[idx + 1]
  return undefined
}

// Vorheriger sichtbarer Step
export function getPreviousVisibleStep(currentStepId: string, state: SDKState): SDKStep | undefined {
  const visible = getVisibleSteps(state)
  const idx = visible.findIndex(s => s.id === currentStepId)
  if (idx > 0) return visible[idx - 1]
  return undefined
}

export function getNextStep(currentStepId: string, state?: SDKState): SDKStep | undefined {
  if (!state) {
    // Fallback: seq-sortiert ohne Sichtbarkeitspruefung
    const sorted = getAllStepsSorted()
    const idx = sorted.findIndex(s => s.id === currentStepId)
    if (idx >= 0 && idx < sorted.length - 1) return sorted[idx + 1]
    return undefined
  }
  return getNextVisibleStep(currentStepId, state)
}

export function getPreviousStep(currentStepId: string, state?: SDKState): SDKStep | undefined {
  if (!state) {
    const sorted = getAllStepsSorted()
    const idx = sorted.findIndex(s => s.id === currentStepId)
    if (idx > 0) return sorted[idx - 1]
    return undefined
  }
  return getPreviousVisibleStep(currentStepId, state)
}

// =============================================================================
// RISK HELPERS
// =============================================================================

export function calculateRiskScore(likelihood: RiskLikelihood, impact: RiskImpact): number {
  return likelihood * impact
}

export function getRiskSeverityFromScore(score: number): RiskSeverity {
  if (score >= 20) return 'CRITICAL'
  if (score >= 12) return 'HIGH'
  if (score >= 6) return 'MEDIUM'
  return 'LOW'
}

export function calculateResidualRisk(risk: Risk): number {
  const inherentScore = calculateRiskScore(risk.likelihood, risk.impact)
  const totalEffectiveness = risk.mitigation
    .filter(m => m.status === 'COMPLETED')
    .reduce((sum, m) => sum + m.effectiveness, 0)

  const effectivenessMultiplier = Math.min(totalEffectiveness, 100) / 100
  return Math.max(1, Math.round(inherentScore * (1 - effectivenessMultiplier)))
}

// =============================================================================
// COMPLETION HELPERS
// =============================================================================

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)
}

// =============================================================================
// PACKAGE HELPERS
// =============================================================================

export function getPackageById(packageId: SDKPackageId): SDKPackage | undefined {
  return _SDK_PACKAGES.find(p => p.id === packageId)
}

export function getStepsForPackage(packageId: SDKPackageId): SDKStep[] {
  return _SDK_STEPS.filter(s => s.package === packageId).sort((a, b) => a.seq - b.seq)
}

export function getPackageCompletionPercentage(state: SDKState, packageId: SDKPackageId): number {
  const packageSteps = getStepsForPackage(packageId)
  if (packageSteps.length === 0) return 0
  const completedPackageSteps = packageSteps.filter(s => state.completedSteps.includes(s.id))
  return Math.round((completedPackageSteps.length / packageSteps.length) * 100)
}

export function getCurrentPackage(currentStepId: string): SDKPackage | undefined {
  const step = getStepById(currentStepId)
  if (!step) return undefined
  return getPackageById(step.package)
}

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

  const packageSteps = getStepsForPackage(currentStep.package)
  const currentIndex = packageSteps.findIndex(s => s.id === currentStepId)

  // Next step in same package
  if (currentIndex < packageSteps.length - 1) {
    return packageSteps[currentIndex + 1]
  }

  // Move to next package
  const currentPackage = getPackageById(currentStep.package)
  if (!currentPackage) return undefined

  const nextPackage = _SDK_PACKAGES.find(p => p.order === currentPackage.order + 1)
  if (!nextPackage) return undefined

  const nextPackageSteps = getStepsForPackage(nextPackage.id)
  return nextPackageSteps[0]
}

export function isPackageUnlocked(state: SDKState, packageId: SDKPackageId): boolean {
  if (state.preferences?.allowParallelWork) return true

  const currentPackage = getPackageById(packageId)
  if (!currentPackage) return false

  // First package is always unlocked
  if (currentPackage.order === 1) return true

  // Previous package must be completed
  const prevPackage = _SDK_PACKAGES.find(p => p.order === currentPackage.order - 1)
  if (!prevPackage) return true

  return getPackageCompletionPercentage(state, prevPackage.id) === 100
}

/** @deprecated Use getVisibleSteps(state) instead */
export function getVisibleStepsForCustomerType(customerType: CustomerType): SDKStep[] {
  return getAllStepsSorted().filter(step => {
    if (step.id === 'import') {
      return customerType === 'existing'
    }
    return true
  })
}
