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

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

const rootDir = path.join(__dirname, '..');
const outDir = path.join(rootDir, 'dist', 'install');
const pkg = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json'), 'utf8'));
const version = `v${pkg.version}`;
const targets = [
  'skill-cli-darwin-arm64',
  'skill-cli-darwin-x64',
  'skill-cli-linux-arm64',
  'skill-cli-linux-x64',
  'skill-cli-win32-x64.exe',
];

const args = process.argv.slice(2);
let baseURL = '';
let rootURL = '';
for (let i = 0; i < args.length; i += 1) {
  if (args[i] === '--base-url') {
    baseURL = args[i + 1] || '';
    i += 1;
  } else if (args[i] === '--root') {
    rootURL = args[i + 1] || '';
    i += 1;
  } else if (args[i] === '-h' || args[i] === '--help') {
    console.log(`Usage:
  node scripts/make-install-bundle.js [--root URL]
  node scripts/make-install-bundle.js [--base-url URL]

Creates dist/install/ with one-line installer scripts and prebuilt binaries.
When --root is provided, generated installer copies default to ROOT/bin/targets.
When --base-url is provided, generated installer copies default to that URL
for binary downloads, which is useful for intranet static hosting.`);
    process.exit(0);
  } else {
    console.error(`unknown option: ${args[i]}`);
    process.exit(2);
  }
}

function trimSlash(value) {
  return value.replace(/\/+$/, '');
}

if (rootURL && baseURL) {
  console.error('use either --root or --base-url, not both');
  process.exit(2);
}

if (rootURL) {
  rootURL = trimSlash(rootURL);
  baseURL = `${rootURL}/bin/targets`;
}

function copyFile(src, dest) {
  fs.mkdirSync(path.dirname(dest), { recursive: true });
  fs.copyFileSync(src, dest);
}

function writeFile(dest, content) {
  fs.mkdirSync(path.dirname(dest), { recursive: true });
  fs.writeFileSync(dest, content);
}

fs.rmSync(outDir, { recursive: true, force: true });

for (const target of targets) {
  const src = path.join(rootDir, 'bin', 'targets', target);
  if (!fs.existsSync(src)) {
    console.error(`missing binary: ${src}`);
    process.exit(1);
  }
  copyFile(src, path.join(outDir, 'bin', 'targets', target));
}

let installSH = fs.readFileSync(path.join(rootDir, 'scripts', 'install.sh'), 'utf8');
let installPS1 = fs.readFileSync(path.join(rootDir, 'scripts', 'install.ps1'), 'utf8');

if (baseURL) {
  const normalizedBaseURL = trimSlash(baseURL);
  installSH = installSH.replace(
    /DEFAULT_BASE_URL="https:\/\/gitee\.com\/marvin-dev\/skill-cli-creator\/raw\/\$\{VERSION\}\/bin\/targets"/,
    `DEFAULT_BASE_URL="${normalizedBaseURL}"`
  ).replace(
    /DEFAULT_BASE_URL_USES_VERSION=1/,
    'DEFAULT_BASE_URL_USES_VERSION=0'
  );
  installPS1 = installPS1.replace(
    /\$BaseUrl = "https:\/\/gitee\.com\/marvin-dev\/skill-cli-creator\/raw\/\$Version\/bin\/targets"/,
    `$BaseUrl = "${normalizedBaseURL}"`
  );
}

writeFile(path.join(outDir, 'scripts', 'install.sh'), installSH);
writeFile(path.join(outDir, 'scripts', 'install.ps1'), installPS1);

const manifest = {
  package: pkg.name,
  version: pkg.version,
  tag: version,
  generatedAt: new Date().toISOString(),
  rootURL: rootURL || null,
  baseURL: baseURL || null,
  files: [
    'scripts/install.ps1',
    'scripts/install.sh',
    ...targets.map((target) => `bin/targets/${target}`),
  ],
};
writeFile(path.join(outDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);

function inferInstallRootFromBaseURL(value) {
  const normalized = trimSlash(value);
  if (normalized.endsWith('/bin/targets')) {
    return normalized.slice(0, -'/bin/targets'.length);
  }
  return '<your-hosted-root>';
}

const installRoot = rootURL || (baseURL ? inferInstallRootFromBaseURL(baseURL) : `https://gitee.com/marvin-dev/skill-cli-creator/raw/${version}`);
const psURL = baseURL ? `${installRoot}/scripts/install.ps1` : `${installRoot}/scripts/install.ps1`;
const shURL = baseURL ? `${installRoot}/scripts/install.sh` : `${installRoot}/scripts/install.sh`;

writeFile(path.join(outDir, 'README.txt'), `skill-cli ${version} install bundle

Host this directory as a static tree. Required layout:
  scripts/install.ps1
  scripts/install.sh
  bin/targets/skill-cli-*

Windows PowerShell:
  irm ${psURL} | iex

macOS/Linux:
  curl -fsSL ${shURL} | bash

If --base-url was not used to generate this bundle, set SKILL_CLI_BASE_URL
to the hosted bin/targets URL before running the installer.
`);

console.log(`Created ${outDir}`);
console.log(`Version: ${version}`);
if (baseURL) {
  console.log(`Default binary base URL: ${baseURL}`);
}
