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

/**
 * Task Engine CLI Entry Point
 *
 * Provides command-line interface for the Task Engine:
 * - scheduler:run     Run one scheduler cycle (invoked by cron)
 * - worker:start      Start a single worker process
 * - worker:manager    Start the worker manager (spawns/monitors workers)
 * - job:dispatch      Manually dispatch a job
 * - job:list          List job definitions
 * - queue:status      Show queue depths
 *
 * Usage:
 *   php userfrosting/bin/task scheduler:run
 *   php userfrosting/bin/task worker:start
 *   php userfrosting/bin/task worker:manager [--daemon]
 *   php userfrosting/bin/task job:dispatch <job-name> [--store=<typeNum>]
 *   php userfrosting/bin/task job:list [--enabled] [--scheduled]
 *   php userfrosting/bin/task queue:status [--detailed]
 */

// Prevent web access
if (php_sapi_name() !== 'cli') {
    die('This script must be run from the command line.');
}

// Set SERVER_NAME for Slim 2 CLI compatibility
if (!isset($_SERVER['SERVER_NAME'])) {
    $_SERVER['SERVER_NAME'] = 'localhost';
}

// Load .env files: root first, then userfrosting/.env (which can override)
$envFiles = [
    dirname(__DIR__, 2) . '/.env',   // /home/bkweb/.env (project root)
    dirname(__DIR__) . '/.env',       // /home/bkweb/userfrosting/.env (local overrides)
];
foreach ($envFiles as $envFile) {
    if (file_exists($envFile)) {
        foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
            if (strpos($line, '#') === 0 || strpos($line, '=') === false) continue;
            [$key, $value] = array_map('trim', explode('=', $line, 2));
            $value = trim($value, '"\'');
            $_ENV[$key] = $value;
            putenv("$key=$value");
        }
    }
}

// Set up error reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Mark this as a TaskEngine worker context
// Workers are long-running, so we disable persistent DB connections to prevent
// connection accumulation (workers would hold connections to every store they ever touched)
define('TASKENGINE_WORKER_CONTEXT', true);

// Ensure Slim environment bootstrap has required server keys in CLI context
$_SERVER['REQUEST_METHOD'] ??= 'CLI';
$_SERVER['REMOTE_ADDR'] ??= '127.0.0.1';
$_SERVER['REQUEST_URI'] ??= '/';

// Change to the userfrosting directory for proper path resolution
$ufDir = dirname(__DIR__);
chdir($ufDir);

// Load the application bootstrap (initializes autoloading, environment, DB connections)
require_once $ufDir . '/initialize.php';

// Build the command handler using the factory
$command = \BuyerKiosk\TaskEngine\Commands\TaskCommandFactory::create();

// Run the command with CLI arguments
$exitCode = $command->run($argv);

exit($exitCode);
