<?php

namespace AIPT\Core;

use AIPT\Core\Database\Migrations\CreateBulkGeneratorTables;
use AIPT\Core\Database\HistoryCleaner;
use AIPT\Core\Database\JobLogCleaner;

class Activator {

    /**
     * Options that should NOT be autoloaded (autoload = false).
     *
     * These are only accessed on specific admin pages, during content generation,
     * or during one-time migrations — never on every frontend page load.
     * Keeping them out of the autoload query reduces memory and TTFB on every request.
     *
     * Options NOT in this list remain autoloaded because they are read on
     * every page load (encryption checks, chatbot widget, AI provider config).
     *
     * @var string[]
     */
    private static $non_autoload_options = [

        'system_prompt',
        'user_prompt',
        'short_system_prompt',
        'short_user_prompt',
        'full_system_prompt',
        'full_user_prompt',
        'standard_short_system_prompt',
        'standard_short_user_prompt',
        'standard_full_system_prompt',
        'standard_full_user_prompt',
        'title_additional_prompt',
        'faq_additional_prompt',
        'seo_meta_additional_prompt',
        'taxonomy_additional_prompt',
        'brand_context',
        'custom_variables',

        'store_index_enabled',
        'store_index_max_products',
        'store_index_categories',
        'store_index_stock_filter',
        'store_index_date_filter_days',
        'store_index_attributes',
        'store_index_schedule',
        'store_index_batch_size',
        'store_index_status',
        'store_index_build_progress',
        'store_index_build_job_id',

        'metabox_hidden',
        'needs_setup',
        'setup_completed',
        'first_activation',
        'first_run_completed',
        'onboarding_dismissed',
        'onboarding_snoozed_until',

        'schema_version',
        'db_version',
        'version',
        'previous_version',

        'bulk_terms_accepted',
        'credit_terms_accepted',

        'enable_tooltip',
        'prompt_priority',
        'preserve_content_images',

        'faq_display_settings',
    ];

    private static $default_values = [
        'openai_api_key' => '',
        'gemini_api_key' => '',
        'api_provider' => 'openai',
        'system_prompt' => '',
        'user_prompt' => '',
        'short_system_prompt' => 'Write a short product description in {language} using a {style} tone.

Lead with the single biggest benefit—not the product name. Include one specific detail from the product specs. Keep it punchy and scannable.',

        'short_user_prompt' => '<product_data>
Product: {title}
Category: {CATEGORIES}
Specs: {ATTRIBUTES}
Price: {REGULAR_PRICE} | Sale: {SALE_PRICE}
</product_data>

<task>
Write 2-3 sentences that hook the reader:
1. Open with the main benefit (what problem does this solve?)
2. Include one specific spec that proves the benefit
3. Make them want to read the full description
</task>',

        'full_system_prompt' => 'Write a product description in {language} using a {style} tone.

Apply the "So What?" test: for every feature, explain what it means for the customer.
Be specific—use actual details from the product data, not generic phrases.

Format: Use <p> for paragraphs, <ul><li> for feature lists, <strong> for key benefits.',

        'full_user_prompt' => '<product_data>
Product: {title}
Category: {CATEGORIES}
Specs: {ATTRIBUTES}
Price: {REGULAR_PRICE}
Sale: {SALE_PRICE}
</product_data>

<task>
Write a complete product description:
1. Open with WHY someone would want this (benefit-first, not product name)
2. Cover key features—transform each into customer value
3. Include practical details (materials, dimensions, compatibility)
4. Close with confidence (no "whether you\'re..." clichés)
</task>

<quality_check>
Before finishing: could a competitor use this exact text? If yes, add more specific details.
</quality_check>',

        'standard_short_system_prompt' => 'Write a short product description in {language} using a {style} tone.

Lead with the main benefit—not the product name. Be specific. Plain text only.',

        'standard_short_user_prompt' => '<product_data>
Product: {title}
Category: {category}
Specs: {attributes}
Price: {price}
</product_data>

<task>
Write 2-3 sentences that hook the reader:
- Open with the biggest benefit
- Include one specific detail from specs
- Make them want to read more
</task>',

        'standard_full_system_prompt' => 'Write a product description in {language} using a {style} tone.

Apply the "So What?" test: explain what each feature means for the customer.
Be specific—use actual product data, not generic phrases.

Plain text format. Use "- " for bullet points.',

        'standard_full_user_prompt' => '<product_data>
Product: {title}
Category: {category}
Specs: {attributes}
Price: {price} | Regular: {regular_price} | Sale: {sale_price}
</product_data>

<task>
Write a complete description:
1. Open with WHY someone would want this
2. Cover key features—transform each into customer value
3. Include practical details
4. Close with confidence
</task>',
        'title_additional_prompt' => '',
        'faq_additional_prompt' => '',
        'seo_meta_additional_prompt' => '',
        'taxonomy_additional_prompt' => '',
        'language' => 'English',
        'writing_style' => 'Professional',
        'content_length_preset' => 'long',
        'short_length_preset' => 'standard',
        'max_tags_count' => '3',
        'model' => 'gpt-4.1-mini',
        'enable_tooltip' => true,
        'metabox_hidden' => false,
        'preserve_content_images' => true,
        'needs_setup' => true,
        'setup_completed' => false,

        'store_index_enabled' => false,
        'store_index_max_products' => 10000,
        'store_index_categories' => [],
        'store_index_stock_filter' => 'all',
        'store_index_date_filter_days' => 0,
        'store_index_attributes' => [],
        'store_index_schedule' => 'daily',
        'store_index_batch_size' => 100,
    ];

