#!/usr/bin/env php
<?php
/**
 * kiri-crontab 独立运行入口脚本
 *
 * 使用方式:
 *   php bin/crontab start      启动调度器
 *   php bin/crontab stop       停止调度器
 *   php bin/crontab restart    重启调度器
 *   php bin/crontab status     查看状态
 *
 * 任务定义方式:
 *   1. 配置文件: config/crontab.php 的 tasks 中声明
 *   2. 注解自动扫描: 在任务类上使用 #[Crontab] 注解
 *
 * CrontabProcess 启动时会自动完成配置任务注册和注解扫描
 */
declare(strict_types=1);

// 自动加载
$autoloadFiles = [
    __DIR__ . '/../vendor/autoload.php',
    __DIR__ . '/../../../vendor/autoload.php',
    __DIR__ . '/../../autoload.php',
];

$autoloadPath = null;
foreach ($autoloadFiles as $file) {
    if (file_exists($file)) {
        $autoloadPath = $file;
        break;
    }
}

if ($autoloadPath === null) {
    fwrite(STDERR, "未找到 autoload.php，请先执行 composer install" . PHP_EOL);
    exit(1);
}

require $autoloadPath;

use Kiri\Crontab\CrontabCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;

// 解析命令行参数
$args   = $argv;
$script = array_shift($args);
$action = array_shift($args) ?: 'status';

// 查找配置文件，获取 PID 文件路径
$configFiles = [
    getcwd() . '/config/crontab.php',
    __DIR__ . '/../config/crontab.php',
];
$configPath = null;
foreach ($configFiles as $file) {
    if (file_exists($file)) {
        $configPath = $file;
        break;
    }
}

if ($configPath === null) {
    fwrite(STDERR, "未找到配置文件 config/crontab.php" . PHP_EOL);
    exit(1);
}

$config = require $configPath;

if (!is_array($config)) {
    fwrite(STDERR, "配置文件格式错误" . PHP_EOL);
    exit(1);
}

// PID 文件路径
$pidFile = $config['scheduler']['pid_file'] ?? (getcwd() . '/storage/crontab.pid');

// 创建 Console Application 并执行
$application = new Application('kiri-crontab', '1.0.0');
$application->setAutoExit(false);

$command = new CrontabCommand($pidFile);
$command->setName('crontab');
$application->add($command);

$input  = new ArgvInput(['crontab', $action]);
$output = new ConsoleOutput();

$exitCode = $application->run($input, $output);
exit($exitCode);
