<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') exit(1);
require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/storage.php';
require_once __DIR__ . '/../src/logger.php';
require_once __DIR__ . '/../src/history.php';
require_once __DIR__ . '/../src/bitrix.php';
require_once __DIR__ . '/../src/bitrix_bot.php';
require_once __DIR__ . '/../src/crm.php';

$options = getopt('', ['deal-id:']);
$dealId = normalizeCrmId($options['deal-id'] ?? '');
if ($dealId === '') {
    fwrite(STDERR, "Usage: php tools/check_qualification_assignment.php --deal-id=123\n");
    exit(1);
}
try {
    $response = bitrixCall('crm.deal.get', ['id' => $dealId]);
    $deal = (array) ($response['result'] ?? []);
    if ((string) ($deal['ID'] ?? '') !== $dealId) throw new RuntimeException('Deal not returned by REST.');
    $state = getQualificationWorkflowState([], $dealId);
    $assignedId = (string) ($deal['ASSIGNED_BY_ID'] ?? '');
    $assignedIsBot = in_array($assignedId, configuredBitrixBotIds(), true);
    echo json_encode([
        'ok' => true, 'deal_id' => $dealId,
        'category_id' => $deal['CATEGORY_ID'] ?? null, 'stage_id' => $deal['STAGE_ID'] ?? null,
        'branch_value' => $deal[(string) config('DEAL_BRANCH_FIELD', 'UF_CRM_1764919997')] ?? null,
        'assigned_by_id' => $assignedId, 'assigned_is_configured_bot' => $assignedIsBot,
        'workflow_status' => $state['status'] ?? 'unknown',
        'workflow_started_at' => $state['started_at'] ?? null,
        'workflow_id' => $state['result']['response']['result'] ?? null,
        'needs_assignment_review' => $assignedId === '' || $assignedId === '0' || $assignedIsBot,
        'note' => 'A successful workflow start is not proof of completion or assignment. This check does not restart workflows or change deals.',
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (Throwable $exception) {
    fwrite(STDERR, $exception->getMessage() . PHP_EOL);
    exit(1);
}
