<?php

/**
 * Basic (Local) Audit Engine
 *
 * Lightweight audit that runs locally without a license/server calls.
 *
 * @package ProRank\SEO\Core\Audits
 */
declare(strict_types=1);

namespace ProRank\SEO\Core\Audits;

use ProRank\SEO\Core\Content\AiContentLeakAuditor;
use WP_Error;

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




class BasicAuditEngine {
    private const AUDIT_ID_PREFIX = 'local_basic_';

    private string $audits_table;
    private string $audit_urls_table;
    private string $audit_issues_table;

    public function __construct() {
        global $wpdb;
        $this->audits_table = $wpdb->prefix . 'prorank_audits';
        $this->audit_urls_table = $wpdb->prefix . 'prorank_audit_urls';
        $this->audit_issues_table = $wpdb->prefix . 'prorank_audit_issues';
    }

    /**
     * Run a basic audit synchronously and persist results.
     *
     * @param array $settings Optional settings (unused for now).
     * @return array|WP_Error Status payload on success, WP_Error on failure.
     */
    public function run(array $settings = []) {
        global $wpdb;

        $this->maybe_create_tables();

        $audit_id = self::AUDIT_ID_PREFIX . wp_generate_uuid4();
        $now_mysql = current_time('mysql');
        $site_url = home_url('/');

        $issues = $this->collect_issues();
        $counts = $this->count_severities($issues);
        $score = $this->calculate_score($counts);

        $stats = [
            'mode' => 'local_basic',
            'unique_issues' => [
                'critical' => $counts['critical'],
                'high' => $counts['high'],
                'medium' => $counts['medium'],
                'low' => $counts['low'],
                'warning' => $counts['warning'],
                'total' => $counts['total'],
            ],
        ];

        $inserted = $wpdb->insert(
            $this->audits_table,
            [
                'audit_id' => $audit_id,
                'status' => 'completed',
                'started_at' => $now_mysql,
                'completed_at' => $now_mysql,
                'total_urls' => 1,
                'score' => $score,
                'stats' => wp_json_encode($stats),
                'options' => wp_json_encode($settings),
                'error' => null,
            ],
            [
                '%s', // audit_id
                '%s', // status
                '%s', // started_at
                '%s', // completed_at
                '%d', // total_urls
                '%d', // score
                '%s', // stats
                '%s', // options
                '%s', // error
            ]
        );

        if ($inserted === false) {
            return new WP_Error('db_error', __('Failed to store audit result', 'prorank-seo'));
        }

        // Store single URL entry (home page) and attach all issues to it.
        $issues_count = $counts['critical'] + $counts['high'];
        $warnings_count = $counts['medium'] + $counts['low'];

        $url_inserted = $wpdb->insert(
            $this->audit_urls_table,
            [
                'audit_id' => $audit_id,
                'url' => $site_url,
                'status' => 'checked',
                'issues_count' => $issues_count,
                'warnings_count' => $warnings_count,
                'passed_count' => 0,
                'score' => $score,
                'created_at' => $now_mysql,
                'checked_at' => $now_mysql,
            ],
            [
                '%s', // audit_id
                '%s', // url
                '%s', // status
                '%d', // issues_count
                '%d', // warnings_count
                '%d', // passed_count
                '%d', // score
                '%s', // created_at
                '%s', // checked_at
            ]
        );

        $url_id = (int) $wpdb->insert_id;

        if ($url_inserted === false || $url_id <= 0) {
            return new WP_Error('db_error', __('Failed to store audit URLs', 'prorank-seo'));
        }

        foreach ($issues as $issue) {
            $wpdb->insert(
                $this->audit_issues_table,
                [
                    'audit_id' => $audit_id,
                    'url_id' => $url_id,
                    'type' => $issue['type'],
                    'severity' => $issue['severity'],
                    'message' => $issue['message'],
                    'data' => wp_json_encode($issue),
                    'created_at' => $now_mysql,
                ],
                [
                    '%s', // audit_id
                    '%d', // url_id
                    '%s', // type
                    '%s', // severity
                    '%s', // message
                    '%s', // data
                    '%s', // created_at
                ]
            );
        }

        // Ensure the dashboard reflects the latest audit immediately.
        delete_transient('prorank_dashboard_stats');

        return $this->format_status($audit_id, [
            'started_at' => $now_mysql,
            'completed_at' => $now_mysql,
            'total_urls' => 1,
            'score' => $score,
        ], $counts);
    }

