import type { ScanStatus } from '$lib/api/admin';

export type StageState = 'pending' | 'in_progress' | 'done' | 'skipped';

export type StageKey =
  | 'library'
  | 'mbid_backfill'
  | 'cover_enrich'
  | 'artist_art_enrich';

const ORDER: readonly StageKey[] = [
  'library',
  'mbid_backfill',
  'cover_enrich',
  'artist_art_enrich'
];

// stageState derives the per-stage state from a ScanStatus snapshot.
//
// Truth table:
//   in_progress = scan in-flight AND this stage's tally is non-empty AND
//                 no later stage has started yet.
//   done        = scan finished_at is set, OR a later stage has a tally
//                 (this stage ran to completion before the next started).
//   pending     = scan in-flight AND this stage hasn't started.
//   skipped     = scan finished AND this stage has no tally
//                 (e.g. ScanOnStartup=false skips the library walk).
export function stageState(scan: ScanStatus | undefined, stage: StageKey): StageState {
  if (!scan) return 'skipped';
  const idx = ORDER.indexOf(stage);
  const thisStage = scan[stage];
  const inFlight = scan.in_flight === true;

  let highestStarted = -1;
  for (let i = 0; i < ORDER.length; i++) {
    if (scan[ORDER[i]]) highestStarted = i;
  }

  if (thisStage) {
    if (!inFlight) return 'done';
    if (highestStarted > idx) return 'done';
    return 'in_progress';
  }

  if (inFlight) return 'pending';
  return 'skipped';
}
