<?php

declare(strict_types=1);

namespace App\Framework\MachineLearning\ModelManagement;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

/**
 * Log-based Alerting Service
 *
 * Simple alerting implementation that logs alerts to PSR-3 logger.
 * For production, replace with email/Slack/PagerDuty integration.
 */
final readonly class LogAlertingService implements AlertingService
{
    public function __construct(
        private ?LoggerInterface $logger = null
    ) {}

    public function sendAlert(
        string $level,
        string $title,
        string $message,
        array $data = []
    ): void {
        if ($this->logger === null) {
            // Fallback to error_log if no logger available
            $this->logToErrorLog($level, $title, $message, $data);
            return;
        }

        $logLevel = $this->mapAlertLevelToLogLevel($level);

        $context = [
            'alert_title' => $title,
            'alert_level' => $level,
            'alert_data' => $data,
        ];

        $this->logger->log($logLevel, $message, $context);
    }

    /**
     * Map alert level to PSR-3 log level
     */
    private function mapAlertLevelToLogLevel(string $alertLevel): string
    {
        return match (strtolower($alertLevel)) {
            'critical' => LogLevel::CRITICAL,
            'warning' => LogLevel::WARNING,
            'info' => LogLevel::INFO,
            default => LogLevel::NOTICE,
        };
    }

    /**
     * Fallback logging to error_log
     */
    private function logToErrorLog(
        string $level,
        string $title,
        string $message,
        array $data
    ): void {
        $logMessage = sprintf(
            '[%s] %s: %s',
            strtoupper($level),
            $title,
            $message
        );

        if (!empty($data)) {
            $logMessage .= ' | Data: ' . json_encode($data);
        }

        error_log($logMessage);
    }
}