    public static function activate() {

        if (!class_exists('WooCommerce')) {
            return;
        }

        self::handle_version_conflicts();

        try {

            $is_first_activation = get_option('aipt_first_activation', true);
            $previous_version = get_option('aipt_version', '0');

            require_once AIPT_PLUGIN_DIR . 'src/Core/Database/Migration.php';
            $migration = \AIPT\Core\Database\Migration::get_instance();
            $migration->create_activation_tables();

                if (defined('AIPT_VERSION')) {
                    update_option('aipt_schema_version', AIPT_VERSION, false);
                }

            try {
                $history_cleaner = new HistoryCleaner();
                $history_cleaner->schedule();
            } catch (\Exception $e) {

            }

            try {
                $log_cleaner = new JobLogCleaner();
                $log_cleaner->schedule();
            } catch (\Exception $e) {

            }

            try {
                \AIPT\Api\AutomationJobs\JobScheduler::setupCronSchedules();
            } catch (\Exception $e) {

            }

            if ($is_first_activation) {
                foreach (self::$default_values as $key => $value) {
                    if (get_option('aipt_' . $key) === false) {
                        $autoload = in_array($key, self::$non_autoload_options, true) ? false : null;
                        add_option('aipt_' . $key, $value, '', $autoload);
                    }
                }

                self::seed_default_templates();
            }

            self::check_and_update_setup_status();

            \AIPT\Utils\ApiKeyManager::migrate_keys_if_needed();

            if ($is_first_activation) {
                update_option('aipt_first_activation', false, false);
            }
            update_option('aipt_version', AIPT_VERSION, false);

            if (version_compare($previous_version, '2.6.0', '<') && version_compare($previous_version, '0', '>')) {
                self::migrate_to_optimized_prompts();
            }

            if ( version_compare( $previous_version, '0', '>' ) && get_option( 'aipt_quickstart_completed' ) === false ) {
                update_option( 'aipt_quickstart_completed', true, false );
            }

            self::ensure_preset_defaults();

            self::migrate_store_index_build_state();

            self::optimize_autoload_settings();

        } catch (\Exception $e) {

            set_transient('aipt_database_error',
                sprintf(
                    /* translators: %1$s: previous version, %2$s: current version, %3$s: error message */
                    __('Plugin upgrade from version %1$s to %2$s failed. Please try again or contact support if the problem persists. Error: %3$s', 'ai-product-tools'),
                    $previous_version,
                    AIPT_VERSION,
                    $e->getMessage()
                ),
                60 
            );

            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
            deactivate_plugins(plugin_basename(AIPT_PLUGIN_DIR . 'ai-product-tools.php'));

            if (isset($_GET['activate'])) {
                unset($_GET['activate']);
            }
        }
    }

    public static function get_default_value($key) {
        return isset(self::$default_values[$key]) ? self::$default_values[$key] : '';
    }

    private static function ensure_preset_defaults() {
        $content_preset = get_option('aipt_content_length_preset', '');
        $short_preset = get_option('aipt_short_length_preset', '');

        $valid_content_presets = array('short', 'medium', 'long', 'very_long');
        $valid_short_presets = array('brief', 'standard', 'detailed');

        if (empty($content_preset) || !in_array($content_preset, $valid_content_presets, true)) {
            update_option('aipt_content_length_preset', 'long');
        }

        if (empty($short_preset) || !in_array($short_preset, $valid_short_presets, true)) {
            update_option('aipt_short_length_preset', 'standard');
        }
    }

