type ReleaseManifestLike = {
  commerce?: {
    operator_checkout_url?: string | null
    studio_checkout_url?: string | null
  } | null
  corresponding_source_url?: string | null
  open_source_repo_url?: string | null
  platforms?: Array<{
    platform_key: string
    configured: boolean
  }>
}

type AuthHealthLike = {
  billing?: {
    productPlanMapConfigured?: boolean
    pricePlanMapConfigured?: boolean
    webhookSecretConfigured?: boolean
  }
  runtime?: {
    public_origin_ready?: boolean
  }
  launch?: {
    posture?: 'launch-ready' | 'preview'
    ready?: boolean
    readiness?: Partial<PublicLaunchReadiness> | null
    checklist?: PublicLaunchChecklistItem[]
    missingLabels?: string[]
    targets?: PublicLaunchTargets
  } | null
}

export type PublicLaunchChecklistId =
  | 'windows-download'
  | 'macos-download'
  | 'linux-download'
  | 'operator-checkout'
  | 'studio-checkout'
  | 'mpl-source'
  | 'open-source-notices'
  | 'billing-product-map'
  | 'billing-price-map'
  | 'billing-webhook-secret'
  | 'public-auth-runtime'

export type PublicLaunchChecklistItem = {
  id: PublicLaunchChecklistId
  label: string
  configured: boolean
  requiredForPublicLaunch: boolean
}

export type PublicLaunchReadiness = {
  windowsDownloadConfigured: boolean
  macosDownloadConfigured: boolean
  linuxDownloadConfigured: boolean
  operatorCheckoutConfigured: boolean
  studioCheckoutConfigured: boolean
  mplSourceConfigured: boolean
  openSourceRepoConfigured: boolean
  billingProductPlanMapConfigured: boolean
  billingPricePlanMapConfigured: boolean
  billingWebhookSecretConfigured: boolean
  publicAuthRuntimeReady: boolean
}

export type PublicLaunchTargets = {
  operatorCheckoutTarget: string | null
  studioCheckoutTarget: string | null
}

export type PublicLaunchStatusSummary = {
  posture: 'launch-ready' | 'preview'
  ready: boolean
  readiness: PublicLaunchReadiness
  checklist: PublicLaunchChecklistItem[]
  missingLabels: string[]
  targets: PublicLaunchTargets
}

type PublicLaunchReadinessInput = Partial<PublicLaunchReadiness> & {
  macDownloadConfigured?: boolean
}

function hasConfiguredPlatform(manifest: ReleaseManifestLike | null | undefined, platformKey: string) {
  if (!Array.isArray(manifest?.platforms)) {
    return null
  }

  return manifest.platforms.some((platform) => platform.platform_key === platformKey && platform.configured)
}

function normalizeConfiguredValue(value: unknown) {
  return value === true
}

export function normalizePublicLaunchReadiness(
  input?: PublicLaunchReadinessInput | null,
): PublicLaunchReadiness {
  return {
    windowsDownloadConfigured: normalizeConfiguredValue(input?.windowsDownloadConfigured),
    macosDownloadConfigured:
      normalizeConfiguredValue(input?.macosDownloadConfigured)
      || normalizeConfiguredValue(input?.macDownloadConfigured),
    linuxDownloadConfigured: normalizeConfiguredValue(input?.linuxDownloadConfigured),
    operatorCheckoutConfigured: normalizeConfiguredValue(input?.operatorCheckoutConfigured),
    studioCheckoutConfigured: normalizeConfiguredValue(input?.studioCheckoutConfigured),
    mplSourceConfigured: normalizeConfiguredValue(input?.mplSourceConfigured),
    openSourceRepoConfigured: normalizeConfiguredValue(input?.openSourceRepoConfigured),
    billingProductPlanMapConfigured: normalizeConfiguredValue(input?.billingProductPlanMapConfigured),
    billingPricePlanMapConfigured: normalizeConfiguredValue(input?.billingPricePlanMapConfigured),
    billingWebhookSecretConfigured: normalizeConfiguredValue(input?.billingWebhookSecretConfigured),
    publicAuthRuntimeReady: normalizeConfiguredValue(input?.publicAuthRuntimeReady),
  }
}

