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

/**
 * WP-CLI commands for GEO Analysis Tool.
 *
 * Registered only when WP-CLI is available. All commands use the configured
 * AI provider + key (BYOK). Examples:
 *
 *   wp aivt analyze 42
 *   wp aivt generate 42 --type=faq --count=6
 *   wp aivt bulk geo
 *   wp aivt job-status
 *   wp aivt prompt-run "Recommend a car detailing studio in Poznan"
 *   wp aivt autopilot 42 --apply
 */
class AIVT_CLI {

    public static function register() {
        if (!defined('WP_CLI') || !WP_CLI) {
            return;
        }
        WP_CLI::add_command('aivt', __CLASS__);
    }

    private function ensure_key() {
        if (!aivt_api_ready()) {
            WP_CLI::error('No verified API key. Configure it in GEO Analysis Tool → Settings (BYOK).');
        }
    }

    /**
     * Analyze the GEO Score of a single post.
     *
     * ## OPTIONS
     *
     * <post_id>
     * : The post/page ID to analyze.
     *
     * @when after_wp_load
     */
    public function analyze($args) {
        $this->ensure_key();
        $post_id = (int) $args[0];
        if (!get_post($post_id)) {
            WP_CLI::error("Post {$post_id} not found.");
        }
        WP_CLI::log("Analyzing GEO Score for #{$post_id}…");
        $res = AIVT_GEO_Score::analyze($post_id);
        if (is_wp_error($res)) {
            WP_CLI::error($res->get_error_message());
        }
        $score = (int) ($res['score'] ?? 0);
        WP_CLI::success(sprintf('GEO Score: %d/100 (%s)', $score, AIVT_GEO_Score::score_label($score)));
        if (!empty($res['tips'])) {
            WP_CLI::log('Top tips:');
            foreach (array_slice($res['tips'], 0, 5) as $tip) {
                WP_CLI::log('  • ' . $tip);
            }
        }
    }

    /**
     * Generate FAQ, Q&A or schema for a post (stored, not auto-inserted).
     *
     * ## OPTIONS
     *
     * <post_id>
     * : The post/page ID.
     *
     * [--type=<type>]
     * : One of faq, qa, schema.
     * ---
     * default: faq
     * options:
     *   - faq
     *   - qa
     *   - schema
     * ---
     *
     * [--count=<count>]
     * : How many pairs/items (faq, qa only). 2–12.
     * ---
     * default: 5
     * ---
     *
     * @when after_wp_load
     */
    public function generate($args, $assoc) {
        $this->ensure_key();
        $post_id = (int) $args[0];
        if (!get_post($post_id)) {
            WP_CLI::error("Post {$post_id} not found.");
        }
        $type = isset($assoc['type']) ? sanitize_key($assoc['type']) : 'faq';
        $count = isset($assoc['count']) ? (int) $assoc['count'] : 5;
        switch ($type) {
            case 'qa':     $res = AIVT_QA::generate($post_id, $count); break;
            case 'schema': $res = AIVT_Schema::generate($post_id); break;
            case 'faq':
            default:       $res = AIVT_FAQ::generate($post_id, $count); break;
        }
        if (is_wp_error($res)) {
            WP_CLI::error($res->get_error_message());
        }
        WP_CLI::success(sprintf('%s generated and stored for #%d.', strtoupper($type), $post_id));
    }

    /**
     * Start a background bulk job over posts missing the given output.
     *
     * ## OPTIONS
     *
     * [<type>]
     * : One of geo, faq, qa, schema.
     * ---
     * default: geo
     * ---
     *
     * @when after_wp_load
     */
    public function bulk($args) {
        $this->ensure_key();
        $type = isset($args[0]) ? sanitize_key($args[0]) : 'geo';
        $job = AIVT_Queue::create_job($type);
        if (is_wp_error($job)) {
            WP_CLI::error($job->get_error_message());
        }
        WP_CLI::success(sprintf('Bulk %s job queued for %d posts. It runs via WP-Cron; check `wp aivt job-status`.', $type, (int) $job['total']));
    }

    /**
     * Show the current bulk job status.
     *
     * @when after_wp_load
     */
    public function job_status() {
        $job = AIVT_Queue::get_job();
        if (!$job) {
            WP_CLI::log('No active job.');
            return;
        }
        WP_CLI::log(sprintf(
            'Type: %s | Status: %s | Progress: %d/%d',
            $job['type'] ?? 'geo',
            $job['status'] ?? '',
            (int) ($job['done'] ?? 0),
            (int) ($job['total'] ?? 0)
        ));
    }

    /**
     * Run a single prompt test and report whether the brand appears.
     *
     * ## OPTIONS
     *
     * <prompt>
     * : The customer-style question to ask the AI model.
     *
     * @when after_wp_load
     */
    public function prompt_run($args) {
        $this->ensure_key();
        $prompt = (string) ($args[0] ?? '');
        if ($prompt === '') {
            WP_CLI::error('Provide a prompt string.');
        }
        $res = AIVT_Prompt_Test::run($prompt);
        if (is_wp_error($res)) {
            WP_CLI::error($res->get_error_message());
        }
        $mentioned = !empty($res['mentioned']);
        WP_CLI::log('Brand mentioned: ' . ($mentioned ? 'YES' : 'no'));
        if (!empty($res['competitors_found'])) {
            WP_CLI::log('Competitors in answer: ' . implode(', ', $res['competitors_found']));
        }
        $mentioned ? WP_CLI::success('Your brand appears in the AI answer.') : WP_CLI::warning('Your brand is missing from the AI answer.');
    }

    /**
     * GEO Autopilot — generate a one-pass optimization for a page.
     *
     * Without --apply it prints the predicted score gain (dry run). With --apply
     * it writes the optimized content (a revision is saved, fully reversible).
     *
     * ## OPTIONS
     *
     * <post_id>
     * : The post/page ID to optimize.
     *
     * [--apply]
     * : Write the changes to the post. Omit for a dry-run preview.
     *
     * @when after_wp_load
     */
    public function autopilot($args, $assoc) {
        $this->ensure_key();
        if (!class_exists('AIVT_Autopilot')) {
            WP_CLI::error('Autopilot is not available in this build.');
        }
        $post_id = (int) $args[0];
        if (!get_post($post_id)) {
            WP_CLI::error("Post {$post_id} not found.");
        }
        WP_CLI::log("Running GEO Autopilot for #{$post_id}…");
        $plan = AIVT_Autopilot::plan($post_id);
        if (is_wp_error($plan)) {
            WP_CLI::error($plan->get_error_message());
        }
        WP_CLI::log(sprintf(
            'Current GEO Score: %d → predicted: %d (+%d)',
            (int) $plan['current_score'],
            (int) $plan['predicted_score'],
            max(0, (int) $plan['predicted_score'] - (int) $plan['current_score'])
        ));
        if (empty($assoc['apply'])) {
            WP_CLI::success('Dry run complete. Re-run with --apply to write the changes.');
            return;
        }
        $applied = AIVT_Autopilot::apply($post_id, $plan);
        if (is_wp_error($applied)) {
            WP_CLI::error($applied->get_error_message());
        }
        WP_CLI::success('Autopilot applied. A revision was saved — revert any time from the editor.');
    }
}