    /**
     * Return latest basic audit status (if any).
     */
    public function get_latest_status(): ?array {
        global $wpdb;

        if (!$this->table_exists($this->audits_table)) {
            return null;
        }

        $row = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT audit_id, status, started_at, completed_at, total_urls, score
                 FROM {$this->audits_table}
                 WHERE audit_id LIKE %s
                 ORDER BY completed_at DESC, started_at DESC, id DESC
                 LIMIT 1",
                self::AUDIT_ID_PREFIX . '%'
            )
        );

        if (!$row) {
            return null;
        }

        $counts = $this->get_issue_counts((string) $row->audit_id);

        return $this->format_status((string) $row->audit_id, [
            'started_at' => $row->started_at,
            'completed_at' => $row->completed_at,
            'total_urls' => (int) ($row->total_urls ?? 0),
            'score' => (int) ($row->score ?? 0),
        ], $counts);
    }

    /**
     * Get issues for a specific local audit.
     */
    public function get_issues(string $audit_id): array {
        global $wpdb;

        if (
            !$this->table_exists($this->audit_issues_table) ||
            !$this->table_exists($this->audit_urls_table)
        ) {
            return [];
        }

        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT i.id, i.type, i.severity, i.message, i.data, u.url
                 FROM {$this->audit_issues_table} i
                 LEFT JOIN {$this->audit_urls_table} u ON u.id = i.url_id
                 WHERE i.audit_id = %s
                 ORDER BY FIELD(i.severity, 'critical', 'high', 'medium', 'low', 'passed'), i.id ASC",
                $audit_id
            )
        );

        if (empty($rows)) {
            return [];
        }

        $issues = [];
        foreach ($rows as $row) {
            $data = [];
            if (!empty($row->data)) {
                $decoded = json_decode((string) $row->data, true);
                if (is_array($decoded)) {
                    $data = $decoded;
                }
            }

            $issues[] = [
                'id' => (string) ($data['id'] ?? $row->id),
                'type' => (string) ($data['type'] ?? $row->type),
                'issue_type' => (string) ($data['type'] ?? $row->type),
                'severity' => (string) ($data['severity'] ?? $row->severity),
                'category' => (string) ($data['category'] ?? 'content'),
                'display_category' => (string) ($data['display_category'] ?? ($data['category'] ?? 'content')),
                'title' => (string) ($data['title'] ?? $row->type),
                'description' => (string) ($data['description'] ?? $row->message),
                'url' => (string) ($data['url'] ?? ($row->url ?? home_url('/'))),
                'impact' => (string) ($data['impact'] ?? ''),
                'how_to_fix' => (string) ($data['how_to_fix'] ?? ''),
                'fix_suggestion' => (string) ($data['how_to_fix'] ?? ''),
                'reference' => $data['reference'] ?? null,
            ];
        }

        return $issues;
    }

    /**
     * Get basic audit history.
     */
    public function get_history(int $limit = 10): array {
        global $wpdb;

        if (!$this->table_exists($this->audits_table)) {
            return [];
        }

        $limit = max(1, min(50, $limit));

        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT audit_id, status, started_at, completed_at, total_urls, score
                 FROM {$this->audits_table}
                 WHERE audit_id LIKE %s
                 ORDER BY completed_at DESC, started_at DESC, id DESC
                 LIMIT %d",
                self::AUDIT_ID_PREFIX . '%',
                $limit
            )
        );

        if (empty($rows)) {
            return [];
        }

        $domain = wp_parse_url(home_url('/'), PHP_URL_HOST) ?: '';

        $audits = [];
        foreach ($rows as $row) {
            $audit_id = (string) $row->audit_id;
            $counts = $this->get_issue_counts($audit_id);

            $audits[] = [
                'id' => $audit_id,
                'audit_id' => $audit_id,
                'domain' => $domain,
                'status' => (string) ($row->status ?? 'completed'),
                'state' => 'completed',
                'audit_type' => 'local_basic',
                'total_urls' => (int) ($row->total_urls ?? 0),
                'progress' => 100,
                'overallScore' => (int) ($row->score ?? 0),
                'overall_score' => (int) ($row->score ?? 0),
                'issues' => [
                    'critical' => $counts['critical'],
                    'high' => $counts['high'],
                    'medium' => $counts['medium'],
                    'low' => $counts['low'],
                    'warning' => $counts['warning'],
                    'total' => $counts['total'],
                ],
                'started_at' => $row->started_at,
                'completed_at' => $row->completed_at,
                'created_at' => $row->completed_at ?: $row->started_at,
            ];
        }

        return $audits;
    }

    private function format_status(string $audit_id, array $audit_row, array $counts): array {
        $total_urls = (int) ($audit_row['total_urls'] ?? 0);
        if ($total_urls <= 0) {
            $total_urls = 1;
        }

        return [
            'audit_id' => $audit_id,
            'state' => 'completed',
            'status' => 'completed',
            'mode' => 'local_basic',
            'message' => __('Basic audit completed locally', 'prorank-seo'),
            'progress' => [
                'percent' => 100,
                'percentage' => 100,
                'total_urls' => $total_urls,
                'checked_urls' => $total_urls,
            ],
            'started_at' => $audit_row['started_at'] ?? null,
            'completed_at' => $audit_row['completed_at'] ?? null,
            'issuesCritical' => $counts['critical'],
            'issuesHigh' => $counts['high'],
            'issuesMedium' => $counts['medium'],
            'issuesLow' => $counts['low'],
            'issuesWarning' => $counts['warning'],
            'overallScore' => (int) ($audit_row['score'] ?? 0),
            'overall_score' => (int) ($audit_row['score'] ?? 0),
            'totalUrls' => $total_urls,
            'total_urls' => $total_urls,
        ];
    }

    private function collect_issues(): array {
        $issues = [];

        $site_url = home_url('/');
        $using_https = function_exists('wp_is_using_https')
            ? (bool) wp_is_using_https()
            : (stripos($site_url, 'https://') === 0);

        // Technical SEO: Search engine visibility
        $blog_public = (int) get_option('blog_public', 1);
        if ($blog_public !== 1) {
            $issues[] = $this->issue([
                'type' => 'discourage_search_engines',
                'severity' => 'critical',
                'category' => 'technical_seo',
                'title' => __('Search engine visibility is disabled', 'prorank-seo'),
                'description' => __('Your site is set to discourage search engines from indexing it.', 'prorank-seo'),
                'how_to_fix' => __('Go to Settings → Reading and uncheck “Discourage search engines from indexing this site”.', 'prorank-seo'),
            ]);
        }

        // Technical SEO: Permalinks
        $permalink_structure = (string) get_option('permalink_structure', '');
        if (trim($permalink_structure) === '') {
            $issues[] = $this->issue([
                'type' => 'permalink_structure',
                'severity' => 'medium',
                'category' => 'technical_seo',
                'title' => __('Permalinks are not enabled', 'prorank-seo'),
                'description' => __('Pretty permalinks improve SEO and readability.', 'prorank-seo'),
                'how_to_fix' => __('Go to Settings → Permalinks and select “Post name”.', 'prorank-seo'),
            ]);
        }

        // Security: HTTPS
        if (!$using_https) {
            $issues[] = $this->issue([
                'type' => 'https_not_enabled',
                'severity' => 'high',
                'category' => 'security',
                'title' => __('HTTPS is not enabled', 'prorank-seo'),
                'description' => __('Your site is not using HTTPS, which can hurt SEO and security.', 'prorank-seo'),
                'how_to_fix' => __('Install an SSL certificate and update WordPress Address + Site Address to https://', 'prorank-seo'),
            ]);
        }

        // Security: Mixed content risk (common WordPress misconfiguration)
        if ($using_https) {
            $home_option = (string) get_option('home', '');
            $siteurl_option = (string) get_option('siteurl', '');
            if (
                (stripos($home_option, 'http://') === 0) ||
                (stripos($siteurl_option, 'http://') === 0)
            ) {
                $issues[] = $this->issue([
                    'type' => 'wordpress_urls_http',
                    'severity' => 'high',
                    'category' => 'security',
                    'title' => __('WordPress URLs are set to http://', 'prorank-seo'),
                    'description' => __('Your admin is running over HTTPS but WordPress Address/Site Address are set to http://. This often causes mixed content warnings (icons, uploads, images).', 'prorank-seo'),
                    'how_to_fix' => __('Go to Settings → General and set both WordPress Address and Site Address to https:// (or define WP_HOME/WP_SITEURL in wp-config.php).', 'prorank-seo'),
                ]);
            }

            $uploads = wp_get_upload_dir();
            $baseurl = is_array($uploads) ? ($uploads['baseurl'] ?? '') : '';
            if (is_string($baseurl) && stripos($baseurl, 'http://') === 0) {
                $issues[] = $this->issue([
                    'type' => 'mixed_content_risk',
                    'severity' => 'high',
                    'category' => 'security',
                    'title' => __('Mixed content risk detected', 'prorank-seo'),
                    'description' => __('Your uploads URL uses http:// while the site is on https://. This can cause mixed content warnings.', 'prorank-seo'),
                    'how_to_fix' => __('Check Settings → General and ensure both WordPress Address and Site Address use https://. Then update hardcoded http:// links.', 'prorank-seo'),
                ]);
            }
        }

        // Site basics: Site icon
        if (function_exists('has_site_icon') && !has_site_icon()) {
            $issues[] = $this->issue([
                'type' => 'site_icon_missing',
                'severity' => 'low',
                'category' => 'on_page_seo',
                'title' => __('Site icon (favicon) is missing', 'prorank-seo'),
                'description' => __('A site icon improves branding in tabs, bookmarks, and some SERP displays.', 'prorank-seo'),
                'how_to_fix' => __('Go to Appearance → Customize → Site Identity and set a Site Icon.', 'prorank-seo'),
            ]);
        }

        // Site basics: Default tagline
        $tagline = trim((string) get_option('blogdescription', ''));
        if ($tagline !== '' && strtolower($tagline) === 'just another wordpress site') {
            $issues[] = $this->issue([
                'type' => 'default_tagline',
                'severity' => 'low',
                'category' => 'on_page_seo',
                'title' => __('Default WordPress tagline detected', 'prorank-seo'),
                'description' => __('Your site tagline is still the default “Just another WordPress site”.', 'prorank-seo'),
                'how_to_fix' => __('Go to Settings → General and update the Tagline to match your brand.', 'prorank-seo'),
            ]);
        }

        // Security: WP_DEBUG enabled
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $issues[] = $this->issue([
                'type' => 'wp_debug_enabled',
                'severity' => 'medium',
                'category' => 'security',
                'title' => __('WP_DEBUG is enabled', 'prorank-seo'),
                'description' => __('Debug mode can leak information and may affect performance.', 'prorank-seo'),
                'how_to_fix' => __('Disable WP_DEBUG on production sites (wp-config.php).', 'prorank-seo'),
            ]);
        }

        // Performance: Cache settings (ProRank)
        $cache_settings = get_option('prorank_cache_settings', []);
        if (is_array($cache_settings)) {
            if (empty($cache_settings['cache_enabled'])) {
                $issues[] = $this->issue([
                    'type' => 'page_cache_disabled',
                    'severity' => 'medium',
                    'category' => 'performance',
                    'title' => __('Page cache is disabled', 'prorank-seo'),
                    'description' => __('Enabling page cache can significantly improve TTFB and repeat visits.', 'prorank-seo'),
                    'how_to_fix' => __('Enable Page Cache in ProRank → Performance → Caching & Delivery.', 'prorank-seo'),
                ]);
            }

            if (empty($cache_settings['browser_cache_enabled'])) {
                $issues[] = $this->issue([
                    'type' => 'browser_cache_disabled',
                    'severity' => 'medium',
                    'category' => 'performance',
                    'title' => __('Browser cache headers are disabled', 'prorank-seo'),
                    'description' => __('Setting cache headers reduces repeat-load times for static assets.', 'prorank-seo'),
                    'how_to_fix' => __('Enable Browser Cache in ProRank → Performance → Caching & Delivery.', 'prorank-seo'),
                ]);
            }
        }

        // Performance: Asset optimization settings (ProRank)
        $asset_settings = get_option('prorank_asset_optimization_settings', []);
        if (is_array($asset_settings)) {
            if (empty($asset_settings['js_minify_enabled'])) {
                $issues[] = $this->issue([
                    'type' => 'js_minify_disabled',
                    'severity' => 'low',
                    'category' => 'performance',
                    'title' => __('JavaScript minification is disabled', 'prorank-seo'),
                    'description' => __('Minifying JS can reduce payload and parsing time.', 'prorank-seo'),
                    'how_to_fix' => __('Enable JS Minify in ProRank → Performance → Assets & JS.', 'prorank-seo'),
                ]);
            }

            if (empty($asset_settings['font_display_swap'])) {
                $issues[] = $this->issue([
                    'type' => 'font_display_swap_disabled',
                    'severity' => 'low',
                    'category' => 'performance',
                    'title' => __('font-display is not set to swap', 'prorank-seo'),
                    'description' => __('Setting font-display: swap keeps text visible during font loading.', 'prorank-seo'),
                    'how_to_fix' => __('Enable “Font Display: swap” in ProRank → Performance → Assets & JS.', 'prorank-seo'),
                ]);
            }
        }

        // Performance: Image settings (ProRank)
        $image_settings = get_option('prorank_image_optimization_settings', []);
        if (is_array($image_settings)) {
            if (isset($image_settings['lazyload_images']) && empty($image_settings['lazyload_images'])) {
                $issues[] = $this->issue([
                    'type' => 'lazyload_images_disabled',
                    'severity' => 'low',
                    'category' => 'performance',
                    'title' => __('Image lazy-loading is disabled', 'prorank-seo'),
                    'description' => __('Lazy-loading images can improve initial load performance.', 'prorank-seo'),
                    'how_to_fix' => __('Enable Image Lazy-load in ProRank → Performance → Image Optimization.', 'prorank-seo'),
                ]);
            }

            if (isset($image_settings['webp_enabled']) && empty($image_settings['webp_enabled'])) {
                $issues[] = $this->issue([
                    'type' => 'next_gen_images_disabled',
                    'severity' => 'low',
                    'category' => 'performance',
                    'title' => __('Next‑gen images (WebP) are disabled', 'prorank-seo'),
                    'description' => __('Serving WebP/AVIF can reduce image transfer size significantly.', 'prorank-seo'),
                    'how_to_fix' => __('Enable WebP in ProRank → Performance → Image Optimization.', 'prorank-seo'),
                ]);
            }
        }

        foreach ($this->collect_ai_content_leak_issues() as $issue) {
            $issues[] = $issue;
        }

        foreach ($this->collect_object_cache_issues() as $issue) {
            $issues[] = $issue;
        }

        foreach ($this->collect_bloat_control_issues() as $issue) {
            $issues[] = $issue;
        }

        foreach ($this->collect_font_delivery_issues() as $issue) {
            $issues[] = $issue;
        }

        return $issues;
    }

    /**
     * Lightweight font-delivery rows (no HTTP fetch). Uses settings +
     * FontOptimizationModule::get_stats() as the single source of truth.
     * Does NOT duplicate the existing font_display_swap_disabled row.
     *
     * @return array
     */
    private function collect_font_delivery_issues(): array {
        $asset = get_option('prorank_asset_optimization_settings', []);
        if (!is_array($asset)) {
            $asset = [];
        }
        $host_local = !empty($asset['host_google_fonts_locally']);

        $stats = ['total_fonts' => 0, 'google_fonts_found' => 0];
        if (class_exists('\\ProRank\\SEO\\Modules\\Performance\\FontOptimizationModule')) {
            try {
                $m = new \ProRank\SEO\Modules\Performance\FontOptimizationModule();
                if (method_exists($m, 'get_stats')) {
                    $s = $m->get_stats();
                    if (is_array($s)) {
                        $stats = array_merge($stats, $s);
                    }
                }
            } catch (\Throwable $e) {
                // best-effort
            }
        }

        $issues = [];

        if ((int) $stats['google_fonts_found'] > 0 && !$host_local) {
            $issues[] = $this->issue([
                'type' => 'external_google_fonts_detected',
                'severity' => 'medium',
                'category' => 'performance',
                'title' => __('External Google Fonts detected', 'prorank-seo'),
                'description' => __('Google Fonts are referenced but local hosting is off, so a third-party request blocks render.', 'prorank-seo'),
                'how_to_fix' => __('Enable “Host Google Fonts locally” in ProRank → Performance → Asset Optimisation.', 'prorank-seo'),
            ]);
        }

        // NOTE: "another component self-hosts fonts" is intentionally NOT an
        // audit row (a wp-content/fonts dir can exist unused → false noise).
        // It is reported only in the Font Delivery Health panel, which has
        // rendered proof before flagging it.

        return $issues;
    }

    /**
     * Single advisory row linking to the unified Bloat Control surface.
     * Reads the same existing option sources; no duplicate detection/runtime.
     *
     * @return array
     */
    private function collect_bloat_control_issues(): array {
        $advanced = get_option('prorank_seo_advanced_settings', []);
        $head     = get_option('prorank_seo_head_cleanup', []);
        if (!is_array($advanced)) {
            $advanced = [];
        }
        if (!is_array($head)) {
            $head = [];
        }

        $safe_advanced = ['disable_emojis'];
        $safe_head     = [
            'remove_wp_generator', 'remove_rsd_link', 'remove_wlwmanifest_link',
            'remove_wp_shortlink', 'remove_emoji_scripts',
            'disable_self_pingbacks', 'remove_comment_urls',
        ];

        $inactive = 0;
        foreach ($safe_advanced as $k) {
            if (empty($advanced[$k])) {
                $inactive++;
            }
        }
        foreach ($safe_head as $k) {
            if (empty($head[$k])) {
                $inactive++;
            }
        }

        if ($inactive === 0) {
            return [];
        }

        return [
            $this->issue([
                'type' => 'bloat_control_opportunities',
                'severity' => 'low',
                'category' => 'performance',
                'title' => sprintf(
                    /* translators: %d: number of inactive safe cleanups */
                    __('%d safe WordPress cleanup option(s) are inactive', 'prorank-seo'),
                    $inactive
                ),
                'description' => __('Several low-risk WordPress bloat cleanups are not enabled.', 'prorank-seo'),
                'how_to_fix' => __('Open ProRank → Performance → Database & Server → WordPress Bloat Control to enable safe cleanups.', 'prorank-seo'),
            ]),
        ];
    }

    /**
     * Object-cache health detection (free tier — summary rows only).
     *
     * @return array
     */
    private function collect_object_cache_issues(): array {
        $health_file = __DIR__ . '/../Performance/ObjectCacheHealth.php';
        if (!class_exists('\\ProRank\\SEO\\Core\\Performance\\ObjectCacheHealth') && is_readable($health_file)) {
            require_once $health_file;
        }
        if (!class_exists('\\ProRank\\SEO\\Core\\Performance\\ObjectCacheHealth')) {
            return [];
        }

        try {
            $report = (new \ProRank\SEO\Core\Performance\ObjectCacheHealth())->report();
        } catch (\Throwable $e) {
            prorank_log('[ProRank SEO] Object cache audit failed: ' . $e->getMessage());
            return [];
        }

        $issues = [];

        if (empty($report['persistent_cache'])) {
            $issues[] = $this->issue([
                'type' => 'object_cache_not_persistent',
                'severity' => 'medium',
                'category' => 'performance',
                'title' => __('No persistent object cache', 'prorank-seo'),
                'description' => __('WordPress is not using a persistent object cache, so database queries are repeated on every request.', 'prorank-seo'),
                'how_to_fix' => __('If your host supports Redis or Memcached, enable a persistent object cache to reduce server response time.', 'prorank-seo'),
            ]);
        }

        // Only surface the highest-severity drop-in/connection problems in free.
        foreach (($report['flags'] ?? []) as $flag) {
            $code = (string) ($flag['code'] ?? '');
            if (!in_array($code, ['invalid_dropin', 'connection_failure'], true)) {
                continue;
            }
            $issues[] = $this->issue([
                'type' => 'object_cache_' . $code,
                'severity' => (string) ($flag['severity'] ?? 'high'),
                'category' => 'performance',
                'title' => __('Object cache problem detected', 'prorank-seo'),
                'description' => (string) ($flag['message'] ?? ''),
                'how_to_fix' => (string) ($flag['recommendation'] ?? ''),
            ]);
        }

        return $issues;
    }

    private function collect_ai_content_leak_issues(): array {
        try {
            $auditor = new AiContentLeakAuditor();
            $scan = $auditor->scan();
        } catch (\Throwable $e) {
            prorank_log('[ProRank SEO] Basic AI content leak audit failed: ' . $e->getMessage());
            return [];
        }

        $offender_count = (int) ($scan['offender_count'] ?? 0);
        $elementor_count = (int) ($scan['elementor']['item_count'] ?? 0);
        $term_count = (int) ($scan['terms']['item_count'] ?? 0);
        $high_confidence = (int) ($scan['totals']['high_confidence'] ?? 0)
            + (int) ($scan['elementor']['totals']['high_confidence'] ?? 0)
            + (int) ($scan['terms']['totals']['high_confidence'] ?? 0);
        $ambiguous = (int) ($scan['totals']['ambiguous'] ?? 0)
            + (int) ($scan['elementor']['totals']['ambiguous'] ?? 0)
            + (int) ($scan['terms']['totals']['ambiguous'] ?? 0);

        if ($high_confidence <= 0 && $ambiguous <= 0) {
            return [];
        }

        $top_offenders = [];
        foreach (array_slice((array) ($scan['offenders'] ?? []), 0, 10) as $offender) {
            if (!is_array($offender)) {
                continue;
            }
            $top_offenders[] = [
                'id' => (int) ($offender['id'] ?? 0),
                'title' => (string) ($offender['title'] ?? ''),
                'type' => (string) ($offender['type'] ?? ''),
                'high_confidence' => (int) ($offender['high_confidence'] ?? 0),
                'ambiguous' => (int) ($offender['ambiguous'] ?? 0),
                'url' => (string) ($offender['permalink'] ?? ''),
            ];
        }
        foreach (array_slice((array) ($scan['terms']['items'] ?? []), 0, 10) as $term) {
            if (!is_array($term)) {
                continue;
            }
            $top_offenders[] = [
                'id' => (int) ($term['term_id'] ?? 0),
                'title' => (string) ($term['name'] ?? ''),
                'type' => 'term:' . (string) ($term['taxonomy'] ?? ''),
                'high_confidence' => (int) ($term['high_confidence'] ?? 0),
                'ambiguous' => (int) ($term['ambiguous'] ?? 0),
                'url' => (string) ($term['edit_link'] ?? ''),
            ];
        }

        usort($top_offenders, static function ($a, $b) {
            return (($b['high_confidence'] ?? 0) + ($b['ambiguous'] ?? 0))
                <=> (($a['high_confidence'] ?? 0) + ($a['ambiguous'] ?? 0));
        });
        $top_offenders = array_slice($top_offenders, 0, 10);

        if ($high_confidence > 0) {
            return [
                $this->issue([
                    'type' => 'ai_content_leak_sitewide',
                    'severity' => $high_confidence >= 100 ? 'critical' : 'high',
                    'category' => 'content',
                    'title' => __('AI paste metadata detected across published content', 'prorank-seo'),
                    'description' => sprintf(
                        __('Found %1$d high-confidence AI metadata attributes across %2$d content items, %3$d Elementor records, and %4$d term descriptions.', 'prorank-seo'),
                        $high_confidence,
                        $offender_count,
                        $elementor_count,
                        $term_count
                    ),
                    'impact' => __('These attributes are visible evidence of uncleaned AI-pasted content and can create scaled-content-abuse risk.', 'prorank-seo'),
                    'how_to_fix' => __('Run the AI Content Safety cleanup in ProRank or WP-CLI, then rewrite the worst affected pages before submitting AdSense appeals or requesting Google recrawl.', 'prorank-seo'),
                    'reference' => 'https://developers.google.com/search/docs/essentials/spam-policies#scaled-content',
                    'data' => [
                        'high_confidence' => $high_confidence,
                        'ambiguous' => $ambiguous,
                        'offender_count' => $offender_count,
                        'elementor_count' => $elementor_count,
                        'term_count' => $term_count,
                        'by_vendor' => $scan['by_vendor'] ?? [],
                        'by_post_type' => $scan['by_post_type'] ?? [],
                        'top_offenders' => $top_offenders,
                    ],
                ]),
            ];
        }

        return [
            $this->issue([
                'type' => 'ambiguous_ai_content_marker_sitewide',
                'severity' => 'medium',
                'category' => 'content',
                'title' => __('Ambiguous AI/editor metadata detected', 'prorank-seo'),
                'description' => sprintf(
                    __('Found %d ambiguous AI/editor metadata attributes. Review before removing because some may belong to legitimate theme or plugin markup.', 'prorank-seo'),
                    $ambiguous
                ),
                'how_to_fix' => __('Review the flagged attributes manually. Remove them only when they are pasted editor artifacts.', 'prorank-seo'),
                    'data' => [
                        'ambiguous' => $ambiguous,
                        'offender_count' => $offender_count,
                        'elementor_count' => $elementor_count,
                        'term_count' => $term_count,
                        'top_offenders' => $top_offenders,
                    ],
            ]),
        ];
    }

    private function issue(array $issue): array {
        $defaults = [
            'id' => (string) wp_generate_uuid4(),
            'type' => '',
            'severity' => 'low',
            'category' => 'content',
            'display_category' => null,
            'title' => '',
            'description' => '',
            'message' => '',
            'url' => home_url('/'),
            'impact' => '',
            'how_to_fix' => '',
            'reference' => null,
        ];

        $merged = array_merge($defaults, $issue);

        if (empty($merged['display_category'])) {
            $merged['display_category'] = $merged['category'];
        }

        if (empty($merged['message'])) {
            $merged['message'] = $merged['description'] ?: $merged['title'];
        }

        $allowed = ['critical', 'high', 'medium', 'low', 'passed'];
        if (!in_array($merged['severity'], $allowed, true)) {
            $merged['severity'] = 'low';
        }

        $merged['category'] = (string) $merged['category'];
        $merged['display_category'] = (string) $merged['display_category'];
        $merged['title'] = (string) $merged['title'];
        $merged['description'] = (string) $merged['description'];
        $merged['message'] = (string) $merged['message'];
        $merged['how_to_fix'] = (string) $merged['how_to_fix'];

        return $merged;
    }

    private function count_severities(array $issues): array {
        $counts = [
            'critical' => 0,
            'high' => 0,
            'medium' => 0,
            'low' => 0,
            'warning' => 0,
            'total' => 0,
        ];

        foreach ($issues as $issue) {
            $severity = (string) ($issue['severity'] ?? 'low');
            if (!isset($counts[$severity])) {
                $severity = 'low';
            }
            $counts[$severity]++;
            $counts['total']++;
        }

        // UI often treats low as "warning"
        $counts['warning'] = $counts['low'];

        return $counts;
    }

    private function calculate_score(array $counts): int {
        $score = 100;
        $score -= min(60, $counts['critical'] * 15);
        $score -= min(40, $counts['high'] * 8);
        $score -= min(25, $counts['medium'] * 4);
        $score -= min(15, $counts['low'] * 2);

        return max(0, min(100, $score));
    }

    private function get_issue_counts(string $audit_id): array {
        global $wpdb;

        $counts = [
            'critical' => 0,
            'high' => 0,
            'medium' => 0,
            'low' => 0,
            'warning' => 0,
            'total' => 0,
        ];

        if (!$this->table_exists($this->audit_issues_table)) {
            return $counts;
        }

        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT severity, COUNT(*) as cnt
                 FROM {$this->audit_issues_table}
                 WHERE audit_id = %s
                 GROUP BY severity",
                $audit_id
            )
        );

        foreach ($rows as $row) {
            $sev = (string) $row->severity;
            if (isset($counts[$sev])) {
                $counts[$sev] = (int) $row->cnt;
            }
        }

        $counts['total'] = $counts['critical'] + $counts['high'] + $counts['medium'] + $counts['low'];
        $counts['warning'] = $counts['low'];

        return $counts;
    }

    private function maybe_create_tables(): void {
        global $wpdb;

        if (
            $this->table_exists($this->audits_table) &&
            $this->table_exists($this->audit_urls_table) &&
            $this->table_exists($this->audit_issues_table)
        ) {
            return;
        }

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $charset_collate = $wpdb->get_charset_collate();

        $sql1 = "CREATE TABLE {$this->audits_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            audit_id varchar(50) NOT NULL,
            status enum('idle','crawling','checking','completed','failed','stopped','stopping') DEFAULT 'idle',
            started_at datetime DEFAULT NULL,
            completed_at datetime DEFAULT NULL,
            total_urls int(11) DEFAULT 0,
            score int(3) DEFAULT NULL,
            stats longtext,
            options longtext,
            error text,
            PRIMARY KEY  (id),
            UNIQUE KEY audit_id (audit_id),
            KEY status (status),
            KEY started_at (started_at)
        ) $charset_collate;";

        $sql2 = "CREATE TABLE {$this->audit_urls_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            audit_id varchar(50) NOT NULL,
            url varchar(500) NOT NULL,
            status enum('pending','checking','checked') DEFAULT 'pending',
            depth int(11) DEFAULT 0,
            issues_count int(11) DEFAULT 0,
            warnings_count int(11) DEFAULT 0,
            passed_count int(11) DEFAULT 0,
            score int(3) DEFAULT NULL,
            created_at datetime DEFAULT NULL,
            checked_at datetime DEFAULT NULL,
            PRIMARY KEY  (id),
            KEY audit_id (audit_id),
            KEY status (status),
            KEY url (url(255))
        ) $charset_collate;";

        $sql3 = "CREATE TABLE {$this->audit_issues_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            audit_id varchar(50) NOT NULL,
            url_id bigint(20) unsigned NOT NULL,
            type varchar(50) NOT NULL,
            severity enum('critical','high','medium','low','passed') DEFAULT 'medium',
            message text,
            data longtext,
            created_at datetime DEFAULT NULL,
            PRIMARY KEY  (id),
            KEY audit_id (audit_id),
            KEY url_id (url_id),
            KEY type (type),
            KEY severity (severity)
        ) $charset_collate;";

        dbDelta($sql1);
        dbDelta($sql2);
        dbDelta($sql3);
    }

    private function table_exists(string $table): bool {
        global $wpdb;
        $found = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table));
        return $found === $table;
    }
}