    /**
     * Setup durumunu kontrol et ve güncelle
     * Her activation'da çağrılmalı
     */
    public static function check_and_update_setup_status() {

        $has_any_api_key = false;

        if (class_exists('\AIPT\Utils\ApiKeyManager')) {
            $has_any_api_key = \AIPT\Utils\ApiKeyManager::has_any_api_key();
        } else {

            $openai_api_key = get_option('aipt_openai_api_key', '');
            $gemini_api_key = get_option('aipt_gemini_api_key', '');
            $claude_api_key = get_option('aipt_claude_api_key', '');
            $has_any_api_key = !empty($openai_api_key) || !empty($gemini_api_key) || !empty($claude_api_key);
        }

        $needs_setup = !$has_any_api_key;
        $setup_completed = $has_any_api_key;

        update_option('aipt_needs_setup', $needs_setup, false);
        update_option('aipt_setup_completed', $setup_completed, false);

        if (defined('WP_DEBUG') && WP_DEBUG) {

        }

        return $setup_completed;
    }

    /**
     * Setup gerekip gerekmediğini kontrol et
     */
    public static function requires_setup() {

        self::check_and_update_setup_status();

        $needs_setup = get_option('aipt_needs_setup', true);
        $setup_completed = get_option('aipt_setup_completed', false);

        if ($needs_setup === false && $setup_completed === true) {

            return false;
        }

        if ($needs_setup === true || $setup_completed === false) {

            return true;
        }

        if (class_exists('\AIPT\Utils\ApiKeyManager')) {
            return !\AIPT\Utils\ApiKeyManager::has_any_api_key();
        }

        $openai_api_key = get_option('aipt_openai_api_key', '');
        $gemini_api_key = get_option('aipt_gemini_api_key', '');
        $claude_api_key = get_option('aipt_claude_api_key', '');
        return empty($openai_api_key) && empty($gemini_api_key) && empty($claude_api_key);
    }

    /**
     * Migrate AI Store Index build state for optimization update.
     *
     * Cancels any in-progress builds that use old OFFSET pagination
     * and cleans up legacy transient storage.
     */
    private static function migrate_store_index_build_state() {

        if (function_exists('as_unschedule_all_actions')) {
            as_unschedule_all_actions('aipt_build_store_index', [], 'aipt-store-index');
        }

        delete_transient('aipt_index_build_data');

        $status = get_option('aipt_store_index_status', 'idle');
        if ($status === 'building') {
            update_option('aipt_store_index_status', 'idle', false);
            update_option('aipt_store_index_build_progress', 0, false);
            update_option('aipt_store_index_build_job_id', 0, false);
        }
    }

    /**
     * Migrate users to optimized prompt system (v2.6.0+)
     * 
     * Clears old verbose default prompts if user hasn't customized them.
     * This allows PromptFactory's optimized base prompts to take effect.
     */
    private static function migrate_to_optimized_prompts() {

        $old_defaults = [
            'short_system_prompt' => [
                'You are a professional product description writer specializing in e-commerce',
                'Make it engaging and action-driven',
            ],
            'short_user_prompt' => [
                'Write a compelling short description in {language}',
                'Focus on the product\'s key features and value',
            ],
            'full_system_prompt' => [
                'You are an expert product description writer for e-commerce',
                'Begin with a compelling introduction that captures attention',
            ],
            'full_user_prompt' => [
                'Write a detailed product description in {language}',
                'Introduction – Briefly introduce the product',
                'Key Features – List important features',
            ],
            'standard_short_system_prompt' => [
                'You are a product description expert',
                'Create a compelling short description',
            ],
            'standard_short_user_prompt' => [
                'Write a short description in {language}',
                'Product Information:',
            ],
            'standard_full_system_prompt' => [
                'You are an e-commerce product description expert',
                'Create a comprehensive description',
            ],
            'standard_full_user_prompt' => [
                'Write a detailed description in {language}',
                'Product Information:',
            ],
        ];

        foreach ($old_defaults as $option_key => $fingerprints) {
            $current_value = get_option('aipt_' . $option_key, '');
            
            if (empty($current_value)) {
                continue;
            }

            $is_old_default = true;
            foreach ($fingerprints as $fingerprint) {
                if (strpos($current_value, $fingerprint) === false) {
                    $is_old_default = false;
                    break;
                }
            }

            if ($is_old_default) {
                $new_default = self::get_default_value($option_key);
                update_option('aipt_' . $option_key, $new_default);
            }
        }
    }

