/**
 * 共享组件版本注册表
 * 用于管理跨Feature的共享组件版本兼容性
 */

export interface ComponentVersion {
  version: string
  compatibleRange: string
  breaking: boolean
  description: string
  dependents: string[]
}

export interface FeatureDependency {
  featureName: string
  requiredComponents: Record<string, string>
  optionalComponents: Record<string, string>
}

/**
 * 全局共享组件注册表
 */
export const SHARED_COMPONENTS: Record<string, ComponentVersion> = {
  'AccountManager': {
    version: '2.1.0',
    compatibleRange: '^2.0.0',
    breaking: false,
    description: '账户管理器 - 处理账户状态、余额、仓位管理',
    dependents: ['001-specManager-perp', '003-delta-50-80']
  },

  'PriceManager': {
    version: '1.5.0',
    compatibleRange: '^1.4.0',
    breaking: false,
    description: '价格管理器 - 实时价格获取和缓存',
    dependents: ['001-specManager-perp', '003-delta-50-80']
  },

  'OrderExecutor': {
    version: '3.0.0',
    compatibleRange: '^3.0.0',
    breaking: true,
    description: '订单执行器 - 统一的订单执行接口',
    dependents: ['001-specManager-perp', '003-delta-50-80']
  },

  'CredentialService': {
    version: '1.0.0',
    compatibleRange: '^1.0.0',
    breaking: false,
    description: '凭证管理服务 - 多平台凭证存储和签名',
    dependents: ['002-credential-manager', '003-delta-50-80']
  },

  'PacificaProxyClient': {
    version: '2.3.0',
    compatibleRange: '^2.0.0',
    breaking: false,
    description: 'Pacifica代理客户端 - HTTP+代理网络访问',
    dependents: ['001-specManager-perp', '003-delta-50-80']
  },

  'RiskManager': {
    version: '1.2.0',
    compatibleRange: '^1.0.0',
    breaking: false,
    description: '风险管理器 - 风险控制和监控',
    dependents: ['001-specManager-perp', '003-delta-50-80']
  }
}

/**
 * Feature依赖声明
 */
export const FEATURE_DEPENDENCIES: Record<string, FeatureDependency> = {
  '001-specManager-perp': {
    featureName: '多平台Delta中性控制平面',
    requiredComponents: {
      'AccountManager': '^2.0.0',
      'PriceManager': '^1.4.0',
      'OrderExecutor': '^3.0.0',
      'PacificaProxyClient': '^2.0.0',
      'RiskManager': '^1.0.0'
    },
    optionalComponents: {}
  },

  '002-credential-manager': {
    featureName: '多平台账户凭据管理与签名服务',
    requiredComponents: {
      'CredentialService': '^1.0.0'
    },
    optionalComponents: {
      'AccountManager': '^2.0.0'
    }
  },

  '003-delta-50-80': {
    featureName: '50%-80%资金利用率的Delta中性控制',
    requiredComponents: {
      'AccountManager': '^2.1.0',
      'PriceManager': '^1.5.0',
      'OrderExecutor': '^3.0.0',
      'CredentialService': '^1.0.0',
      'PacificaProxyClient': '^2.0.0',
      'RiskManager': '^1.2.0'
    },
    optionalComponents: {}
  }
}

/**
 * 检查版本兼容性
 */
export function checkVersionCompatibility(
  componentName: string,
  requiredVersion: string
): { compatible: boolean; message: string } {
  const component = SHARED_COMPONENTS[componentName]

  if (!component) {
    return {
      compatible: false,
      message: `未知组件: ${componentName}`
    }
  }

  // 简单的版本检查逻辑
  const currentVersion = component.version
  const semverRegex = /^(\^|~)?(\d+)\.(\d+)\.(\d+)$/

  const currentMatch = currentVersion.match(semverRegex)
  const requiredMatch = requiredVersion.match(semverRegex)

  if (!currentMatch || !requiredMatch) {
    return {
      compatible: false,
      message: `版本格式错误: current=${currentVersion}, required=${requiredVersion}`
    }
  }

  const [, requiredPrefix, reqMajor, reqMinor, reqPatch] = requiredMatch
  const [, , curMajor, curMinor, curPatch] = currentMatch

  const reqMajorNum = parseInt(reqMajor)
  const reqMinorNum = parseInt(reqMinor)
  const reqPatchNum = parseInt(reqPatch)

  const curMajorNum = parseInt(curMajor)
  const curMinorNum = parseInt(curMinor)
  const curPatchNum = parseInt(curPatch)

  if (requiredPrefix === '^') {
    // 兼容主版本
    if (curMajorNum !== reqMajorNum) {
      return {
        compatible: false,
        message: `主版本不兼容: current=${currentVersion}, required=${requiredVersion}`
      }
    }

    if (curMinorNum < reqMinorNum ||
        (curMinorNum === reqMinorNum && curPatchNum < reqPatchNum)) {
      return {
        compatible: false,
        message: `版本过低: current=${currentVersion}, required=${requiredVersion}`
      }
    }
  }

  return {
    compatible: true,
    message: `版本兼容: current=${currentVersion}, required=${requiredVersion}`
  }
}

/**
 * 检查Feature依赖
 */
export function checkFeatureDependencies(featureName: string): {
  success: boolean
  issues: string[]
  warnings: string[]
} {
  const dependency = FEATURE_DEPENDENCIES[featureName]

  if (!dependency) {
    return {
      success: false,
      issues: [`未找到Feature依赖定义: ${featureName}`],
      warnings: []
    }
  }

  const issues: string[] = []
  const warnings: string[] = []

  // 检查必需组件
  for (const [componentName, requiredVersion] of Object.entries(dependency.requiredComponents)) {
    const check = checkVersionCompatibility(componentName, requiredVersion)

    if (!check.compatible) {
      issues.push(`${componentName}: ${check.message}`)
    }
  }

  // 检查可选组件
  for (const [componentName, requiredVersion] of Object.entries(dependency.optionalComponents)) {
    const check = checkVersionCompatibility(componentName, requiredVersion)

    if (!check.compatible) {
      warnings.push(`${componentName} (可选): ${check.message}`)
    }
  }

  return {
    success: issues.length === 0,
    issues,
    warnings
  }
}

/**
 * 获取组件的所有依赖Feature
 */
export function getComponentDependents(componentName: string): string[] {
  const component = SHARED_COMPONENTS[componentName]
  return component ? component.dependents : []
}

/**
 * 检查组件更新对其他Feature的影响
 */
export function checkComponentUpdateImpact(
  componentName: string,
  newVersion: string
): {
  affectedFeatures: string[]
  breakingChanges: boolean
  recommendations: string[]
} {
  const component = SHARED_COMPONENTS[componentName]

  if (!component) {
    return {
      affectedFeatures: [],
      breakingChanges: false,
      recommendations: [`组件 ${componentName} 不存在`]
    }
  }

  const affectedFeatures = component.dependents
  const recommendations: string[] = []

  // 检查是否为破坏性变更
  const currentMajor = parseInt(component.version.split('.')[0])
  const newMajor = parseInt(newVersion.split('.')[0])
  const breakingChanges = newMajor > currentMajor

  if (breakingChanges) {
    recommendations.push(`⚠️  主版本升级，需要更新所有依赖Feature`)
    recommendations.push(`建议创建迁移指南`)
    recommendations.push(`建议分阶段更新Feature`)
  } else {
    recommendations.push(`✅ 向后兼容的更新`)
    recommendations.push(`可以直接更新，无需修改依赖Feature`)
  }

  return {
    affectedFeatures,
    breakingChanges,
    recommendations
  }
}