export function getPublicLaunchChecklist(
  readinessInput: PublicLaunchReadinessInput,
): PublicLaunchChecklistItem[] {
  const readiness = normalizePublicLaunchReadiness(readinessInput)

  return [
    {
      id: 'windows-download',
      label: 'Windows download URL',
      configured: readiness.windowsDownloadConfigured,
      requiredForPublicLaunch: true,
    },
    {
      id: 'macos-download',
      label: 'macOS download URL',
      configured: readiness.macosDownloadConfigured,
      requiredForPublicLaunch: false,
    },
    {
      id: 'linux-download',
      label: 'Linux download URL',
      configured: readiness.linuxDownloadConfigured,
      requiredForPublicLaunch: false,
    },
    {
      id: 'operator-checkout',
      label: 'Operator checkout URL',
      configured: readiness.operatorCheckoutConfigured,
      requiredForPublicLaunch: true,
    },
    {
      id: 'studio-checkout',
      label: 'Studio checkout URL',
      configured: readiness.studioCheckoutConfigured,
      requiredForPublicLaunch: true,
    },
    {
      id: 'mpl-source',
      label: 'MPL corresponding-source URL',
      configured: readiness.mplSourceConfigured,
      requiredForPublicLaunch: true,
    },
    {
      id: 'open-source-notices',
      label: 'Open-source repo/notices URL',
      configured: readiness.openSourceRepoConfigured,
      requiredForPublicLaunch: true,
    },
    {
      id: 'billing-product-map',
      label: 'Billing product-plan map',
      configured: readiness.billingProductPlanMapConfigured,
      requiredForPublicLaunch: true,
    },
    {
      id: 'billing-price-map',
      label: 'Billing price-plan map',
      configured: readiness.billingPricePlanMapConfigured,
      requiredForPublicLaunch: true,
    },
    {
      id: 'billing-webhook-secret',
      label: 'Paddle webhook secret',
      configured: readiness.billingWebhookSecretConfigured,
      requiredForPublicLaunch: true,
    },
    {
      id: 'public-auth-runtime',
      label: 'Public auth runtime status',
      configured: readiness.publicAuthRuntimeReady,
      requiredForPublicLaunch: true,
    },
  ]
}

export function getMissingPublicLaunchChecklistItems(
  readinessInput: PublicLaunchReadinessInput,
  options?: {
    requiredOnly?: boolean
  },
): PublicLaunchChecklistItem[] {
  return getPublicLaunchChecklist(readinessInput).filter((item) => (
    !item.configured && (!options?.requiredOnly || item.requiredForPublicLaunch)
  ))
}

export function isPublicLaunchReady(readinessInput: PublicLaunchReadinessInput): boolean {
  return getMissingPublicLaunchChecklistItems(readinessInput, { requiredOnly: true }).length === 0
}

export function resolveManifestPublicLaunchReadiness(
  manifest: ReleaseManifestLike | null | undefined,
  fallback?: PublicLaunchReadinessInput | null,
): PublicLaunchReadiness {
  const normalizedFallback = normalizePublicLaunchReadiness(fallback)

  const windowsDownloadConfigured = hasConfiguredPlatform(manifest, 'windows')
  const macosDownloadConfigured = hasConfiguredPlatform(manifest, 'macos')
  const linuxDownloadConfigured = hasConfiguredPlatform(manifest, 'linux')

  return {
    windowsDownloadConfigured:
      windowsDownloadConfigured ?? normalizedFallback.windowsDownloadConfigured,
    macosDownloadConfigured:
      macosDownloadConfigured ?? normalizedFallback.macosDownloadConfigured,
    linuxDownloadConfigured:
      linuxDownloadConfigured ?? normalizedFallback.linuxDownloadConfigured,
    operatorCheckoutConfigured:
      manifest?.commerce?.operator_checkout_url != null
        ? Boolean(manifest.commerce.operator_checkout_url)
        : normalizedFallback.operatorCheckoutConfigured,
    studioCheckoutConfigured:
      manifest?.commerce?.studio_checkout_url != null
        ? Boolean(manifest.commerce.studio_checkout_url)
        : normalizedFallback.studioCheckoutConfigured,
    mplSourceConfigured:
      manifest?.corresponding_source_url != null
        ? Boolean(manifest.corresponding_source_url)
        : normalizedFallback.mplSourceConfigured,
    openSourceRepoConfigured:
      manifest?.open_source_repo_url != null
        ? Boolean(manifest.open_source_repo_url)
        : normalizedFallback.openSourceRepoConfigured,
    billingProductPlanMapConfigured: normalizedFallback.billingProductPlanMapConfigured,
    billingPricePlanMapConfigured: normalizedFallback.billingPricePlanMapConfigured,
    billingWebhookSecretConfigured: normalizedFallback.billingWebhookSecretConfigured,
    publicAuthRuntimeReady: normalizedFallback.publicAuthRuntimeReady,
  }
}

export function resolvePublicLaunchTargets(
  manifest: ReleaseManifestLike | null | undefined,
  health?: AuthHealthLike | null,
): PublicLaunchTargets {
  return {
    operatorCheckoutTarget:
      health?.launch?.targets?.operatorCheckoutTarget
      ?? manifest?.commerce?.operator_checkout_url
      ?? null,
    studioCheckoutTarget:
      health?.launch?.targets?.studioCheckoutTarget
      ?? manifest?.commerce?.studio_checkout_url
      ?? null,
  }
}

