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

/**
 * Automation Actions
 *
 * Registers and handles automation actions (Step executors).
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/automation/actions
 */

class Kitsune_AI_Platform_Automation_Actions {

    public function __construct() {
        // Listen for the execution hook fired by Triggers
        add_action('kitsune_ai_platform_execute_workflow', array($this, 'execute_workflow'), 10, 3);
    }

    /**
     * Get list of registered actions for UI
     * 
     * Each action includes:
     * - label: Human-readable name
     * - description: Short explanation shown as subtitle
     * - config_fields: Configuration options for the action
     */
    public function get_registered_actions() {
        return array(
            'update_kb' => array(
                'label' => __('Update Knowledge Base', 'kitsune-ai-platform'),
                'description' => __('Delete and recreate content in a Vector Database for AI chatbot knowledge', 'kitsune-ai-platform'),
                'config_fields' => array(
                    array(
                        'name' => 'kb_source',
                        'label' => __('Select Knowledge Base', 'kitsune-ai-platform'),
                        'type' => 'kb_selector' // UI component needs to handle this
                    ),
                    array(
                        'name' => 'data_source',
                        'label' => __('Data Source', 'kitsune-ai-platform'),
                        'type' => 'radio',
                        'options' => array(
                            'trigger' => __('From Trigger', 'kitsune-ai-platform'),
                            'select_post' => __('Select Specific Post', 'kitsune-ai-platform')
                        ),
                        'default' => 'trigger'
                    ),
                    array(
                        'name' => 'content_template',
                        'label' => __('Content Template', 'kitsune-ai-platform'),
                        'type' => 'textarea',
                        'rows' => 5,
                        'placeholder' => __('Compose content using trigger variables, e.g.:
{{post_title}}

{{post_content}}

Author: {{post_author}}', 'kitsune-ai-platform'),
                        'depends_on' => array('data_source' => 'trigger')
                    ),
                    array(
                        'name' => 'post_type_select',
                        'label' => __('Post Type', 'kitsune-ai-platform'),
                        'type' => 'post_type_selector', // Shows when data_source = 'select_post'
                        'depends_on' => array('data_source' => 'select_post')
                    ),
                    array(
                        'name' => 'post_id_select',
                        'label' => __('Select Post', 'kitsune-ai-platform'),
                        'type' => 'post_selector', // Dynamic dropdown based on post_type_select
                        'depends_on' => array('data_source' => 'select_post')
                    )
                )
            ),
            'create_kb' => array(
                'label' => __('Create Knowledge Base', 'kitsune-ai-platform'),
                'description' => __('Create a new Knowledge Base source for the AI chatbot', 'kitsune-ai-platform'),
                'config_fields' => array(
                    array(
                        'name' => 'kb_name',
                        'label' => __('Knowledge Base Name', 'kitsune-ai-platform'),
                        'type' => 'text',
                        'placeholder' => __('e.g. Product Docs or {{post_title}}', 'kitsune-ai-platform')
                    ),
                    array(
                        'name' => 'initial_content_source',
                        'label' => __('Initial Content', 'kitsune-ai-platform'),
                        'type' => 'radio',
                        'options' => array(
                            'none'    => __('Empty (no initial content)', 'kitsune-ai-platform'),
                            'trigger' => __('From Trigger', 'kitsune-ai-platform')
                        ),
                        'default' => 'none'
                    ),
                    array(
                        'name' => 'content_template',
                        'label' => __('Content Template', 'kitsune-ai-platform'),
                        'type' => 'textarea',
                        'rows' => 5,
                        'placeholder' => __('Compose content using trigger variables, e.g.:
{{post_title}}

{{post_content}}

Author: {{post_author}}', 'kitsune-ai-platform'),
                        'depends_on' => array('initial_content_source' => 'trigger')
                    ),
                    array(
                        'name' => 'sync_after_create',
                        'label' => __('Sync After Create', 'kitsune-ai-platform'),
                        'type' => 'checkbox',
                        'checkbox_label' => __('Sync to vector database', 'kitsune-ai-platform'),
                        'default' => false
                    )
                )
            ),
            'delete_kb' => array(
                'label' => __('Delete Knowledge Base', 'kitsune-ai-platform'),
                'description' => __('Permanently delete a Knowledge Base source and all its embeddings', 'kitsune-ai-platform'),
                'config_fields' => array(
                    array(
                        'name' => 'kb_source',
                        'label' => __('Knowledge Base to Delete', 'kitsune-ai-platform'),
                        'type' => 'kb_selector'
                    ),
                    array(
                        'name' => 'confirm_delete',
                        'label' => __('Confirm Deletion', 'kitsune-ai-platform'),
                        'type' => 'radio',
                        'options' => array(
                            'yes' => __('Yes, permanently delete this KB source', 'kitsune-ai-platform'),
                            'no'  => __('No, keep it (skip this action)', 'kitsune-ai-platform')
                        ),
                        'default' => 'no'
                    )
                )
            ),
            'send_email' => array(
                'label' => __('Send Email', 'kitsune-ai-platform'),
                'description' => __('Send an email notification to specified recipients', 'kitsune-ai-platform'),
                'config_fields' => array(
                    array(
                        'name' => 'email_source',
                        'label' => __('Email Content Source', 'kitsune-ai-platform'),
                        'type' => 'radio',
                        'options' => array(
                            'trigger' => __('From Trigger (Dynamic Content)', 'kitsune-ai-platform'),
                            'custom'  => __('Custom Message', 'kitsune-ai-platform')
                        ),
                        'default' => 'custom'
                    ),
                    array(
                        'name' => 'to',
                        'label' => __('To Email', 'kitsune-ai-platform'),
                        'type' => 'text',
                        'placeholder' => __('user@example.com or {{post_author_email}}', 'kitsune-ai-platform')
                    ),
                    array(
                        'name' => 'subject',
                        'label' => __('Subject', 'kitsune-ai-platform'),
                        'type' => 'text',
                        'placeholder' => __('Email subject — supports {{variables}}, e.g. New post: {{post_title}}', 'kitsune-ai-platform')
                    ),
                    array(
                        'name' => 'message',
                        'label' => __('Message (Custom)', 'kitsune-ai-platform'),
                        'type' => 'textarea',
                        'rows' => 4,
                        'placeholder' => __('Static message body (supports {{variables}})', 'kitsune-ai-platform'),
                        'depends_on' => array('email_source' => 'custom')
                    ),
                    array(
                        'name' => 'message',
                        'label' => __('Message Template', 'kitsune-ai-platform'),
                        'type' => 'textarea',
                        'rows' => 5,
                        'placeholder' => __('Compose email body using trigger variables, e.g.:
Post: {{post_title}}

{{post_content}}

URL: {{post_url}}', 'kitsune-ai-platform'),
                        'depends_on' => array('email_source' => 'trigger')
                    )
                )
            )
        );
    }

    /**
     * Main Execution Entry Point
     */
    public function execute_workflow($workflow_id, $config, $context) {
        $trigger = $config['trigger'];
        if (empty($trigger['actions']) || !is_array($trigger['actions'])) {
            return;
        }

        do_action('kitsune_ai_platform_workflow_execution_started', $workflow_id, $config, $context);

        // Execute parallel branches
        foreach ($trigger['actions'] as $action_node) {
            $this->process_action_chain($action_node, $context, $workflow_id);
        }

        do_action('kitsune_ai_platform_workflow_executed', $workflow_id, $config, $context);
        Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
            Kitsune_AI_Platform_Webhook_Events::WORKFLOW_EXECUTED,
            array(
                'workflow_id' => (int) $workflow_id,
                'context_keys' => array_keys(is_array($context) ? $context : array()),
                'actor_id' => get_current_user_id(),
            )
        );
    }

    /**
     * Process Chain of Actions recursively
     */
    private function process_action_chain($node, $context, $workflow_id) {
        if (empty($node)) return;

        // Execute current action
        $success = $this->run_action($node, $context);
        
        // Log result
        do_action('kitsune_ai_platform_log_workflow', $workflow_id, $success ? 'info' : 'error', 
            sprintf(
                /* translators: 1: Action type key, 2: Execution result label. */
                __('Action %1$s: %2$s', 'kitsune-ai-platform'),
                $node['action_type'],
                $success ? __('Success', 'kitsune-ai-platform') : __('Failed', 'kitsune-ai-platform')
            ),
            array('action' => $node, 'context_keys' => array_keys($context))
        );

        if ($success && !empty($node['next_action'])) {
            $this->process_action_chain($node['next_action'], $context, $workflow_id);
        }
    }

    /**
     * Run Specific Action Logic
     */
    private function run_action($node, $context) {
        $type = $node['action_type'];
        $config = $node['config'] ?? array();

        switch ($type) {
            case 'update_kb':
                return $this->handle_update_kb($config, $context);
            case 'create_kb':
                return $this->handle_create_kb($config, $context);
            case 'delete_kb':
                return $this->handle_delete_kb($config, $context);
            case 'send_email':
                return $this->handle_send_email($config, $context);
            default:
                return false;
        }
    }

    /**
     * Action: Update Knowledge Base
     */
    private function handle_update_kb($config, $context) {
        if (empty($config['kb_source'])) return false;

        $source_id = intval($config['kb_source']);
        $content = '';
        $content_id = 0;

        // Determine content source
        $data_source = isset($config['data_source']) ? $config['data_source'] : 'trigger';

        if ($data_source === 'select_post' && !empty($config['post_id_select'])) {
            // Get content from selected post
            $post_id = intval($config['post_id_select']);
            $post = get_post($post_id);
            if ($post) {
                $content = $post->post_title . "\n\n" . wp_strip_all_tags($post->post_content);
                $content_id = $post_id;
            }
        } else {
            // From Trigger — use user-defined template if provided, otherwise auto-build
            $content_id = $context['post_id'] ?? 0;
            if (!empty($config['content_template'])) {
                $content = wp_strip_all_tags($this->replace_vars($config['content_template'], $context));
            } else {
                if (isset($context['post_content'])) $content = wp_strip_all_tags($context['post_content']);
                elseif (isset($context['comment_content'])) $content = wp_strip_all_tags($context['comment_content']);
                if (isset($context['post_title'])) {
                    $content = $context['post_title'] . "\n\n" . $content;
                }
            }
        }

        if (empty($content)) return false;

        // Split content into chunks respecting KB settings
        $chunking_rules = $this->get_kb_chunking_rules();
        $chunks = $this->chunk_text_for_embeddings($content, $chunking_rules['size'], $chunking_rules['overlap']);

        if (empty($chunks)) return false;

        global $wpdb;
        $table = $wpdb->prefix . 'kitsune_ai_platform_embeddings';
        $inserted = 0;

        foreach ($chunks as $chunk_text) {
            $result = $wpdb->insert($table, array(
                'source_id'  => $source_id,
                'content_id' => $content_id,
                'chunk_text' => $chunk_text,
                'vector_id'  => 'pending_processing',
                'status'     => 'pending',
                'created_at' => current_time('mysql'),
            ));
            if ($result !== false) {
                $inserted++;
            }
        }

        return $inserted > 0;
    }

    /**
     * Action: Create Knowledge Base
     */
    private function handle_create_kb($config, $context) {
        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-kb-source-model.php';
        $model = new Kitsune_AI_Platform_KB_Source_Model();

        $name = $this->replace_vars($config['kb_name'] ?? __('Auto Created KB', 'kitsune-ai-platform'), $context);
        $name = sanitize_text_field($name);

        $data = array(
            'name'   => $name,
            'type'   => 'paste',
            'status' => 'pending',
        );

        // Seed with trigger content if requested
        $content_source = $config['initial_content_source'] ?? 'none';
        if ($content_source === 'trigger') {
            // Use user-defined template if provided, otherwise auto-build from context
            if (!empty($config['content_template'])) {
                $content = $this->replace_vars($config['content_template'], $context);
            } else {
                $content = '';
                if (!empty($context['post_title'])) {
                    $content .= $context['post_title'] . "\n\n";
                }
                $content .= $context['post_content'] ?? $context['comment_content'] ?? '';
            }
            $data['paste'] = array(
                'name'    => $name,
                'content' => substr($content, 0, 10000)
            );
        }

        $post_id = $model->create($data);
        if (is_wp_error($post_id) || $post_id <= 0) {
            return false;
        }

        // Optionally sync (generate embeddings) immediately after creation
        if (!empty($config['sync_after_create'])) {
            do_action('kitsune_ai_platform_kb_sync_source', $post_id);
        }

        return true;
    }

    /**
     * Action: Delete Knowledge Base
     */
    private function handle_delete_kb($config, $context) {
        if (empty($config['kb_source'])) return false;
        if (($config['confirm_delete'] ?? 'no') !== 'yes') return true; // Skipped intentionally

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-kb-source-model.php';
        $model = new Kitsune_AI_Platform_KB_Source_Model();

        $source_id = intval($config['kb_source']);

        // Delete associated embeddings first
        global $wpdb;
        $table = $wpdb->prefix . 'kitsune_ai_platform_embeddings';
        $wpdb->delete($table, array('source_id' => $source_id));

        $result = $model->delete($source_id);
        return !is_wp_error($result);
    }

    /**
     * Action: Send Email
     */
    private function handle_send_email($config, $context) {
        $to      = $this->replace_vars($config['to'] ?? get_option('admin_email'), $context);
        $subject = $this->replace_vars($config['subject'] ?? __('Notification', 'kitsune-ai-platform'), $context);
        $message = $this->replace_vars($config['message'] ?? '', $context);

        return wp_mail($to, $subject, $message);
    }

    /**
     * Read chunk size and overlap from KB settings.
     *
     * @return array{size: int, overlap: int}
     */
    private function get_kb_chunking_rules() {
        $settings     = get_option('kitsune_ai_platform_kb_settings', array());
        $chunk_size   = max(128, min(2048, intval($settings['chunkSize']   ?? 512)));
        $chunk_overlap = max(0,   min(200,  intval($settings['chunkOverlap'] ?? 50)));

        if ($chunk_overlap >= $chunk_size) {
            $chunk_overlap = max(0, $chunk_size - 1);
        }

        return array(
            'size'    => $chunk_size,
            'overlap' => $chunk_overlap,
        );
    }

    /**
     * Split text into overlapping word-based chunks.
     *
     * @param string $text
     * @param int    $chunk_size    Chunk size in words.
     * @param int    $chunk_overlap Overlap in words.
     * @return string[]
     */
    private function chunk_text_for_embeddings($text, $chunk_size, $chunk_overlap) {
        $normalized = trim(preg_replace('/\s+/', ' ', wp_strip_all_tags((string) $text)));
        if ($normalized === '') {
            return array();
        }

        $words = preg_split('/\s+/', $normalized);
        if (!is_array($words) || empty($words)) {
            return array();
        }

        $chunk_size    = max(1, intval($chunk_size));
        $chunk_overlap = max(0, min($chunk_size - 1, intval($chunk_overlap)));
        $step          = max(1, $chunk_size - $chunk_overlap);

        $chunks = array();
        $total  = count($words);
        for ($start = 0; $start < $total; $start += $step) {
            $slice = array_slice($words, $start, $chunk_size);
            if (empty($slice)) {
                break;
            }

            $chunk = trim(implode(' ', $slice));
            if ($chunk !== '') {
                $chunks[] = $chunk;
            }

            if ($start + $chunk_size >= $total) {
                break;
            }
        }

        return $chunks;
    }

    /**
     * Helper: Replace variables {{post_title}} etc.
     */
    private function replace_vars($text, $context) {
        foreach ($context as $key => $value) {
            if (is_string($value) || is_numeric($value)) {
                $text = str_replace('{{' . $key . '}}', $value, $text);
            }
        }
        return $text;
    }
}
