import { describe, it, expect, onTestFinished } from "vitest";
import { mkdtempSync, rmSync, cpSync } from "node:fs";
import { tmpdir } from "node:os";
import { execSync } from "node:child_process";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { computeSnapshot } from "../lib/snapshot.js";
import expectedSnapshot from "../__snapshots__/core-package/analytics.snapshot.json" with { type: "json" };

// Repo root is 2 levels up from turbo/generators/__tests__
const REPO_ROOT = resolve(
  fileURLToPath(import.meta.url),
  "..",
  "..",
  "..",
  "..",
);

describe("e2e: core-package analytics", () => {
  it(
    "byte-identical reconstruction matches snapshot",
    { timeout: 120_000 },
    () => {
      const tmp = mkdtempSync(join(tmpdir(), "e2e-analytics-"));
      // Each e2e run clones the repo into the OS temp dir; remove it when
      // the test finishes so sequential runs don't accumulate and fill disk.
      onTestFinished(() => rmSync(tmp, { recursive: true, force: true }));
      cpSync(REPO_ROOT, tmp, {
        recursive: true,
        filter: (src) =>
          !src.includes("node_modules") &&
          !src.includes(".turbo") &&
          !src.includes(".pnpm-store") &&
          !src.includes("packages/core-analytics"),
      });

      // No other package.json depends on @repo/core-analytics, so no strip
      // step is needed — excluding the source dir is sufficient.
      execSync(`cd ${tmp} && pnpm install --frozen-lockfile=false`, {
        stdio: "ignore",
      });
      execSync(`cd ${tmp} && pnpm turbo gen core-package --args analytics`, {
        stdio: "ignore",
      });
      const result = computeSnapshot(join(tmp, "packages/core-analytics"));
      expect(result).toEqual(expectedSnapshot);
    },
  );
});
