import fs from "fs";
import path from "path";
import {
  applyTimingUpdates,
  createEmptyTimings,
  normalizeTimings,
} from "../timing/index.mjs";

const TIMINGS_FILENAME = "timings.json";

export function writeRunArtifact(productDir, artifact) {
  const resultsDir = path.join(productDir, ".testkit", "results");
  fs.mkdirSync(resultsDir, { recursive: true });
  fs.writeFileSync(path.join(resultsDir, "latest.json"), JSON.stringify(artifact, null, 2));
}

export function writeStatusArtifact(productDir, artifact) {
  fs.writeFileSync(
    path.join(productDir, "testkit.status.json"),
    `${JSON.stringify(artifact, null, 2)}\n`
  );
}

export function loadTimings(productDir) {
  const filePath = path.join(productDir, ".testkit", TIMINGS_FILENAME);
  if (!fs.existsSync(filePath)) {
    return createEmptyTimings();
  }

  try {
    return normalizeTimings(JSON.parse(fs.readFileSync(filePath, "utf8")));
  } catch {
    return createEmptyTimings();
  }
}

export function saveTimings(productDir, timings, updates) {
  if (updates.length === 0) return;
  const next = applyTimingUpdates(timings, updates);
  const rootDir = path.join(productDir, ".testkit");
  fs.mkdirSync(rootDir, { recursive: true });
  fs.writeFileSync(path.join(rootDir, TIMINGS_FILENAME), JSON.stringify(next, null, 2));
}
