<?php

/**
 * Standalone plugin-ZIP builder — no WordPress required.
 *
 * Wraps the framework Packager so a release archive can be produced in CI
 * (or locally) without booting WordPress. The `wp __PLUGIN_NAME__ build`
 * WP-CLI subcommand uses the same engine.
 *
 * Usage:
 *   php bin/build-zip.php [--slug=<slug>] [--version=<ver>] [--output=<dir>]
 *
 * Run `composer install --no-dev -o` and `npm run build` first so the archive
 * ships a lean vendor/ and built public/ assets.
 */

use PluginsNameSpaces\Framework\Console\Packager;

$root = dirname(__DIR__);

// The plugin's autoloaded helpers guard on ABSPATH (`exit` when undefined).
// Define a stub so the Composer autoloader loads outside WordPress; no WP
// function is actually called by the Packager.
if (! defined('ABSPATH')) {
    define('ABSPATH', $root . '/');
}

$autoload = $root . '/vendor/autoload.php';
if (! is_file($autoload)) {
    fwrite(STDERR, "Composer autoloader missing. Run `composer install` first.\n");
    exit(1);
}
require $autoload;

/**
 * Parse `--key=value` CLI options.
 */
$opts = [];
foreach (array_slice($argv, 1) as $arg) {
    if (preg_match('/^--([^=]+)=(.*)$/', $arg, $m)) {
        $opts[$m[1]] = $m[2];
    }
}

$slug = isset($opts['slug']) ? $opts['slug'] : basename($root);

if (isset($opts['version'])) {
    $version = $opts['version'];
} else {
    $version = '';
    $pkg = $root . '/package.json';
    if (is_file($pkg)) {
        $json = json_decode((string) file_get_contents($pkg), true);
        $version = isset($json['version']) ? (string) $json['version'] : '';
    }
}

try {
    $packager = new Packager($root, $slug, $version, isset($opts['output']) ? $opts['output'] : null);
    $zip = $packager->build();
} catch (\Throwable $e) {
    fwrite(STDERR, 'Build failed: ' . $e->getMessage() . "\n");
    exit(1);
}

fwrite(STDOUT, $zip . "\n");
exit(0);
