<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/config.php';

$options = getopt('', ['deal-ids:']);
$dealIds = array_values(array_filter(array_map(
    static fn(string $value): string => trim($value),
    explode(',', (string) ($options['deal-ids'] ?? ''))
)));

if ($dealIds === []) {
    fwrite(STDERR, "Usage: php tools/diagnose_branch_notifications.php --deal-ids=123,456\n");
    exit(1);
}

$logFile = (string) config('LOG_FILE', __DIR__ . '/../storage/logs/app.log');
$handle = @fopen($logFile, 'rb');
if ($handle === false) {
    fwrite(STDERR, "Cannot read log file: {$logFile}\n");
    exit(1);
}

$events = array_fill_keys($dealIds, []);
$interestingMessages = [
    'CRM deal fields updated from AI extraction',
    'CRM sync failed',
    'Undefined branch notification sent',
    'Undefined branch notification failed',
];

while (($line = fgets($handle)) !== false) {
    $entry = json_decode($line, true);
    if (!is_array($entry) || !in_array((string) ($entry['message'] ?? ''), $interestingMessages, true)) {
        continue;
    }

    $context = is_array($entry['context'] ?? null) ? $entry['context'] : [];
    $dealId = firstDealId($context);
    if ($dealId === '' || !array_key_exists($dealId, $events)) {
        continue;
    }

    $events[$dealId][] = [
        'time' => $entry['time'] ?? null,
        'level' => $entry['level'] ?? null,
        'message' => $entry['message'] ?? null,
        'extracted' => $context['extracted'] ?? null,
        'fields' => $context['fields'] ?? null,
        'city_match' => compactMatch($context['city_match'] ?? null),
        'branch_match' => compactMatch($context['branch_match'] ?? null),
        'branch_notification' => $context['branch_notification'] ?? null,
        'error' => $context['error'] ?? null,
        'result' => $context['result'] ?? null,
    ];
}
fclose($handle);

echo json_encode([
    'config' => [
        'enabled' => (bool) config('UNDEFINED_BRANCH_NOTIFICATION_ENABLED', true),
        'dialog_id' => (string) config('UNDEFINED_BRANCH_NOTIFICATION_DIALOG_ID', 'chat985965'),
        'bot_id' => (int) config('UNDEFINED_BRANCH_NOTIFICATION_BOT_ID', 0),
    ],
    'deals' => $events,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;

function firstDealId(array $context): string
{
    $candidates = [
        $context['deal_id'] ?? null,
        $context['context']['deal_id'] ?? null,
        $context['crm_sync']['deal_id'] ?? null,
    ];

    foreach ($candidates as $candidate) {
        if (is_scalar($candidate) && trim((string) $candidate) !== '') {
            return trim((string) $candidate);
        }
    }

    return '';
}

function compactMatch($match)
{
    if (!is_array($match)) {
        return $match;
    }

    return array_intersect_key($match, array_flip(['id', 'value', 'label', 'match', 'score']));
}
