<?php

declare(strict_types=1);

namespace BotGuard\Core;

/**
 * Lightweight PSR-3-flavoured file logger.
 *
 * Writes newline-delimited JSON to daily log files under storage/logs so log
 * lines are both human-readable and machine-parseable. Not a full PSR-3
 * implementation, but exposes the familiar level methods.
 */
final class Logger
{
    public function __construct(private string $directory)
    {
        if (! is_dir($this->directory)) {
            @mkdir($this->directory, 0775, true);
        }
    }

    public function emergency(string $message, array $context = []): void
    {
        $this->log('emergency', $message, $context);
    }

    public function error(string $message, array $context = []): void
    {
        $this->log('error', $message, $context);
    }

    public function warning(string $message, array $context = []): void
    {
        $this->log('warning', $message, $context);
    }

    public function info(string $message, array $context = []): void
    {
        $this->log('info', $message, $context);
    }

    public function debug(string $message, array $context = []): void
    {
        $this->log('debug', $message, $context);
    }

    /**
     * @param array<string, mixed> $context
     */
    public function log(string $level, string $message, array $context = []): void
    {
        $record = [
            'time'    => now(),
            'level'   => $level,
            'message' => $message,
            'context' => $context,
        ];

        $line = json_encode($record, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
        $file = $this->directory . DIRECTORY_SEPARATOR . 'app-' . date('Y-m-d') . '.log';

        @file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
    }
}
