<?php
declare(strict_types=1);

namespace Celena\Core;

/**
 * Файловый логгер с уровнями PSR-3.
 * Пишет в storage/logs/celena-YYYY-MM-DD.log
 */
final class Logger
{
    private const LEVELS = [
        'debug' => 0, 'info' => 1, 'notice' => 2, 'warning' => 3,
        'error' => 4, 'critical' => 5, 'alert' => 6, 'emergency' => 7,
    ];

    public function __construct(
        private readonly string $logDir,
        private readonly string $minLevel = 'warning',
    ) {
    }

    public function emergency(string $msg, array $ctx = []): void { $this->log('emergency', $msg, $ctx); }
    public function alert(string $msg, array $ctx = []): void     { $this->log('alert', $msg, $ctx); }
    public function critical(string $msg, array $ctx = []): void  { $this->log('critical', $msg, $ctx); }
    public function error(string $msg, array $ctx = []): void     { $this->log('error', $msg, $ctx); }
    public function warning(string $msg, array $ctx = []): void   { $this->log('warning', $msg, $ctx); }
    public function notice(string $msg, array $ctx = []): void    { $this->log('notice', $msg, $ctx); }
    public function info(string $msg, array $ctx = []): void      { $this->log('info', $msg, $ctx); }
    public function debug(string $msg, array $ctx = []): void     { $this->log('debug', $msg, $ctx); }

    public function log(string $level, string $message, array $context = []): void
    {
        $level = strtolower($level);
        if ((self::LEVELS[$level] ?? -1) < (self::LEVELS[$this->minLevel] ?? 0)) {
            return;
        }
        if (!is_dir($this->logDir)) {
            @mkdir($this->logDir, 0755, true);
        }
        $file = $this->logDir . '/celena-' . date('Y-m-d') . '.log';
        $time = date('Y-m-d H:i:s');
        $ctx = $context !== [] ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : '';
        $line = "[$time] [$level] $message$ctx" . PHP_EOL;
        @file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
    }
}
