<?php
if (!defined('ABSPATH')) exit;

/**
 * Rich Results Score — 0–100 Google/Bing readiness per schema.
 */
class AISB_Rich_Results_Score {

    public static function compute($schema) {
        if (!is_array($schema)) {
            return self::empty_result(__('No schema data', 'pewit-ai-schema-builder'));
        }

        $validation = AISB_Rich_Results::validate($schema);
        $type = $validation['type'] ?? '';
        $rules = AISB_Rich_Results::field_rules()[$type] ?? null;

        if (!$type || !$rules) {
            return [
                'score'      => 0,
                'grade'      => 'none',
                'label'      => __('No score', 'pewit-ai-schema-builder'),
                'type'       => $type,
                'missing'    => [],
                'warnings'   => $validation['warnings'] ?? [],
                'errors'     => $validation['errors'] ?? [],
                'valid'      => false,
            ];
        }

        $missing_required = [];
        $missing_recommended = [];

        foreach ($rules['required'] as $field) {
            if (!self::field_present($schema, $field, $type)) {
                $missing_required[] = $field;
            }
        }
        foreach ($rules['recommended'] as $field) {
            if (!self::field_present($schema, $field, $type)) {
                $missing_recommended[] = $field;
            }
        }

        $req_total = max(1, count($rules['required']));
        $rec_total = max(1, count($rules['recommended']));
        $req_pct = 1 - (count($missing_required) / $req_total);
        $rec_pct = 1 - (count($missing_recommended) / $rec_total);

        $score = (int) round(($req_pct * 70) + ($rec_pct * 30));
        $score = max(0, min(100, $score));

        if (!empty($validation['errors'])) {
            $score = min($score, 40);
        }

        return [
            'score'               => $score,
            'grade'               => self::grade($score),
            'label'               => self::grade_label($score),
            'type'                => $type,
            'missing_required'    => $missing_required,
            'missing_recommended' => $missing_recommended,
            'missing'             => array_merge($missing_required, $missing_recommended),
            'warnings'            => $validation['warnings'] ?? [],
            'errors'              => $validation['errors'] ?? [],
            'valid'               => empty($validation['errors']),
            'google'              => !empty($validation['google']),
        ];
    }

    public static function site_stats() {
        $post_types = AISB_CPT_Registry::get_enabled_post_types();
        $with_schema = 0;
        $total_score = 0;
        $below_80 = 0;
        $no_schema = 0;

        $q = new WP_Query([
            'post_type'      => $post_types,
            'post_status'    => 'publish',
            'posts_per_page' => 500,
            'fields'         => 'ids',
            'no_found_rows'  => true,
        ]);

        foreach ($q->posts as $post_id) {
            $schema = AISB_Schema::get_json($post_id);
            if (!$schema) {
                $no_schema++;
                continue;
            }
            $with_schema++;
            $result = self::compute($schema);
            $total_score += (int) $result['score'];
            if ($result['score'] < 80) {
                $below_80++;
            }
        }

        $avg = $with_schema ? (int) round($total_score / $with_schema) : 0;

        return [
            'published'   => count($q->posts),
            'with_schema' => $with_schema,
            'no_schema'   => $no_schema,
            'avg_score'   => $avg,
            'below_80'    => $below_80,
            'grade'       => self::grade($avg),
            'label'       => self::grade_label($avg),
        ];
    }

    public static function render_badge_html($score, $compact = false) {
        $score = max(0, min(100, (int) $score));
        $grade = self::grade($score);
        if ($compact) {
            return sprintf(
                '<span class="aisb-rr-score aisb-rr-score--%1$s" title="%2$s">%3$d</span>',
                esc_attr($grade),
                esc_attr(self::grade_label($score)),
                $score
            );
        }
        return sprintf(
            '<div class="aisb-rr-score-block aisb-rr-score-block--%1$s"><span class="aisb-rr-score-value">%2$d</span><span class="aisb-rr-score-label">%3$s</span></div>',
            esc_attr($grade),
            $score,
            esc_html(self::grade_label($score))
        );
    }

    private static function field_present($schema, $field, $type) {
        if ($field === 'headline' && !empty($schema['headline'])) {
            return true;
        }
        if ($field === 'name' && (!empty($schema['name']) || !empty($schema['headline']))) {
            return true;
        }
        if ($field === 'title' && !empty($schema['title'])) {
            return true;
        }
        if ($field === 'image' && !empty($schema['image'])) {
            return true;
        }
        if ($field === 'author' && !empty($schema['author'])) {
            return true;
        }
        if ($field === 'offers' && !empty($schema['offers'])) {
            return true;
        }
        if ($field === 'mainEntity' && !empty($schema['mainEntity'])) {
            return true;
        }
        if ($field === 'address' && !empty($schema['address'])) {
            return true;
        }
        if ($field === 'location' && !empty($schema['location'])) {
            return true;
        }
        if ($field === 'step' && !empty($schema['step'])) {
            return true;
        }
        if ($field === 'recipeIngredient' && !empty($schema['recipeIngredient'])) {
            return true;
        }
        if ($field === 'itemListElement' && !empty($schema['itemListElement'])) {
            return true;
        }
        if ($field === 'hiringOrganization' && !empty($schema['hiringOrganization'])) {
            return true;
        }
        if ($field === 'jobLocation' && !empty($schema['jobLocation'])) {
            return true;
        }
        return !empty($schema[$field]);
    }

    private static function grade($score) {
        if ($score >= 90) {
            return 'excellent';
        }
        if ($score >= 80) {
            return 'good';
        }
        if ($score >= 60) {
            return 'fair';
        }
        if ($score >= 40) {
            return 'poor';
        }
        return 'critical';
    }

    private static function grade_label($score) {
        if ($score >= 90) {
            return __('Excellent — rich results ready', 'pewit-ai-schema-builder');
        }
        if ($score >= 80) {
            return __('Good — minor gaps', 'pewit-ai-schema-builder');
        }
        if ($score >= 60) {
            return __('Fair — fix recommended fields', 'pewit-ai-schema-builder');
        }
        if ($score >= 40) {
            return __('Poor — missing required fields', 'pewit-ai-schema-builder');
        }
        return __('Critical — unlikely to show rich results', 'pewit-ai-schema-builder');
    }

    private static function empty_result($message) {
        return [
            'score'    => 0,
            'grade'    => 'none',
            'label'    => $message,
            'type'     => '',
            'missing'  => [],
            'warnings' => [],
            'errors'   => [$message],
            'valid'    => false,
        ];
    }
}
