import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { env } from '../config/env.js';

type WorkServerSlot = 'blue' | 'green';

function normalizeSlot(value: string | null | undefined): WorkServerSlot | null {
  const normalized = String(value ?? '').trim().toLowerCase();
  return normalized === 'blue' || normalized === 'green' ? normalized : null;
}

function buildActiveSlotFileCandidates() {
  const candidates = [
    env.SERVER_COMMAND_WORK_SERVER_ACTIVE_SLOT_FILE?.trim(),
    path.join(env.SERVER_COMMAND_MAIN_PROJECT_ROOT, 'etc', 'servers', 'work-server', '.docker', 'runtime', 'active-slot'),
    path.join(env.SERVER_COMMAND_PROJECT_ROOT, 'etc', 'servers', 'work-server', '.docker', 'runtime', 'active-slot'),
    path.join(env.SERVER_COMMAND_PROJECT_ROOT, '.docker', 'runtime', 'active-slot'),
  ]
    .map((value) => String(value ?? '').trim())
    .filter(Boolean);

  return [...new Set(candidates)];
}

async function readActiveSlotFromFile() {
  for (const candidate of buildActiveSlotFileCandidates()) {
    try {
      const value = await readFile(candidate, 'utf8');
      const slot = normalizeSlot(value);

      if (slot) {
        return slot;
      }
    } catch {
      // Ignore missing or unreadable candidates and continue.
    }
  }

  return null;
}

export async function isCurrentWorkServerSlotActive() {
  const currentSlot = normalizeSlot(process.env.WORK_SERVER_SLOT);

  if (!currentSlot) {
    return true;
  }

  const activeSlot = (await readActiveSlotFromFile()) ?? 'blue';
  return currentSlot === activeSlot;
}
