<?php
// Lightweight bootstrap for CLI execution without full index.php
if (!defined('WD')) {
    define('WD', __DIR__ . '/../../');
}

require_once WD . 'traits/module_config_variable_t.php';
require_once WD . 'traits/module_config_t.php';
require_once WD . 'classes/selfserve.php';
require_once WD . 'modules/selfserve/classes/selfserve_lane.php';
require_once WD . 'modules/selfserve/helpers/selfserve_lane_relay.php';
require_once WD . 'modules/selfserve/helpers/selfserve_lane_state.php';
require_once WD . 'modules/selfserve/helpers/selfserve_lane_status.php';

use classes\selfserve;

function ok($message): void { echo "\n\033[32m✔ $message\033[0m\n"; }
function warn($message): void { echo "\n\033[33m! $message\033[0m\n"; }
function fail($message): void { echo "\n\033[31m✖ $message\033[0m\n"; }

echo "\nForceMachineRelayBypassTest starting...\n";

$selfserve = new selfserve();

// Use lane 1 for test purposes (must exist in the test environment)
$laneId = 1;
$lane = $selfserve->lane($laneId);

// Clear allowed services to simulate a state where MACHINE would normally be gated
try {
    $lane->setLaneCache($laneId, $lane::CACHE_SELFSERVE_LANE_KEY_ALLOWED_SERVICES, []);
    ok('Cleared allowed services for lane ' . $laneId);
} catch (Exception $e) {
    fail('Failed to clear allowed services: ' . $e->getMessage());
}

// Ensure lane is not in a clearly invalid status (CLOSED/MAINTENANCE/FAULT)
try {
    // If lane reports CLOSED/MAINTENANCE/FAULT here, this is an environment/setup issue for the test
    $status = $lane->getLaneStatus();
    if (in_array($status->name, ['CLOSED', 'MAINTENANCE', 'FAULT'], true)) {
        warn('Lane is in status ' . $status->name . ' — force method will refuse as designed. Skipping state assertions.');
    }
} catch (Exception $e) {
    // Non-fatal for this test
}

// Call the force bypass method; we expect it to bypass the allowed-services gating.
// Any hardware/network/module config error after that is acceptable in test env.
$bypassedGating = false;
try {
    $lane->forceTurnOnMachineRelay(1); // 1s auto-off if hardware honors it
    $bypassedGating = true;
    warn('forceTurnOnMachineRelay returned without exception. Assuming environment allowed a real toggle.');
} catch (Exception $e) {
    if (stripos($e->getMessage(), 'not allowed') !== false) {
        fail('Bypass did not work: received a gating "not allowed" error');
    } else {
        ok('Bypass reached hardware/network layer (non-gating error acceptable in tests): ' . $e->getMessage());
        $bypassedGating = true;
    }
}

if ($bypassedGating) {
    ok('ForceMachineRelayBypassTest completed successfully.');
} else {
    fail('ForceMachineRelayBypassTest did not confirm bypass behavior.');
}

echo "\nForceMachineRelayBypassTest finished.\n";
