<?php
/**
 * Results Analyzer Class
 *
 * Analyzes speed test results and generates recommendations.
 *
 * @package MaplePress_SearchSpeedTest
 */

class MPSS_Results_Analyzer {

	/**
	 * Analyze speed test results.
	 *
	 * @param array $all_results All profile results.
	 * @return array Analyzed results with summary and recommendations.
	 */
	public function analyze( $all_results ) {
		$summary = array();

		foreach ( $all_results as $profile_key => $data ) {
			$times = array_column( $data['results'], 'duration_ms' );

			if ( empty( $times ) ) {
				continue;
			}

			$avg_ms = array_sum( $times ) / count( $times );

			$summary[ $profile_key ] = array(
				'profile_name' => $data['profile']['name'],
				'query_count'  => count( $data['results'] ),
				'avg_ms'       => round( $avg_ms, 2 ),
				'min_ms'       => round( min( $times ), 2 ),
				'max_ms'       => round( max( $times ), 2 ),
				'median_ms'    => $this->median( $times ),
				'p95_ms'       => $this->percentile( $times, 95 ),
				'p99_ms'       => $this->percentile( $times, 99 ),
				'status'       => $this->get_status( $avg_ms ),
			);
		}

		return array(
			'summary'         => $summary,
			'recommendations' => $this->generate_recommendations( $summary ),
		);
	}

	/**
	 * Calculate median of an array.
	 *
	 * @param array $array Numeric array.
	 * @return float Median value.
	 */
	private function median( $array ) {
		sort( $array );
		$count  = count( $array );
		$middle = floor( $count / 2 );

		if ( $count % 2 === 0 ) {
			return round( ( $array[ $middle - 1 ] + $array[ $middle ] ) / 2, 2 );
		}

		return round( $array[ $middle ], 2 );
	}

	/**
	 * Calculate percentile of an array.
	 *
	 * @param array $array      Numeric array.
	 * @param int   $percentile Percentile to calculate (e.g., 95 for P95).
	 * @return float Percentile value.
	 */
	private function percentile( $array, $percentile ) {
		sort( $array );
		$index = ceil( ( $percentile / 100 ) * count( $array ) ) - 1;
		$index = max( 0, $index );
		return round( $array[ $index ], 2 );
	}

	/**
	 * Get performance status based on average response time.
	 *
	 * @param float $avg_ms Average response time in milliseconds.
	 * @return string Status (excellent, good, fair, poor, critical).
	 */
	private function get_status( $avg_ms ) {
		if ( $avg_ms < 50 ) {
			return 'excellent';
		} elseif ( $avg_ms < 150 ) {
			return 'good';
		} elseif ( $avg_ms < 500 ) {
			return 'fair';
		} elseif ( $avg_ms < 1000 ) {
			return 'poor';
		} else {
			return 'critical';
		}
	}

	/**
	 * Get current site information.
	 *
	 * @return array Site information.
	 */
	private function get_site_info() {
		$post_count = wp_count_posts( 'post' );
		$page_count = wp_count_posts( 'page' );

		$published_posts = isset( $post_count->publish ) ? $post_count->publish : 0;
		$published_pages = isset( $page_count->publish ) ? $page_count->publish : 0;

		$total_content = $published_posts + $published_pages;

		// Determine profile
		if ( $total_content < 50 ) {
			$profile = 'tiny';
		} elseif ( $total_content < 500 ) {
			$profile = 'small';
		} elseif ( $total_content < 5000 ) {
			$profile = 'medium';
		} elseif ( $total_content < 50000 ) {
			$profile = 'big';
		} else {
			$profile = 'gigantic';
		}

		return array(
			'posts'         => $published_posts,
			'pages'         => $published_pages,
			'total_content' => $total_content,
			'profile'       => $profile,
		);
	}

	/**
	 * Generate actionable recommendations based on results.
	 *
	 * @param array $summary Profile summaries.
	 * @return array Recommendations array.
	 */
	private function generate_recommendations( $summary ) {
		$recommendations = array();

		// Get the actual test results (could be 'custom' or any profile key)
		$test_result = reset( $summary );
		if ( ! $test_result ) {
			return $recommendations;
		}

		$avg_ms = $test_result['avg_ms'];

		// Performance-based recommendations
		if ( $avg_ms < 50 ) {
			$recommendations[] = array(
				'level'   => 'success',
				'title'   => __( 'Excellent Performance', 'maplepress-searchspeedtest' ),
				'message' => sprintf(
					/* translators: %s: average response time */
					__( 'Average response time of %.2f ms is excellent! Your search is performing very well.', 'maplepress-searchspeedtest' ),
					$avg_ms
				),
			);
		} elseif ( $avg_ms < 150 ) {
			$recommendations[] = array(
				'level'   => 'success',
				'title'   => __( 'Good Performance', 'maplepress-searchspeedtest' ),
				'message' => sprintf(
					/* translators: %s: average response time */
					__( 'Average response time of %.2f ms is good. Your search is performing well.', 'maplepress-searchspeedtest' ),
					$avg_ms
				),
			);
		} elseif ( $avg_ms < 500 ) {
			$recommendations[] = array(
				'level'   => 'warning',
				'title'   => __( 'Fair Performance - Room for Improvement', 'maplepress-searchspeedtest' ),
				'message' => sprintf(
					/* translators: %s: average response time */
					__( 'Average response time of %.2f ms is acceptable but could be improved. Consider implementing search caching or optimizing your database queries.', 'maplepress-searchspeedtest' ),
					$avg_ms
				),
			);
		} elseif ( $avg_ms < 1000 ) {
			$recommendations[] = array(
				'level'   => 'error',
				'title'   => __( 'Poor Performance', 'maplepress-searchspeedtest' ),
				'message' => sprintf(
					/* translators: %s: average response time */
					__( 'Average response time of %.2f ms indicates performance issues. Consider database optimization, adding indexes, or using a dedicated search solution.', 'maplepress-searchspeedtest' ),
					$avg_ms
				),
			);
		} else {
			$recommendations[] = array(
				'level'   => 'critical',
				'title'   => __( 'Critical: Very Slow Performance', 'maplepress-searchspeedtest' ),
				'message' => sprintf(
					/* translators: %s: average response time */
					__( 'Average response time of %.2f ms is critically slow. Your database may need optimization, or you should consider a cloud-based search solution like MaplePress.', 'maplepress-searchspeedtest' ),
					$avg_ms
				),
			);
		}

		// Add database optimization tip if showing slowness
		if ( $avg_ms > 200 ) {
			$recommendations[] = array(
				'level'   => 'info',
				'title'   => __( 'Database Optimization Tip', 'maplepress-searchspeedtest' ),
				'message' => __( 'Consider adding database indexes on post_title and post_content columns, implementing search result caching, or using a cloud-based search solution like MaplePress for better performance.', 'maplepress-searchspeedtest' ),
			);
		}

		// Add general optimization tips
		$recommendations[] = array(
			'level'   => 'info',
			'title'   => __( 'Optimization Tips', 'maplepress-searchspeedtest' ),
			'message' => __( 'Consider: 1) Implementing search result caching, 2) Adding database indexes on post_title and post_content, 3) Using a CDN, 4) Upgrading server resources, 5) Trying MaplePress for cloud-powered search.', 'maplepress-searchspeedtest' ),
		);

		return $recommendations;
	}
}
