<?php

namespace WPProofShield\Security;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


use WPProofShield\Support\Settings;

final class ModeAdvisor {

	public function __construct(
		private Settings $settings,
		private StatsStore $stats
	) {
	}

	public function effectiveMode(): string {
		if ( ! $this->settings->isEnabled( 'enabled_auto_mode' ) ) {
			return $this->settings->mode();
		}

		return $this->recommendMode();
	}

	public function recommendMode(): string {
		$summary     = $this->summary();
		$blocked     = (int) $summary['blocked_24h'];
		$blockedRate = (float) $summary['blocked_rate_24h'];
		$load        = (int) $summary['system_load_percent'];

		$mode = 'relaxed';
		if ( $blocked >= 35 || $blockedRate >= 45.0 ) {
			$mode = 'balanced';
		}
		if ( $blocked >= 120 || $blockedRate >= 75.0 ) {
			$mode = 'strict';
		}

		if ( $load >= 85 ) {
			$mode = 'strict';
		} elseif ( $load >= 65 && $mode === 'relaxed' ) {
			$mode = 'balanced';
		}

		return $mode;
	}

	public function summary(): array {
		$dashboard   = $this->stats->getDashboard( '24h' );
		$recent      = $dashboard['recent_24h'] ?? array(
			'ok'      => 0,
			'blocked' => 0,
		);
		$ok          = (int) ( $recent['ok'] ?? 0 );
		$blocked     = (int) ( $recent['blocked'] ?? 0 );
		$total       = $ok + $blocked;
		$blockedRate = $total > 0 ? round( ( $blocked / $total ) * 100, 1 ) : 0.0;

		return array(
			'ok_24h'              => $ok,
			'blocked_24h'         => $blocked,
			'total_24h'           => $total,
			'blocked_rate_24h'    => $blockedRate,
			'system_load_percent' => $this->systemLoadPercent(),
		);
	}

	private function systemLoadPercent(): int {
		$load = 0.0;

		if ( function_exists( 'sys_getloadavg' ) ) {
			$values = sys_getloadavg();
			if ( is_array( $values ) && isset( $values[0] ) ) {
				$cpus = $this->cpuCount();
				$load = max( 0.0, ( (float) $values[0] / max( 1, $cpus ) ) * 100.0 );
			}
		}

		$memoryLoad = $this->memoryLoadPercent();
		$combined   = max( $load, $memoryLoad );

		return (int) max( 0, min( 100, round( $combined ) ) );
	}

	private function cpuCount(): int {
		$env = (int) getenv( 'NUMBER_OF_PROCESSORS' );
		if ( $env > 0 ) {
			return $env;
		}
		return 4;
	}

	private function memoryLoadPercent(): float {
		$limit = $this->memoryLimitBytes();
		if ( $limit <= 0 ) {
			return 0.0;
		}

		$usage = memory_get_usage( true );
		return max( 0.0, min( 100.0, ( $usage / $limit ) * 100.0 ) );
	}

	private function memoryLimitBytes(): int {
		$raw = trim( (string) ini_get( 'memory_limit' ) );
		if ( $raw === '' || $raw === '-1' ) {
			return 0;
		}

		$unit  = strtolower( substr( $raw, -1 ) );
		$value = (int) $raw;
		return match ( $unit ) {
			'g' => $value * 1024 * 1024 * 1024,
			'm' => $value * 1024 * 1024,
			'k' => $value * 1024,
			default => (int) $raw,
		};
	}
}
