<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit(1);
}

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/logger.php';
require_once __DIR__ . '/../src/storage.php';
require_once __DIR__ . '/../src/history.php';
require_once __DIR__ . '/../src/bitrix.php';
require_once __DIR__ . '/../src/crm.php';

$promptData = loadPromptsFromBitrixLists();
$lineIds = managedOpenLineIdsFromPromptData($promptData);
$botIds = normalizedConfiguredIds(
    config('MANAGED_OPEN_LINE_BOT_IDS', [config('BITRIX_OPENLINE_BOT_ID', '')])
);

if ($lineIds === [] || $botIds === []) {
    fwrite(STDERR, "Prompt lists must contain an open line id and MANAGED_OPEN_LINE_BOT_IDS must not be empty.\n");
    exit(1);
}

$allowedLineId = $lineIds[0];
$allowedBotId = $botIds[0];
$cases = [
    'managed_pair' => [
        'context' => ['open_line_id' => $allowedLineId, 'bot_id' => $allowedBotId],
        'expected' => true,
    ],
    'missing_line' => [
        'context' => ['open_line_id' => '', 'bot_id' => $allowedBotId],
        'expected' => false,
    ],
    'missing_bot' => [
        'context' => ['open_line_id' => $allowedLineId, 'bot_id' => ''],
        'expected' => false,
    ],
    'foreign_line' => [
        'context' => ['open_line_id' => '999999999', 'bot_id' => $allowedBotId],
        'expected' => false,
    ],
    'foreign_bot' => [
        'context' => ['open_line_id' => $allowedLineId, 'bot_id' => '999999999'],
        'expected' => false,
    ],
];

$failed = false;
$results = [];
foreach ($cases as $name => $case) {
    $scope = managedOpenLineBotScope($case['context']);
    $actual = ($scope['allowed'] ?? false) === true;
    $passed = $actual === $case['expected'];
    $failed = $failed || !$passed;
    $results[$name] = [
        'passed' => $passed,
        'scope' => $scope,
    ];
}

echo json_encode([
    'ok' => !$failed,
    'configured_line_ids' => $lineIds,
    'configured_bot_ids' => $botIds,
    'cases' => $results,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;

exit($failed ? 1 : 0);
