<?php

namespace FleekDash\Core;

use FleekDash\Core\ResourceBlocker\BlockerContext;
use FleekDash\Core\ResourceBlocker\InlineGuard;
use FleekDash\Core\ResourceBlocker\QueueGuard;

if (!function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

class ResourceBlocker
{
    private BlockerContext $context;
    private QueueGuard $queueGuard;
    private InlineGuard $inlineGuard;

    /**
     * @param array{
     *     allowed_styles?: array<int, string>,
     *     allowed_scripts?: array<int, string>,
     *     condition?: callable,
     *     block_patterns?: array<int, string>,
     *     block_third_party?: bool,
     *     allowed_paths?: array<int, string>
     * } $config
     */
    public function __construct(array $config = [])
    {
        $this->context = new BlockerContext($config);
        $this->queueGuard = new QueueGuard($this->context);
        $this->inlineGuard = new InlineGuard($this->context);

        $this->initHooks();
    }

    public function addBlockPattern(string $pattern): self
    {
        $this->context->addBlockPattern($pattern);
        return $this;
    }

    public function addBlockPatterns(array $patterns): self
    {
        $this->context->addBlockPatterns($patterns);
        return $this;
    }

    public function removeBlockPattern(string $pattern): self
    {
        $this->context->removeBlockPattern($pattern);
        return $this;
    }

    public function getBlockPatterns(): array
    {
        return $this->context->getBlockPatterns();
    }

    private function initHooks(): void
    {
        \add_action('init', [$this->queueGuard, 'preventResourceLoading'], 1);
        \add_action('admin_init', [$this->queueGuard, 'dequeueResources'], 1);
        \add_filter('print_styles_array', [$this->queueGuard, 'filterPrintStyles'], 100);
        \add_action('admin_enqueue_scripts', [$this->queueGuard, 'purgeLateQueuedResources'], 9999);

        // Block CartFlows admin_print_styles hook that directly outputs load-styles.php
        \add_action('admin_print_styles', [$this->queueGuard, 'blockCartFlowsAdminStyles'], 0);

        \add_action('admin_head', [$this->inlineGuard, 'blockInlineScripts'], 1);
        \add_action('admin_print_scripts', [$this->inlineGuard, 'blockInlineScripts'], 1);
        \add_action('admin_print_footer_scripts', [$this->inlineGuard, 'blockInlineScripts'], 1);
        \add_action('admin_head', [$this->inlineGuard, 'addJQueryPolyfill'], 0);

        // \add_action('admin_head', [$this->inlineGuard, 'startContentFiltering'], 0);
        // \add_action('admin_footer', [$this->inlineGuard, 'stopContentFiltering'], 999);

        \add_action('admin_head', [$this->inlineGuard, 'implementComprehensiveBlocking'], 0);
    }
}
