#!/usr/bin/env php
<?php

declare(strict_types=1);

require_once __DIR__ . '/module-cli-bootstrap.php';

require_once __DIR__ . '/module-migrate.php';
require_once __DIR__ . '/module-permissions-sync.php';
require_once __DIR__ . '/module-build.php';
require_once __DIR__ . '/module-assets-sync.php';

function moduleRuntimeSyncRun(): int
{
    return moduleCliRunStep('module-runtime-sync', static function (): int {
        $lockFile = __DIR__ . '/../storage/runtime/.module-runtime-sync.lock';
        return moduleCliWithFileLock(
            $lockFile,
            'module-runtime-sync: another runtime sync is in progress, skipping.',
            static function (): int {
                moduleCliBootstrapApp();
                $warningsBeforeAll = moduleCliVendorWarningsIgnoredTotal();

                $steps = [
                    'migrate' => static fn (): int => moduleMigrateRun(),
                    'permissions-sync' => static fn (): int => modulePermissionsSyncRun(),
                    'build' => static fn (): int => moduleBuildRun(),
                    'assets-sync' => static fn (): int => moduleAssetsSyncRun(),
                ];

                $statusByStep = [];
                foreach (array_keys($steps) as $stepName) {
                    $statusByStep[$stepName] = 'pending';
                }

                $finalExitCode = 0;
                foreach ($steps as $stepName => $runner) {
                    $stepWarningsBefore = moduleCliVendorWarningsIgnoredTotal();
                    $stepExitCode = $runner();
                    $stepWarnings = moduleCliVendorWarningsIgnoredSince($stepWarningsBefore);
                    $stepStatus = $stepExitCode === 0 ? 'ok' : 'failed';
                    $statusByStep[$stepName] = $stepStatus;

                    fwrite(STDOUT, sprintf(
                        "module-runtime-sync: step=%s status=%s exit_code=%d vendor_warnings_ignored=%d\n",
                        $stepName,
                        $stepStatus,
                        $stepExitCode,
                        $stepWarnings
                    ));

                    if ($stepExitCode !== 0) {
                        $finalExitCode = $stepExitCode;
                        break;
                    }
                }

                $totalVendorWarnings = moduleCliVendorWarningsIgnoredSince($warningsBeforeAll);
                fwrite(STDOUT, sprintf(
                    "module-runtime-sync: summary migrate=%s permissions-sync=%s build=%s assets-sync=%s vendor_warnings_ignored=%d\n",
                    $statusByStep['migrate'],
                    $statusByStep['permissions-sync'],
                    $statusByStep['build'],
                    $statusByStep['assets-sync'],
                    $totalVendorWarnings
                ));

                return $finalExitCode;
            }
        );
    });
}

if (PHP_SAPI === 'cli' && realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
    exit(moduleRuntimeSyncRun());
}
