import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";

const currentDir = dirname(fileURLToPath(import.meta.url));
const projectRoot = join(currentDir, "..");
const packageJson = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
const artifactRoot = join(projectRoot, "artifacts", "mobile");
const artifactName = `projectcraft-pro-mobile-store-source-${packageJson.version}.zip`;
const artifactPath = join(artifactRoot, artifactName);
const conflictCopyPattern = / [2-9](?=\.[^.]+$)/;
const skippedDirectories = new Set([
  "node_modules",
  "artifacts",
  ".gradle",
  "build",
  "Pods",
  ".swiftpm"
]);

function removeConflictCopies(directory) {
  for (const entry of readdirSync(directory)) {
    const fullPath = join(directory, entry);
    const stats = statSync(fullPath);

    if (stats.isDirectory()) {
      if (!skippedDirectories.has(entry)) {
        removeConflictCopies(fullPath);
      }
      continue;
    }

    if (stats.isFile() && conflictCopyPattern.test(entry)) {
      unlinkSync(fullPath);
    }
  }
}

mkdirSync(artifactRoot, { recursive: true });
rmSync(artifactPath, { force: true });
removeConflictCopies(projectRoot);

const result = spawnSync(
  "zip",
  [
    "-r",
    "-X",
    artifactPath,
    ".",
    "-x",
    "node_modules/*",
    "artifacts/*",
    "ios/App/Pods/*",
    "ios/App/build/*",
    "ios/App/CapApp-SPM/.swiftpm/*",
    "ios/App/CapApp-SPM/build/*",
    "android/.gradle/*",
    "android/app/build/*",
    "android/build/*",
    "* [2-9].*"
  ],
  {
    cwd: projectRoot,
    stdio: "inherit"
  }
);

if (result.status !== 0) {
  process.exit(result.status ?? 1);
}

console.log(`Mobile store source package created: ${artifactPath}`);
