'use strict';

const fs = require('fs');
const path = require('path');

// Returns ordered list of camera device paths.
// Priority: DEV0/DEV1/... env vars → /dev/v4l/by-id/ → /dev/video*
function detectDevices() {
  // Explicit env vars take priority
  const envDevices = [];
  for (let i = 0; i < 8; i++) {
    const dev = process.env[`DEV${i}`];
    if (dev) envDevices.push(dev);
  }
  if (envDevices.length > 0) return envDevices;

  // Stable device IDs (survive USB re-plug without renumbering)
  const byIdDir = '/dev/v4l/by-id';
  if (fs.existsSync(byIdDir)) {
    try {
      const found = fs.readdirSync(byIdDir)
        .filter(name => !name.endsWith('-index1')) // skip audio/metadata endpoints
        .map(name => fs.realpathSync(path.join(byIdDir, name)))
        .filter((v, i, arr) => arr.indexOf(v) === i) // deduplicate symlink targets
        .sort();
      if (found.length > 0) return found;
    } catch { /* fall through */ }
  }

  // Simple enumeration fallback (Linux)
  try {
    const found = fs.readdirSync('/dev')
      .filter(name => /^video\d+$/.test(name))
      .sort((a, b) => parseInt(a.slice(5)) - parseInt(b.slice(5)))
      .map(name => `/dev/${name}`);
    if (found.length > 0) return found;
  } catch { /* fall through */ }

  return ['/dev/video0', '/dev/video2'];
}


module.exports = { detectDevices };
