<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "This script can be run only from CLI.\n";
    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/openai.php';
require_once __DIR__ . '/../src/crm.php';

$options = getopt('', ['deal-id:', 'message:', 'dialog-id::', 'chat-id::', 'open-line-id::', 'bot-id::', 'dry-run', 'help']);
if (isset($options['help']) || empty($options['deal-id']) || empty($options['message'])) {
    echo "Usage: php tools/test_deal_contact_sync.php --deal-id=123 --message=\"Телефон +79990000000, город Казань\" [--open-line-id=227] [--dry-run]\n";
    exit(isset($options['help']) ? 0 : 1);
}

$managedLineIds = managedOpenLineIdsFromPrompts();
$context = [
    'deal_id' => (string) $options['deal-id'],
    'dialog_id' => (string) ($options['dialog-id'] ?? 'test-sync'),
    'chat_id' => (string) ($options['chat-id'] ?? ''),
    'open_line_id' => (string) ($options['open-line-id'] ?? ($managedLineIds[0] ?? '')),
    'bot_id' => (string) ($options['bot-id'] ?? config('BITRIX_OPENLINE_BOT_ID', '')),
];

try {
    if (isset($options['dry-run'])) {
        $extracted = extractDealContactFields((string) $options['message'], $context);
        $cityItems = getDealUserFieldEnumItems((string) config('DEAL_CITY_FIELD', 'UF_CRM_1693995123245'));
        $cityMatch = matchDealCityEnumValue((string) ($extracted['city'] ?? ''), $cityItems);
        $branchItems = getDealUserFieldEnumItems((string) config('DEAL_BRANCH_FIELD', 'UF_CRM_1764919997'));
        $branchMatch = matchDealBranchEnumValue((string) ($extracted['branch'] ?? ''), $branchItems);

        echo json_encode([
            'context' => $context,
            'extracted' => $extracted,
            'normalized_phone' => normalizePhoneForDeal((string) ($extracted['phone'] ?? '')),
            'normalized_full_name' => normalizeClientFullName((string) ($extracted['full_name'] ?? '')),
            'normalized_interest_group' => normalizeInterestGroup($extracted['interest_group'] ?? ''),
            'normalized_branch' => normalizeBranchName($extracted['branch'] ?? ''),
            'city_match' => $cityMatch,
            'branch_match' => $branchMatch,
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
        exit(0);
    }

    $result = syncDealFieldsFromConversation((string) $options['message'], $context);
    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $exception) {
    fwrite(STDERR, $exception->getMessage() . PHP_EOL);
    exit(1);
}
