import fs from "fs";
import path from "path";

const RESULT_LOGS_DIRNAME = "logs";

export function createRunLogRegistry(productDir) {
  const records = new Map();

  return {
    ensureServiceLogRecord(config) {
      const key = `${config.runtimeLabel || config.name}:${config.name}`;
      const existing = records.get(key);
      if (existing) return existing;

      const fileName = `${sanitizePathSegment(config.runtimeLabel || config.name)}__${sanitizePathSegment(config.name)}.log`;
      const relativePath = path.join(".testkit", "results", RESULT_LOGS_DIRNAME, fileName);
      const absolutePath = path.join(productDir, relativePath);
      fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
      const stream = fs.createWriteStream(absolutePath, { flags: "a" });
      const record = {
        key,
        serviceName: config.name,
        runtimeLabel: config.runtimeLabel || config.name,
        path: normalizePath(relativePath),
        absolutePath,
        stream,
      };
      records.set(key, record);
      return record;
    },
    append(record, streamName, line) {
      if (!record || typeof line !== "string") return;
      record.stream.write(`${new Date().toISOString()} [${streamName}] ${line}\n`);
    },
    listServiceLogs() {
      return [...records.values()]
        .map((record) => ({
          serviceName: record.serviceName,
          runtimeLabel: record.runtimeLabel,
          path: record.path,
        }))
        .sort(
          (left, right) =>
            left.serviceName.localeCompare(right.serviceName) ||
            left.runtimeLabel.localeCompare(right.runtimeLabel)
        );
    },
    closeAll() {
      for (const record of records.values()) {
        record.stream.end();
      }
    },
  };
}

export function readLogTail(absolutePath, lineCount = 80) {
  if (!absolutePath || !fs.existsSync(absolutePath)) return [];
  const lines = fs.readFileSync(absolutePath, "utf8").split(/\r?\n/).filter(Boolean);
  return lines.slice(Math.max(0, lines.length - lineCount));
}

function sanitizePathSegment(value) {
  return String(value)
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9._-]+/g, "-")
    .replace(/^-+|-+$/g, "") || "log";
}

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