import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const root = path.resolve(__dirname, '..');
const stagingDir = path.join(root, '.pack-drupal-staging', 'dfg_3dviewer');
const outFile = path.join(root, 'dfg_3dviewer-drupal.zip');

const moduleFiles = [
  'dfg_3dviewer.info.yml',
  'dfg_3dviewer.libraries.yml',
  'dfg_3dviewer.links.menu.yml',
  'dfg_3dviewer.module',
  'dfg_3dviewer.permissions.yml',
  'dfg_3dviewer.routing.yml',
  'dfg_3dviewer.services.yml',
  'dfg_3dviewer.translation.yml',
  'README.md',
];

const moduleDirs = ['src', 'config'];

const scriptExclude = new Set([
  'pack-drupal-module.js',
  '.env',
]);

function copyRecursive(src, dest) {
  fs.cpSync(src, dest, { recursive: true });
}

function stageScripts(targetScriptsDir) {
  fs.mkdirSync(targetScriptsDir, { recursive: true });
  for (const entry of fs.readdirSync(path.join(root, 'scripts'), { withFileTypes: true })) {
    if (entry.isFile() && scriptExclude.has(entry.name)) {
      continue;
    }
    const src = path.join(root, 'scripts', entry.name);
    const dest = path.join(targetScriptsDir, entry.name);
    if (entry.isDirectory()) {
      copyRecursive(src, dest);
    } else {
      fs.copyFileSync(src, dest);
    }
  }
}

function stageModule() {
  if (fs.existsSync(path.dirname(stagingDir))) {
    fs.rmSync(path.dirname(stagingDir), { recursive: true, force: true });
  }
  fs.mkdirSync(stagingDir, { recursive: true });

  for (const file of moduleFiles) {
    const src = path.join(root, file);
    if (!fs.existsSync(src)) {
      console.warn(`[pack-drupal] skip missing file: ${file}`);
      continue;
    }
    fs.copyFileSync(src, path.join(stagingDir, file));
  }

  for (const dir of moduleDirs) {
    copyRecursive(path.join(root, dir), path.join(stagingDir, dir));
  }

  stageScripts(path.join(stagingDir, 'scripts'));
}

stageModule();

if (fs.existsSync(outFile)) {
  fs.rmSync(outFile);
}

const zipProcess = spawnSync('zip', ['-rq', outFile, 'dfg_3dviewer'], {
  cwd: path.dirname(stagingDir),
  stdio: 'inherit',
});

fs.rmSync(path.dirname(stagingDir), { recursive: true, force: true });

if (zipProcess.error) {
  if (zipProcess.error.code === 'ENOENT') {
    console.error('`zip` command not found. Install it before running pack.');
    process.exit(1);
  }
  throw zipProcess.error;
}

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

console.log(`Created ${outFile} (${fs.statSync(outFile).size} bytes)`);
