import type { Block } from '@/services/api/blocks'
import type { MissionControlBridgeStatusResponse } from '@/services/api/missionControl'
import {
  normalizeExplorerStats,
  type ExplorerFreshnessReference,
  type ExplorerFreshnessSnapshot,
  type ExplorerStats,
} from '@/services/api/stats'
import type { ChainActivityContext } from '@/utils/activityContext'

export function resolveEffectiveFreshness(
  stats: ExplorerStats | null | undefined,
  bridgeStatus: MissionControlBridgeStatusResponse | null | undefined,
): ExplorerFreshnessSnapshot | null {
  if (stats?.freshness) {
    return stats.freshness
  }

  const missionFreshness = bridgeStatus?.data?.freshness
  if (!missionFreshness || typeof missionFreshness !== 'object') {
    return null
  }

  return normalizeExplorerStats({
    freshness: missionFreshness as Record<string, unknown>,
  }).freshness
}

export function resolveFreshnessSourceLabel(
  stats: ExplorerStats | null | undefined,
  bridgeStatus: MissionControlBridgeStatusResponse | null | undefined,
): string {
  if (stats?.freshness) {
    return 'Based on public stats and indexed explorer freshness.'
  }

  if (bridgeStatus?.data?.freshness) {
    return 'Based on mission-control freshness and latest visible public data.'
  }

  return 'Based on the latest visible public explorer data.'
}

export function summarizeFreshnessConfidence(
  stats: ExplorerStats | null | undefined,
  bridgeStatus: MissionControlBridgeStatusResponse | null | undefined,
): string[] {
  const effectiveFreshness = resolveEffectiveFreshness(stats, bridgeStatus)
  if (!effectiveFreshness) {
    return ['Freshness: unavailable']
  }

  const chainConfidence = describeFreshnessReference('Head', effectiveFreshness.chain_head)
  const txConfidence = describeFreshnessReference('Transactions', effectiveFreshness.latest_indexed_transaction)
  const snapshotMode = bridgeStatus?.data?.mode?.kind || null

  return [
    chainConfidence,
    txConfidence,
    snapshotMode ? `Feed: ${snapshotMode}` : 'Feed: direct',
  ]
}

function describeFreshnessReference(label: string, reference: ExplorerFreshnessReference): string {
  const completeness = String(reference.completeness || '').toLowerCase()
  const confidence = String(reference.confidence || '').toLowerCase()
  const source = String(reference.source || '').toLowerCase()

  if (source === 'unavailable' || completeness === 'unavailable') {
    return `${label}: unavailable`
  }

  if (completeness === 'partial') {
    return `${label}: partial visibility`
  }

  if (confidence === 'high') {
    return `${label}: directly reported`
  }

  if (confidence === 'medium') {
    return `${label}: reported sample`
  }

  if (confidence === 'low') {
    return `${label}: limited confidence`
  }

  return `${label}: reported`
}

export function shouldExplainEmptyHeadBlocks(
  blocks: Pick<Block, 'transaction_count'>[],
  context: ChainActivityContext,
): boolean {
  if (!Array.isArray(blocks) || blocks.length === 0) {
    return false
  }

  const visibleBlocks = blocks.slice(0, Math.min(blocks.length, 5))
  const allVisibleBlocksEmpty = visibleBlocks.every((block) => Number(block.transaction_count || 0) === 0)

  return allVisibleBlocksEmpty && Boolean(context.head_is_idle && (context.block_gap_to_latest_transaction || 0) > 0)
}
