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

/**
 * GEO Autopilot — the one-click "cure" (1.0 flagship).
 *
 * Reads a page's weak GEO dimensions, then generates an answer-first intro, a
 * key-facts block, FAQ pairs and schema in a single AI pass. plan() is a dry run
 * (preview + predicted score); apply() writes the optimized content. A backup of
 * the original content is stored and WordPress saves a revision, so every change
 * is fully reversible.
 */
class AIVT_Autopilot {

    const META_BACKUP = '_aivt_autopilot_backup';
    const META_LAST   = '_aivt_autopilot';

    /**
     * Build an optimization plan for a post (no writes).
     *
     * @return array|WP_Error
     */
    public static function plan($post_id) {
        $post_id = (int) $post_id;
        $ctx = AIVT_API::post_context($post_id, 6000);
        if (empty($ctx)) {
            return new WP_Error('aivt_no_post', __('Post not found', 'pewit-geo-analysis-tool'));
        }

        // Ensure we have a current GEO read to target the weakest areas.
        $geo = AIVT_Store::get($post_id, AIVT_Store::META_GEO);
        if (empty($geo) || !isset($geo['score'])) {
            $geo = AIVT_GEO_Score::analyze($post_id);
            if (is_wp_error($geo)) {
                return $geo;
            }
        }
        $current = (int) ($geo['score'] ?? 0);

        $weak = [];
        if (!empty($geo['breakdown']) && is_array($geo['breakdown'])) {
            foreach ($geo['breakdown'] as $row) {
                if ((int) ($row['score'] ?? 100) < 70) {
                    $weak[] = (string) ($row['label'] ?? '');
                }
            }
        }
        $weak = array_values(array_filter($weak));

        $json = AIVT_API::complete_json(self::build_prompt($ctx, $geo, $weak), 2200);
        if (is_wp_error($json)) {
            return $json;
        }

        $intro = sanitize_text_field((string) ($json['intro'] ?? ''));
        $facts = [];
        foreach ((array) ($json['key_facts'] ?? []) as $f) {
            $f = trim((string) (is_array($f) ? ($f['fact'] ?? '') : $f));
            if ($f !== '') {
                $facts[] = sanitize_text_field($f);
            }
        }
        $facts = array_slice($facts, 0, 8);
        $faq = AIVT_FAQ::clean_pairs($json['faq'] ?? []);

        if ($intro === '' && empty($facts) && empty($faq)) {
            return new WP_Error('aivt_empty', __('Autopilot could not generate improvements. Try again.', 'pewit-geo-analysis-tool'));
        }

        $predicted = AIVT_API::clamp_score((int) ($json['predicted_score'] ?? ($current + 12)));
        if ($predicted < $current) {
            $predicted = min(100, $current + 8); // optimization should not lower the score
        }

        return [
            'post_id'         => $post_id,
            'current_score'   => $current,
            'predicted_score' => $predicted,
            'weak'            => $weak,
            'intro'           => $intro,
            'key_facts'       => $facts,
            'faq'             => $faq,
            'summary'         => sanitize_text_field((string) ($json['changes_summary'] ?? '')),
            'has_backup'      => (bool) get_post_meta($post_id, self::META_BACKUP, true),
        ];
    }

    private static function build_prompt(array $ctx, array $geo, array $weak) {
        $context = AIVT_API::context_block();
        $weak_str = !empty($weak) ? implode(', ', $weak) : 'overall answer-engine readiness';

        $p  = "You are a Generative Engine Optimization (GEO/AEO) editor. Improve how the page below is surfaced and cited by AI answer engines (ChatGPT, Perplexity, Gemini, Google AI Overviews).\n";
        $p .= "Focus on the weakest areas: {$weak_str}.\n";
        $p .= "Produce, grounded ONLY in the existing page content (do NOT invent facts, prices, names or claims):\n";
        $p .= "1) intro: a single answer-first opening paragraph (2-4 sentences) that directly answers the page's core question.\n";
        $p .= "2) key_facts: 3-6 short, specific, quotable factual bullet points.\n";
        $p .= "3) faq: 3-5 question/answer pairs, answer-first, 2-4 sentences each.\n";
        $p .= "4) predicted_score: integer 0-100 — the GEO Score you expect AFTER these additions.\n";
        $p .= "5) changes_summary: one sentence describing the improvement.\n\n";
        $p .= "Return ONLY JSON, no markdown:\n";
        $p .= '{"intro":"","key_facts":["",""],"faq":[{"question":"","answer":""}],"predicted_score":0,"changes_summary":""}'."\n\n";
        if ($context) {
            $p .= "Site context:\n{$context}\n\n";
        }
        $p .= "Current GEO Score: " . (int) ($geo['score'] ?? 0) . "/100\n";
        if (!empty($ctx['focus_keyword'])) {
            $p .= "Target keyword: {$ctx['focus_keyword']}\n";
        }
        $p .= "PAGE\nTitle: {$ctx['title']}\nContent:\n{$ctx['content']}\n";
        return $p;
    }