export function resolveHealthPublicLaunchReadiness({
  manifest,
  health,
  fallback,
}: {
  manifest?: ReleaseManifestLike | null
  health?: AuthHealthLike | null
  fallback?: PublicLaunchReadinessInput | null
}): PublicLaunchReadiness {
  const manifestReadiness = resolveManifestPublicLaunchReadiness(manifest, fallback)
  const healthReadiness = normalizePublicLaunchReadiness({
    ...manifestReadiness,
    billingProductPlanMapConfigured: health?.billing?.productPlanMapConfigured,
    billingPricePlanMapConfigured: health?.billing?.pricePlanMapConfigured,
    billingWebhookSecretConfigured: health?.billing?.webhookSecretConfigured,
    publicAuthRuntimeReady: health?.runtime?.public_origin_ready,
    ...health?.launch?.readiness,
  })

  return healthReadiness
}

export function buildPublicLaunchStatusSummary(
  readinessInput: PublicLaunchReadinessInput,
  targets: PublicLaunchTargets = {
    operatorCheckoutTarget: null,
    studioCheckoutTarget: null,
  },
): PublicLaunchStatusSummary {
  const readiness = normalizePublicLaunchReadiness(readinessInput)
  const ready = isPublicLaunchReady(readiness)

  return {
    posture: ready ? 'launch-ready' : 'preview',
    ready,
    readiness,
    checklist: getPublicLaunchChecklist(readiness),
    missingLabels: getMissingPublicLaunchChecklistItems(readiness, {
      requiredOnly: true,
    }).map((item) => item.label),
    targets,
  }
}

function resolveHealthLaunchChecklist(
  launch: NonNullable<AuthHealthLike['launch']>,
  readiness: PublicLaunchReadiness,
): PublicLaunchChecklistItem[] {
  const derivedChecklist = getPublicLaunchChecklist(readiness)
  if (!Array.isArray(launch.checklist) || launch.checklist.length === 0) {
    return derivedChecklist
  }

  const launchChecklistById = new Map(
    launch.checklist.map((item) => [item.id, item]),
  )

  return derivedChecklist.map((item) => {
    const launchItem = launchChecklistById.get(item.id)
    if (!launchItem) {
      return item
    }

    return {
      ...item,
      label:
        typeof launchItem.label === 'string' && launchItem.label.trim().length > 0
          ? launchItem.label
          : item.label,
      configured: normalizeConfiguredValue(launchItem.configured),
      requiredForPublicLaunch:
        typeof launchItem.requiredForPublicLaunch === 'boolean'
          ? launchItem.requiredForPublicLaunch
          : item.requiredForPublicLaunch,
    }
  })
}

function resolveHealthLaunchMissingLabels(
  launch: NonNullable<AuthHealthLike['launch']>,
  checklist: readonly PublicLaunchChecklistItem[],
  ready: boolean,
): string[] {
  const launchMissingLabels = Array.isArray(launch.missingLabels)
    ? launch.missingLabels
      .map((label) => String(label || '').trim())
      .map((label) => label.replace(/\bpreview-tier launch gate\b/gi, 'public launch gate'))
      .map((label) => label.replace(/\bpreview-tier\b/gi, 'public launch'))
      .filter(Boolean)
    : []

  if (launchMissingLabels.length > 0 || ready) {
    return launchMissingLabels
  }

  return checklist
    .filter((item) => item.requiredForPublicLaunch && !item.configured)
    .map((item) => item.label)
}

export function resolvePublicLaunchStatusSummary({
  manifest,
  health,
  fallback,
}: {
  manifest?: ReleaseManifestLike | null
  health?: AuthHealthLike | null
  fallback?: PublicLaunchReadinessInput | null
}): PublicLaunchStatusSummary {
  const derivedSummary = buildPublicLaunchStatusSummary(
    resolveHealthPublicLaunchReadiness({
      manifest,
      health,
      fallback,
    }),
    resolvePublicLaunchTargets(manifest, health),
  )

  if (!health?.launch) {
    return derivedSummary
  }

  const readiness = normalizePublicLaunchReadiness({
    ...derivedSummary.readiness,
    ...health.launch.readiness,
  })
  const checklist = resolveHealthLaunchChecklist(health.launch, readiness)
  const ready =
    typeof health.launch.ready === 'boolean'
      ? health.launch.ready && health.launch.posture === 'launch-ready'
      : derivedSummary.ready

  return {
    posture: ready ? 'launch-ready' : 'preview',
    ready,
    readiness,
    checklist,
    missingLabels: resolveHealthLaunchMissingLabels(health.launch, checklist, ready),
    targets: resolvePublicLaunchTargets(manifest, health),
  }
}
