'use strict';

const INTERFERENCE_TYPES = new Set(['COE', 'P2P', 'P3P']);
const DIRECTION_TYPES     = new Set(['UL', 'DL', 'BI']);

/**
 * Parse a TC_WIFI_*.ini filename and its parent directory name into tags.
 * Returns an object with all tag fields plus id and test_id.
 */
function parseTargetFilename(filename, parentDir) {
  const baseName = filename.replace(/\.ini$/i, '');
  const segments = baseName.split('_').slice(2); // Skip "TC" and "WIFI" prefix

  const id = `${parentDir}/${baseName}`;

  // Interference: first segment, fixed enum
  const interference = INTERFERENCE_TYPES.has(segments[0]) ? segments[0] : null;

  // File ID: segment matching R<digit><ALNUM>+
  const test_id = segments.find(s => /^R\d+[A-Z0-9]+$/i.test(s)) || null;

  // Device: segment after interference
  const device   = segments.length > 1 ? segments[1] : null;

  // Test Point: segment starting with TPT
  const test_point = segments.find(s => /^TPT\w+$/.test(s)) || null;

  // RSSI: segment matching RSSI<digits>
  const rssi = segments.find(s => /^RSSI\d+$/.test(s)) || null;

  // Station: segment matching STA<digits>
  const station = segments.find(s => /^STA\d+$/.test(s)) || null;

  // Band: segment matching <digit>GHZ
  const band = segments.find(s => /^\dGHZ$/.test(s)) || null;

  // Channel: segment matching CH<digits>
  const channel = segments.find(s => /^CH\d+$/.test(s)) || null;

  // Bandwidth: segment matching BW<digits>
  const bandwidth = segments.find(s => /^BW\d+$/.test(s)) || null;

  // Direction: last segment, fixed enum
  const lastSeg = segments[segments.length - 1];
  const direction = DIRECTION_TYPES.has(lastSeg) ? lastSeg : null;

  // Rotation from parent directory name: ROT<digits>
  const rotation = parentDir
    ? (parentDir.split('_').find(s => /^ROT\d+$/.test(s)) || null)
    : null;

  return { id, test_id, interference, device, test_point, rssi, station, band, channel, bandwidth, direction, rotation };
}

function parseResultFilename(filename){
  // Extract test_id and device from result file name
  // COE_CGW453_R2COERXAX014_TPT3E_RSSI70_STA56_2GHZ_CH1_BW20_TCP_MIMOFD_SONFD_MESHFD_LPI_UL
  const segments = filename.split(/[_\-]/);
  const test_id  = segments.find(s => /^R\d+[A-Z0-9]+$/.test(s)) || null;
  const device   = segments.length > 1 ? segments[1] : null; // Assuming device is the second segment
  return { test_id, device };
}

/**
 * Extract a timestamp from a result log filename.
 * Matches YYYY-MM-DD-HH-MM or YYYY-MM-DD-HH-MM-SS at the end of the name.
 * Returns an ISO-ish string (e.g. "2026-05-16T07:30:14") or null.
 */
function parseTimestamp(filename) {
  const match = filename.match(/(\d{4}-\d{2}-\d{2}-\d{2}-\d{2}(?:-\d{2})?)(?:\.\w+)?$/);
  if (!match) return null;
  const parts = match[1].split('-');
  const [year, month, day, hour, minute, second = '00'] = parts;
  return `${year}-${month}-${day}T${hour}:${minute}:${second}`;
}

/**
 * Convert an elapsed time string "H:MM:SS.ffffff" to total seconds.
 */
function parseElapsedTime(timeStr) {
  const match = timeStr.match(/^(\d+):(\d{2}):(\d{2})\.(\d+)$/);
  if (!match) return null;
  const [, h, m, s, frac] = match;
  return parseInt(h) * 3600 + parseInt(m) * 60 + parseInt(s) + parseFloat(`0.${frac}`);
}

function parseTputRssi(line) {
  // Parse a line for station, tput, and RSSI info. Ex:
  // [2026-05-18 15:09:46,167 INFO] STA56 over angles >> AVG IxChariot TPUT: 1464 Mbps, AVG DL RSSI: -42 dBm, AVG UL RSSI: -50 dBm, CHANNEL: 100
  const match = line.match(/STA(\d+) over angles >> AVG IxChariot TPUT: (\d+) Mbps, AVG DL RSSI: (-?\d+) dBm, AVG UL RSSI: (-?\d+) dBm/);
  if (!match) return null;
  const [, station, tput, dlRssi, ulRssi] = match;
  return { station: parseInt(station), tput: parseInt(tput), dlRssi: parseInt(dlRssi), ulRssi: parseInt(ulRssi) };
}

module.exports = { parseTargetFilename, parseResultFilename, parseTimestamp, parseElapsedTime, parseTputRssi };
