import path from "path";

export function createEmptyTimings() {
  return {
    version: 1,
    files: {},
  };
}

export function normalizeTimings(parsed) {
  return {
    version: 1,
    files: parsed?.files && typeof parsed.files === "object" ? parsed.files : {},
  };
}

export function applyTimingUpdates(timings, updates, updatedAt = new Date().toISOString()) {
  const next = {
    version: 1,
    files: { ...timings.files },
  };

  for (const update of updates) {
    const existing = next.files[update.key];
    if (!existing) {
      next.files[update.key] = {
        durationMs: Math.max(1, Math.round(update.durationMs)),
        runs: 1,
        updatedAt,
      };
      continue;
    }

    const runs = Number(existing.runs || 0) + 1;
    const durationMs = Math.max(
      1,
      Math.round(((existing.durationMs || update.durationMs) * (runs - 1) + update.durationMs) / runs)
    );
    next.files[update.key] = {
      durationMs,
      runs,
      updatedAt,
    };
  }

  return next;
}

export function estimateTaskDuration(timings, timingKey, suite) {
  const cached = timings.files[timingKey];
  if (cached?.durationMs) return cached.durationMs;

  const base =
    suite.framework === "playwright"
      ? 20_000
      : suite.type === "dal"
        ? 4_000
        : 8_000;
  return Math.max(1_000, Math.round((base * suite.weight) / Math.max(1, suite.files.length)));
}

export function buildTimingKey(serviceName, suite, file) {
  return [
    serviceName,
    suite.framework,
    suite.type,
    normalizePathSeparators(file),
  ].join("|");
}

function normalizePathSeparators(filePath) {
  return filePath.split(path.sep).join("/");
}
