import fs from "fs";
import os from "os";
import path from "path";
import { execFileSync } from "child_process";
import { afterEach, describe, expect, it } from "vitest";
import {
  collectGitMetadata,
  readPackageMetadata,
  safeHostname,
  safeUsername,
} from "./metadata.mjs";

const tempDirs = [];

afterEach(() => {
  for (const dir of tempDirs.splice(0)) {
    fs.rmSync(dir, { recursive: true, force: true });
  }
});

function mkTempDir() {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "testkit-runner-metadata-"));
  tempDirs.push(dir);
  return dir;
}

describe("runner-metadata", () => {
  it("reads package metadata and safe host/user info", () => {
    const pkg = readPackageMetadata();
    const packageJson = JSON.parse(
      fs.readFileSync(path.resolve(process.cwd(), "package.json"), "utf8")
    );
    expect(pkg.version).toBe(packageJson.version);
    expect(typeof safeHostname()).toBe("string");
    expect(typeof safeUsername()).toBe("string");
  });

  it("collects git metadata from a real repo", () => {
    const repoDir = mkTempDir();
    execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "ignore" });
    execFileSync("git", ["config", "user.email", "test@example.com"], { cwd: repoDir, stdio: "ignore" });
    execFileSync("git", ["config", "user.name", "Test User"], { cwd: repoDir, stdio: "ignore" });
    fs.writeFileSync(path.join(repoDir, "README.md"), "# test\n");
    execFileSync("git", ["add", "README.md"], { cwd: repoDir, stdio: "ignore" });
    execFileSync("git", ["commit", "-m", "init"], { cwd: repoDir, stdio: "ignore" });

    const metadata = collectGitMetadata(repoDir);
    expect(metadata.branch).toBe("main");
    expect(metadata.commitSha).toMatch(/^[a-f0-9]{40}$/);
    expect(metadata.repoRoot).toBe(repoDir);
  });
});
