<?php

declare(strict_types=1);

namespace app\admin\command;

use app\common\service\SplitCronLockService;
use app\common\service\SplitTicketSyncLogger;
use app\common\service\SplitTicketSyncService;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

/**
 * 工单云控定时同步 CLI
 *
 * 用法：
 *   php think split:sync-tickets
 *   php think split:sync-tickets --ticket=12
 */
class SplitSyncTickets extends Command
{
    protected function configure(): void
    {
        $this->setName('split:sync-tickets')
            ->addOption('ticket', 't', Option::VALUE_OPTIONAL, '指定工单 ID（强制同步，忽略周期）', '')
            ->setDescription('同步分流工单云控数据');
    }

    protected function execute(Input $input, Output $output): void
    {
        set_time_limit(0);
        SplitTicketSyncLogger::log('cli', 'command start', [
            'ticketOption' => trim((string) $input->getOption('ticket')),
            'appDebug'     => SplitTicketSyncLogger::isEnabled(),
        ]);
        $service = new SplitTicketSyncService();
        $ticketId = trim((string) $input->getOption('ticket'));

        if ($ticketId !== '' && ctype_digit($ticketId)) {
            $result = $service->syncOne((int) $ticketId, true);
            if (!empty($result['skipped'])) {
                $output->writeln('<comment>跳过: ' . ($result['message'] ?? '') . '</comment>');
                return;
            }
            if ($result['success']) {
                $output->writeln('<info>工单 #' . $ticketId . ' 同步成功</info>');
            } else {
                $output->writeln('<error>工单 #' . $ticketId . ' 同步失败: ' . ($result['message'] ?? '') . '</error>');
            }
            return;
        }

        $cronLock = new SplitCronLockService();
        if (!$cronLock->acquire()) {
            SplitTicketSyncLogger::log('cli', 'cron lock busy, skip');
            $output->writeln('<comment>上一轮同步仍在执行，跳过本次</comment>');
            return;
        }

        try {
            $count = $service->syncDueTickets();
            $output->writeln('<info>本次处理工单数: ' . $count . '</info>');
            $output->writeln('<comment>汇总日志已写入 runtime/log/split_sync.log</comment>');
        } finally {
            $cronLock->release();
        }

        if (SplitTicketSyncLogger::isEnabled()) {
            $output->writeln('<comment>详细调试日志已写入 runtime/log/split_sync.log</comment>');
        }
    }
}
