<?php
/**
 * Centralized error handling and logging.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

/**
 * Handles error logging and reporting for the AgenticWP plugin.
 *
 * Provides centralized error handling with configurable logging levels
 * and integration with WordPress debugging tools.
 *
 * @package AgenticWP
 * @since 1.0.0
 */
final class Error_Handler {

	/**
	 * Logs an error message with context and additional data.
	 *
	 * @param string               $context Context identifier (e.g., 'api_call', 'database').
	 * @param string|\WP_Error     $message Error message or WP_Error object.
	 * @param array<string, mixed> $data    Additional context data.
	 */
	public static function log_error( string $context, string|\WP_Error $message, array $data = array() ): void {
		if ( is_wp_error( $message ) ) {
			$data['error_code'] = $message->get_error_code();
			$message            = $message->get_error_message();
		}

		$log = sprintf( '[AgenticWP][ERROR] %s: %s', $context, $message );

		if ( ! empty( $data ) ) {
			$log .= ' | ' . wp_json_encode( $data );
		}

		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional error logging in Error_Handler class.
		error_log( $log );
	}

	/**
	 * Logs a debug message with context when WP_DEBUG is enabled.
	 *
	 * @param string               $message Debug message.
	 * @param array<string, mixed> $context Additional context data.
	 */
	public static function debug_log( string $message, array $context = array() ): void {
		if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
			return;
		}

		$log = sprintf( '[AgenticWP][DEBUG] %s', $message );

		if ( ! empty( $context ) ) {
			$log .= ' | ' . wp_json_encode( $context );
		}

		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional debug logging in Error_Handler class.
		error_log( $log );
	}
}
