<?php
/**
 * Bundled minimal Monolog PsrLogMessageProcessor.
 *
 * Substitutes {placeholder} tokens in log messages with values from context.
 * BlackRed code uses interpolation rarely; this is included for compatibility.
 *
 * Original: https://github.com/Seldaek/monolog (MIT)
 */

declare(strict_types=1);

namespace Monolog\Processor;

final class PsrLogMessageProcessor
{
    /**
     * @param array<string, mixed> $record
     * @return array<string, mixed>
     */
    public function __invoke(array $record): array
    {
        if (!isset($record['message']) || !is_string($record['message'])) {
            return $record;
        }
        if (!str_contains($record['message'], '{')) {
            return $record;
        }
        $context = $record['context'] ?? [];
        if (!is_array($context) || empty($context)) {
            return $record;
        }

        $replacements = [];
        foreach ($context as $key => $value) {
            $placeholder = '{' . $key . '}';
            if (str_contains($record['message'], $placeholder)) {
                $replacements[$placeholder] = is_scalar($value) || $value === null
                    ? (string)($value ?? '')
                    : '[' . gettype($value) . ']';
            }
        }
        if (!empty($replacements)) {
            $record['message'] = strtr($record['message'], $replacements);
        }
        return $record;
    }
}
