import fs from "fs";
import os from "os";
import path from "path";
import { execFileSync } from "child_process";
import { fileURLToPath } from "url";
import { parseGitHubRepoSlug } from "../known-failures/github.mjs";

export function collectGitMetadata(productDir) {
  const read = (args) => {
    try {
      return execaSyncCompat("git", args, { cwd: productDir }).trim() || null;
    } catch {
      return null;
    }
  };

  const remoteUrl = read(["remote", "get-url", "origin"]);

  return {
    branch: read(["rev-parse", "--abbrev-ref", "HEAD"]),
    commitSha: read(["rev-parse", "HEAD"]),
    repoRoot: read(["rev-parse", "--show-toplevel"]),
    remoteUrl,
    repoSlug: parseGitHubRepoSlug(remoteUrl),
  };
}

export function readPackageMetadata() {
  try {
    const thisFile = fileURLToPath(import.meta.url);
    const packagePath = path.resolve(path.dirname(thisFile), "..", "..", "package.json");
    return JSON.parse(fs.readFileSync(packagePath, "utf8"));
  } catch {
    return { version: "unknown" };
  }
}

export function safeHostname() {
  try {
    return os.hostname();
  } catch {
    return null;
  }
}

export function safeUsername() {
  try {
    return os.userInfo().username;
  } catch {
    return process.env.USER || process.env.USERNAME || null;
  }
}

function execaSyncCompat(command, args, options) {
  return execFileSync(command, args, {
    cwd: options?.cwd,
    encoding: "utf8",
    stdio: ["ignore", "pipe", "pipe"],
  });
}
