<?php
declare(strict_types=1);

/**
 * Create .env from the prepared staging/production template.
 *
 * Usage:
 *   php scripts/create_env.php staging
 *   php scripts/create_env.php production
 *   php scripts/create_env.php staging --force
 */

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "403 Forbidden\n";
    exit(1);
}

$root = dirname(__DIR__);
$environment = $argv[1] ?? '';
$force = in_array('--force', $argv, true);

if (!in_array($environment, ['staging', 'production'], true)) {
    fwrite(STDERR, "Usage: php scripts/create_env.php <staging|production> [--force]\n");
    exit(1);
}

$source = $root . "/deploy/env/.env.{$environment}.template";
$target = $root . '/.env';

if (!is_file($source)) {
    fwrite(STDERR, "Template not found: {$source}\n");
    exit(1);
}

if (is_file($target) && !$force) {
    fwrite(STDERR, ".env already exists. Use --force only if you intentionally want to replace it.\n");
    exit(1);
}

if (!copy($source, $target)) {
    fwrite(STDERR, "Failed to create .env\n");
    exit(1);
}

@chmod($target, 0600);

echo "Created .env from {$environment} template.\n";
echo "Next: edit .env and replace every ISI_ / GANTI_ placeholder.\n";
