<?php

/**
 * Readability Module
 *
 * @package ProRank\SEO\Modules\Content
 * @since   0.1.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Modules\Content;

use ProRank\SEO\Modules\BaseModule;
use WP_REST_Request;
use WP_REST_Response;

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


/**
 * Readability module class
 */


class ReadabilityModule extends BaseModule {
    
    /**
     * Module slug
     *
     * @var string
     */
    protected string $slug = 'readability-analysis';
    
    /**
     * Module name
     *
     * @var string
     */
    protected string $name = 'Readability';
    
    /**
     * Module description
     *
     * @var string
     */
    protected string $description = 'Analyze content readability and SEO optimization';
    
    /**
     * Required tier
     *
     * @var string
     */
    protected string $feature_tier = 'free';
    
    /**
     * Parent module
     *
     * @var string|null
     */
    protected ?string $parent_slug = 'on-page-seo';
    
    /**
     * Readability instance
     *
     * @var Readability|null
     */
    private ?Readability $readability = null;
    
    /**
     * Initialize module hooks
     *
     * @return void
     */
    public function init_hooks(): void {
        if (!$this->is_enabled()) {
            return;
        }
        
        // Initialize readability analysis
        $this->readability = new Readability();
        
        // Add hooks for readability analysis
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('rest_api_init', [$this, 'register_rest_routes']);
    }
    
    /**
     * Enqueue module assets
     *
     * @param string $hook Current admin page hook
     * @return void
     */
    public function enqueue_assets(string $hook): void {
        if (!in_array($hook, ['post.php', 'post-new.php'], true)) {
            return;
        }
        
        // The readability functionality is included in the sidebar.js bundle
        // which is enqueued by the editor integration
    }
    
    /**
     * Register REST routes
     *
     * @return void
     */
    public function register_rest_routes(): void {
        // Register the ReadabilityController
        if (class_exists('\ProRank\SEO\Core\RestApi\ReadabilityController')) {
            $controller = new \ProRank\SEO\Core\RestApi\ReadabilityController();
            $controller->register_routes();
        }
        
        // Also register the old endpoint for backward compatibility
        register_rest_route(
            'prorank-seo/v1',
            '/readability/analyze',
            [
                'methods' => 'POST',
                'callback' => [$this, 'analyze_content'],
                'permission_callback' => function() {
                    return current_user_can('edit_posts');
                },
            ]
        );
    }

    /**
     * Backward-compatible readability analyzer.
     *
     * Supports legacy POST /readability/analyze payloads.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response
     */
    public function analyze_content(WP_REST_Request $request): WP_REST_Response {
        $content = (string) $request->get_param('content');
        $post_id = absint((string) $request->get_param('post_id'));

        if ('' === trim($content) && $post_id > 0) {
            $post_content = get_post_field('post_content', $post_id, 'raw');
            if (is_string($post_content)) {
                $content = $post_content;
            }
        }

        if ('' === trim($content)) {
            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'score' => null,
                    'level' => null,
                    'grade' => null,
                    'stats' => [
                        'word_count' => 0,
                        'sentence_count' => 0,
                        'paragraph_count' => 0,
                        'estimated_reading_time' => 0,
                    ],
                    'message' => __('No content to analyze.', 'prorank-seo'),
                ],
            ], 200);
        }

        $cleaned_content = strip_shortcodes($content);
        $cleaned_content = wp_strip_all_tags($cleaned_content);
        $cleaned_content = html_entity_decode($cleaned_content, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $cleaned_content = preg_replace('/\s+/', ' ', $cleaned_content);
        $cleaned_content = trim((string) $cleaned_content);

        if ('' === $cleaned_content) {
            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'score' => null,
                    'level' => null,
                    'grade' => null,
                    'stats' => [
                        'word_count' => 0,
                        'sentence_count' => 0,
                        'paragraph_count' => 0,
                        'estimated_reading_time' => 0,
                    ],
                    'message' => __('No content to analyze.', 'prorank-seo'),
                ],
            ], 200);
        }

        $score = Readability::calculate_flesch_kincaid($cleaned_content);
        $word_count = str_word_count($cleaned_content);
        $sentence_count = preg_match_all('/[.!?]+/', $cleaned_content, $matches);
        $paragraph_count = max(1, count(preg_split('/\n\s*\n/', $content)));
        $estimated_reading_time = max(1, (int) ceil($word_count / 225));

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'score' => $score,
                'level' => null !== $score ? Readability::get_readability_level($score) : null,
                'grade' => null !== $score ? Readability::get_grade_level($score) : null,
                'stats' => [
                    'word_count' => $word_count,
                    'sentence_count' => max(1, (int) $sentence_count),
                    'paragraph_count' => $paragraph_count,
                    'estimated_reading_time' => $estimated_reading_time,
                ],
            ],
        ], 200);
    }
}
