#!/usr/bin/env node
'use strict';

const path = require('path');
const fs = require('fs');

const rootDir = path.join(__dirname, '..');
const binDir = path.join(__dirname, '..', 'bin');
const targetsDir = path.join(binDir, 'targets');
const packageJSONPath = path.join(rootDir, 'package.json');
const expected = [
  'skill-cli-darwin-arm64',
  'skill-cli-darwin-x64',
  'skill-cli-linux-arm64',
  'skill-cli-linux-x64',
  'skill-cli-win32-x64.exe',
];
const expectedInstallers = [
  'scripts/install.ps1',
  'scripts/install.sh',
  'scripts/make-install-bundle.js',
  'scripts/check-install-host.js',
];

const missing = expected.filter((name) => !fs.existsSync(path.join(targetsDir, name)));

if (missing.length > 0) {
  console.error('skill-cli: missing bundled binaries for npm publish:');
  for (const name of missing) {
    console.error('  - ' + name);
  }
  console.error('Run: bash scripts/build-all.sh');
  process.exit(1);
}

const pkg = JSON.parse(fs.readFileSync(packageJSONPath, 'utf8'));
const files = new Set(pkg.files || []);
const missingInstallers = expectedInstallers.filter((name) => !fs.existsSync(path.join(rootDir, name)));
const missingInstallerFilesEntries = expectedInstallers.filter((name) => !files.has(name));

if (missingInstallers.length > 0) {
  console.error('skill-cli: missing one-line installer scripts:');
  for (const name of missingInstallers) {
    console.error('  - ' + name);
  }
  process.exit(1);
}

if (missingInstallerFilesEntries.length > 0) {
  console.error('skill-cli: package.json files is missing installer scripts:');
  for (const name of missingInstallerFilesEntries) {
    console.error('  - ' + name);
  }
  process.exit(1);
}

const expectedVersion = `v${pkg.version}`;
const installerVersionPatterns = [
  {
    file: 'scripts/install.sh',
    pattern: /DEFAULT_VERSION="([^"]+)"/,
  },
  {
    file: 'scripts/install.ps1',
    pattern: /\$Version = "([^"]+)"/,
  },
];

for (const item of installerVersionPatterns) {
  const installerPath = path.join(rootDir, item.file);
  const content = fs.readFileSync(installerPath, 'utf8');
  const match = content.match(item.pattern);
  if (!match) {
    console.error(`skill-cli: could not find default version in ${item.file}`);
    process.exit(1);
  }
  if (match[1] !== expectedVersion) {
    console.error(`skill-cli: ${item.file} default version is ${match[1]}, expected ${expectedVersion}`);
    process.exit(1);
  }
}