    /** Gutenberg blocks for the intro + key-facts block (prepended above content). */
    public static function intro_blocks(array $plan) {
        $out = '';
        if (!empty($plan['intro'])) {
            $out .= "<!-- wp:paragraph -->\n<p>" . esc_html($plan['intro']) . "</p>\n<!-- /wp:paragraph -->\n\n";
        }
        if (!empty($plan['key_facts'])) {
            $out .= "<!-- wp:heading {\"level\":2} -->\n<h2>" . esc_html__('Key facts', 'pewit-geo-analysis-tool') . "</h2>\n<!-- /wp:heading -->\n\n";
            $out .= "<!-- wp:list -->\n<ul>\n";
            foreach ($plan['key_facts'] as $fact) {
                $out .= "<li>" . esc_html($fact) . "</li>\n";
            }
            $out .= "</ul>\n<!-- /wp:list -->\n\n";
        }
        return trim($out);
    }

    public static function faq_blocks(array $plan) {
        if (empty($plan['faq'])) {
            return '';
        }
        return AIVT_FAQ::render_blocks($plan['faq'], __('Frequently Asked Questions', 'pewit-geo-analysis-tool'));
    }

    /**
     * Apply a plan to the post. Saves a backup + a revision. Stores FAQ + schema.
     *
     * @return array|WP_Error
     */
    public static function apply($post_id, $plan = null) {
        $post_id = (int) $post_id;
        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('aivt_cap', __('Permission denied for this post.', 'pewit-geo-analysis-tool'));
        }
        if (!is_array($plan)) {
            $plan = self::plan($post_id);
        }
        if (is_wp_error($plan)) {
            return $plan;
        }
        $post = get_post($post_id);
        if (!$post) {
            return new WP_Error('aivt_no_post', __('Post not found', 'pewit-geo-analysis-tool'));
        }

        $intro = self::intro_blocks($plan);
        $faq = self::faq_blocks($plan);
        if ($intro === '' && $faq === '') {
            return new WP_Error('aivt_empty', __('Nothing to apply.', 'pewit-geo-analysis-tool'));
        }

        // Backup original content for one-click revert (kept until reverted).
        update_post_meta($post_id, self::META_BACKUP, [
            'content' => $post->post_content,
            'ts'      => time(),
        ]);

        $parts = [];
        if ($intro !== '') {
            $parts[] = $intro;
        }
        $parts[] = trim($post->post_content);
        if ($faq !== '') {
            $parts[] = $faq;
        }
        $new_content = implode("\n\n", array_filter($parts));

        // wp_update_post saves a revision automatically for revisioned post types.
        wp_update_post(['ID' => $post_id, 'post_content' => $new_content]);

        // Persist FAQ + FAQPage schema so analysis and frontend reflect the changes.
        if (!empty($plan['faq'])) {
            AIVT_Store::save($post_id, AIVT_Store::META_FAQ, ['pairs' => $plan['faq']]);
            $schema = AIVT_FAQ::build_schema($post_id, $plan['faq']);
            if (!empty($schema)) {
                AIVT_Store::save($post_id, AIVT_Store::META_SCHEMA, [
                    'type' => 'FAQPage',
                    'json' => wp_json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                ]);
            }
        }

        update_post_meta($post_id, self::META_LAST, [
            'predicted' => (int) $plan['predicted_score'],
            'before'    => (int) $plan['current_score'],
            'ts'        => time(),
        ]);

        return [
            'post_id'         => $post_id,
            'predicted_score' => (int) $plan['predicted_score'],
            'before_score'    => (int) $plan['current_score'],
        ];
    }

    /** Restore the pre-autopilot content from the saved backup. */
    public static function revert($post_id) {
        $post_id = (int) $post_id;
        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('aivt_cap', __('Permission denied for this post.', 'pewit-geo-analysis-tool'));
        }
        $backup = get_post_meta($post_id, self::META_BACKUP, true);
        if (empty($backup['content']) && (!isset($backup['content']) || $backup['content'] === '')) {
            return new WP_Error('aivt_no_backup', __('No Autopilot backup to restore.', 'pewit-geo-analysis-tool'));
        }
        wp_update_post(['ID' => $post_id, 'post_content' => (string) $backup['content']]);
        delete_post_meta($post_id, self::META_BACKUP);
        delete_post_meta($post_id, self::META_LAST);
        return ['post_id' => $post_id];
    }

    public static function has_backup($post_id) {
        return (bool) get_post_meta((int) $post_id, self::META_BACKUP, true);
    }
}
