<?php

declare(strict_types=1);

namespace SecurWP\Modules\Firewall\ExtendedProtection;

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

use SecurWP\Modules\Firewall\FirewallConfigService;
use SecurWP\Modules\Firewall\SearchTrust\SearchTrustScopeBuilder;

final class ConfigCoordinator {
	public static function refresh_if_installed(): void {
		if ( is_file( Manager::get_bootstrap_path() ) ) {
			ConfigWriter::write();
		}
	}

	public static function ensure_runtime_assets_current(): void {
		if ( ! is_file( Manager::get_bootstrap_path() ) ) {
			return;
		}

		Manager::ensure_bootstrap_current();

		if ( (string) get_option( 'securwp_waf_policy_signature', '' ) === '' || self::config_needs_refresh() ) {
			ConfigWriter::write( FirewallConfigService::load_runtime_effective_settings() );
		}
	}

	public static function config_needs_refresh(): bool {
		$config_path = Manager::get_config_path();
		if ( ! is_file( $config_path ) || ! is_readable( $config_path ) ) {
			return true;
		}

		$config = @include $config_path;
		if ( ! is_array( $config ) ) {
			return true;
		}

		$verification = is_array( $config['internal_verification'] ?? null ) ? $config['internal_verification'] : [];
		$secret = (string) ( $verification['secret'] ?? '' );
		$version = (string) ( $verification['version'] ?? '' );
		$window = (int) ( $verification['window'] ?? 0 );

		$scope = SearchTrustScopeBuilder::build_from_wordpress();
		$expected_scope_hash = (string) ( $scope['scope_hash'] ?? '' );
		$search_exception = is_array( $config['search_exception'] ?? null ) ? $config['search_exception'] : [];
		$stored_scope_hash = (string) ( $search_exception['scope_hash'] ?? '' );
		$effective_settings = FirewallConfigService::load_runtime_effective_settings();
		$expected_origin_mode = FirewallConfigService::get_origin_enforcement_mode( $effective_settings );
		$stored_origin_mode = (string) ( $config['origin_enforcement_mode'] ?? '' );

		$required_files = [
			(string) ( $config['engine_file'] ?? '' ),
			(string) ( $config['search_trust_core_file'] ?? '' ),
			(string) ( $config['search_trust_context_file'] ?? '' ),
			(string) ( $config['search_trust_dns_verifier_file'] ?? '' ),
		];

		foreach ( $required_files as $required_file ) {
			if ( $required_file === '' || ! is_file( $required_file ) || ! is_readable( $required_file ) ) {
				return true;
			}
		}

		return $secret === ''
			|| $version !== '1'
			|| $window < 1
			|| $stored_origin_mode === ''
			|| ! hash_equals( $expected_origin_mode, $stored_origin_mode )
			|| $expected_scope_hash === ''
			|| $stored_scope_hash === ''
			|| ! hash_equals( $expected_scope_hash, $stored_scope_hash );
	}
}
