<?php

declare(strict_types=1);

namespace RedMCP;

final class McpDebugLogger
{
    private ?string $path;

    public function __construct(?string $path)
    {
        $this->path = $path;
    }

    public function enabled(): bool
    {
        return $this->path !== null && $this->path !== '';
    }

    /**
     * @param array<string,mixed> $record
     */
    public function log(array $record): void
    {
        if (!$this->enabled()) {
            return;
        }

        $record = ['timestamp' => gmdate('c')] + $record;
        $encoded = json_encode($record, JSON_UNESCAPED_SLASHES);
        if ($encoded === false) {
            return;
        }

        $dir = dirname((string) $this->path);
        if ($dir !== '' && $dir !== '.' && !is_dir($dir)) {
            mkdir($dir, 0775, true);
        }

        file_put_contents((string) $this->path, $encoded . "\n", FILE_APPEND | LOCK_EX);
    }
}
