/**
 * SDK Helper Functions
 *
 * Navigation helpers, risk calculation, completion tracking,
 * and package management utilities.
 */

import type { SDKPhase, SDKPackageId, RiskLikelihood, RiskImpact, RiskSeverity, CustomerType } from './core'
import type { SDKStep, SDK_STEPS } from './sdk-flow'
import type { SDKPackage, SDK_PACKAGES } from './company-profile'
import type { Risk } from './risk'
import type { SDKState } from './state'

// Re-import values (not just types) for runtime use
// We need the actual arrays, not just the types
import { SDK_STEPS as STEPS } from './sdk-flow'
import { SDK_PACKAGES as PACKAGES } from './company-profile'

// =============================================================================
// STEP NAVIGATION
// =============================================================================

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

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

export function getStepsForPhase(phase: SDKPhase): SDKStep[] {
  return 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]
  }

  // Move to next phase
  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]
  }

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

  return undefined
}

// =============================================================================
// RISK CALCULATION
// =============================================================================

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 TRACKING
// =============================================================================

export function getCompletionPercentage(state: SDKState): number {
  const totalSteps = 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 PACKAGES.find(p => p.id === packageId)
}

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

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 = 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 = PACKAGES.find(p => p.order === currentPackage.order - 1)
  if (!prevPackage) return true

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

export function getVisibleStepsForCustomerType(customerType: CustomerType): SDKStep[] {
  return STEPS.filter(step => {
    // Import step is only for existing customers
    if (step.id === 'import') {
      return customerType === 'existing'
    }
    return true
  })
}