    /**
     * Handle version conflicts during activation
     * Automatically deactivates conflicting versions
     */
    private static function handle_version_conflicts() {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $current_plugin = plugin_basename(AIPT_PLUGIN_DIR . 'ai-product-tools.php');
        $conflicting_plugins = [];

        $possible_conflicts = [
            'ai-product-tools/ai-product-tools.php',           
            'ai-product-tools-premium/ai-product-tools.php',  
            'ai-product-tools-pro/ai-product-tools.php'       
        ];

        foreach ($possible_conflicts as $plugin_path) {
            if ($plugin_path !== $current_plugin && is_plugin_active($plugin_path)) {
                $conflicting_plugins[] = $plugin_path;
            }
        }

        if (!empty($conflicting_plugins)) {
            foreach ($conflicting_plugins as $conflict_plugin) {
                deactivate_plugins($conflict_plugin, true); 
            }

            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
        }
    }

    /**
     * Seed default prompt templates on first activation.
     *
     * Inserts pre-built templates for description and standard generators
     * so users have a starting point in the Prompt Templates tab.
     */
    private static function seed_default_templates(): void {
        global $wpdb;

        $table_name = $wpdb->prefix . 'aipt_prompt_templates';

        $table_exists = $wpdb->get_var(
            $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name )
        );

        if ( $table_exists !== $table_name ) {
            return;
        }

        $existing_count = (int) $wpdb->get_var(

            "SELECT COUNT(*) FROM {$table_name}"
        );

        if ( $existing_count > 0 ) {
            return;
        }

        $now = current_time( 'mysql' );

        $templates = [
            [
                'name'           => 'Default Description Prompts',
                'description'    => 'Pre-configured prompts for the Advanced Bulk Description Generator.',
                'generator_type' => 'description',
                'prompt_data'    => wp_json_encode( [
                    'system_prompt'     => self::get_default_value( 'short_system_prompt' ),
                    'user_prompt'       => self::get_default_value( 'short_user_prompt' ),
                    'additional_prompt' => '',
                ] ),
                'is_default'     => 1,
                'source'         => 'local',
                'created_at'     => $now,
                'updated_at'     => $now,
            ],
            [
                'name'           => 'Default Standard Prompts',
                'description'    => 'Pre-configured prompts for the Standard Bulk Description Generator.',
                'generator_type' => 'standard',
                'prompt_data'    => wp_json_encode( [
                    'system_prompt'     => self::get_default_value( 'standard_short_system_prompt' ),
                    'user_prompt'       => self::get_default_value( 'standard_short_user_prompt' ),
                    'additional_prompt' => '',
                ] ),
                'is_default'     => 1,
                'source'         => 'local',
                'created_at'     => $now,
                'updated_at'     => $now,
            ],
        ];

        foreach ( $templates as $template ) {

            $wpdb->insert(
                $table_name,
                $template,
                [ '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' ]
            );
        }
    }

    /**
     * Optimize autoload settings for existing options.
     *
     * Moves admin-only and rarely-used options out of the autoload query.
     * Uses wp_set_option_autoload_values() on WP 6.6+, direct SQL on older versions.
     * Idempotent — safe to call on every activation.
     */
    private static function optimize_autoload_settings(): void {
        $option_names = array_map(
            static function ( $key ) {
                return 'aipt_' . $key;
            },
            self::$non_autoload_options
        );

        if ( empty( $option_names ) ) {
            return;
        }

        if ( function_exists( 'wp_set_option_autoload_values' ) ) {
            $autoload_map = array_fill_keys( $option_names, false );
            \wp_set_option_autoload_values( $autoload_map );
            return;
        }

        global $wpdb;
        $placeholders = implode( ',', array_fill( 0, count( $option_names ), '%s' ) );

        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ({$placeholders}) AND autoload != 'no'",
                $option_names
            )
        );

        wp_cache_delete( 'alloptions', 'options' );
    }

    /**
     * Check if an option key should be autoloaded.
     *
     * @param string $key Option key without aipt_ prefix.
     * @return bool True if the option should be autoloaded.
     */
    public static function should_autoload( string $key ): bool {
        return ! in_array( $key, self::$non_autoload_options, true );
    }
}
