<?php

defined('ABSPATH') or die();

add_action('wp_ajax_aiomatic_run_agent', function () {

    check_ajax_referer('aiomatic_agents_nonce', 'nonce');
    $agent_id = isset($_POST['agent_id']) ? absint($_POST['agent_id']) : 0;
    if (!current_user_can('edit_posts')) {
        wp_die(esc_html__('Unauthorized', 'aiomatic-automatic-ai-content-writer'));
    }
    $task = isset($_POST['task'])
    ? sanitize_textarea_field(wp_unslash($_POST['task']))
    : null;

    try {
        $agent = new Aiomatic_Agent($agent_id);

        update_post_meta($agent_id, '_agent_status', 'running');

        if ($task) {
            $result = $agent->reset_and_run($task);
        } else {
            $result = $agent->run();
        }

        wp_send_json_success([
            'result' => $result
        ]);

    } catch (Throwable $e) {
        wp_send_json_error([
            'message' => $e->getMessage()
        ]);
    }
});
add_action('wp_ajax_aiomatic_refine_goal', function () {

    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'No access']);
    }

    check_ajax_referer('aiomatic_agents_nonce', 'nonce');

    $agent_id = isset($_POST['agent_id']) ? intval($_POST['agent_id']) : 0;
    $goal     = isset($_POST['goal']) ? sanitize_textarea_field($_POST['goal']) : '';

    if (!$agent_id || !$goal) {
        wp_send_json_error(['message' => 'Missing data']);
    }

    $agent = new Aiomatic_Agent($agent_id);

    $description = get_post_meta($agent_id, 'aiomatic_agent_description', true);
    $expertise   = get_post_meta($agent_id, 'aiomatic_agent_expertise', true);
    $config      = $agent->get_config();
    $tools       = array_keys(Aiomatic_Agent::get_agent_tools());

    if (is_array($config['allowed_tools'])) {
        $tools = array_values(array_intersect($tools, $config['allowed_tools']));
    }

    $tools_text = implode(', ', array_slice($tools, 0, 20));

    $prompt = "
You are an expert AI task designer.

Rewrite the user's goal so it becomes a precise, structured instruction for an autonomous AI agent.

Agent context:
- Description: {$description}
- Expertise: {$expertise}
- Available tools: {$tools_text}

User input:
{$goal}

Requirements:
- Make the goal clear and actionable
- Avoid ambiguity
- If needed, break into steps implicitly (but keep as one goal)
- Infer useful constraints
- Infer expected output format

Return ONLY raw JSON.
Do not wrap it in markdown.
Do not use ```json.
Do not add explanations.

STRICTLY FOLLOW THIS JSON FORMAT:

{
  \"goal\": \"...\",
  \"constraints\": [\"...\"],
  \"output_format\": \"...\"
}
";

    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
    $appids = array_filter(preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id'] ?? '')));
    $token = !empty($appids) ? $appids[array_rand($appids)] : '';
    $token = apply_filters('aiomatic_openai_api_key', $token);

    $model = $agent->get_model();
    $aierror = '';
    $finish_reason = '';
    $thread_id = '';
    $available_tokens = 500;
    $query_token_count = count(aiomatic_encode($prompt));
    $max_tokens = aimogenpro_get_max_tokens($model);
    $available_tokens = aiomatic_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count);
    if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS)
    {
        $string_len = aiomatic_strlen($prompt);
        $string_len = $string_len / 2;
        $string_len = intval(0 - $string_len);
        $prompt = aiomatic_substr($prompt, 0, $string_len);
        $prompt = trim($prompt);
        $query_token_count = count(aiomatic_encode($prompt));
        $available_tokens = $max_tokens - $query_token_count;
    }
    if($agent->is_debug_mode())
    {
        $agent->debug_log('AI summary call: ' . print_r($prompt, true));
    }
    $response = aiomatic_generate_text($token, $model, $prompt, $available_tokens, 1, 0, 0, 0, false, 'goalRefine', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', '', $thread_id, '', 'disabled', '', false, false, array(), '', '', '');
    if($agent->is_debug_mode())
    {
        $agent->debug_log('AI goal refine response: ' . print_r($response, true));
    }
    if (!$response) {
        wp_send_json_error(['message' => 'AI failed']);
    }

    $json_raw = aiomatic_extract_json_object($response);
    $json = json_decode($json_raw, true);

    if (!is_array($json)) {
        wp_send_json_error([
            'message' => 'Invalid AI response',
            'raw'     => $response,
        ]);
    }

    if (!is_array($json)) {
        wp_send_json_error(['message' => 'Invalid AI response', 'raw'     => $response]);
    }

    wp_send_json_success([
        'goal' => isset($json['goal']) ? sanitize_textarea_field($json['goal']) : '',
        'constraints' => isset($json['constraints']) && is_array($json['constraints'])
            ? array_map('sanitize_text_field', $json['constraints'])
            : [],
        'output_format' => isset($json['output_format']) ? sanitize_text_field($json['output_format']) : ''
    ]);
});
add_action('wp_ajax_aiomatic_clear_agent_long_memory', function () {

    check_ajax_referer('aiomatic_agents_nonce', 'nonce');
    $agent_id = isset($_POST['agent_id']) ? absint($_POST['agent_id']) : 0;
    if (!$agent_id) {
        wp_send_json_error(['message' => esc_html__('Missing agent_id', 'aiomatic-automatic-ai-content-writer')]);
    }
    if (!current_user_can('edit_posts')) {
        wp_die(esc_html__('Unauthorized', 'aiomatic-automatic-ai-content-writer'));
    }

    $result = aiomatic_clear_agent_long_memory_internal($agent_id);

    if ($result['success']) {
        wp_send_json_success([
            'deleted' => $result['deleted'] ?? 0
        ]);
    } else {
        wp_send_json_error([
            'message' => $result['message']
        ]);
    }
});
add_action('wp_ajax_aiomatic_get_agent_logs', function(){
    check_ajax_referer('aiomatic_agents_nonce', 'nonce');
    global $wpdb;

    $agent_id = isset($_POST['agent_id']) ? absint($_POST['agent_id']) : 0;
    $after_id = isset($_POST['after_id']) ? absint($_POST['after_id']) : 0;
    $before_id = isset($_POST['before_id']) ? absint($_POST['before_id']) : 0;
    if (!current_user_can('edit_posts')) {
        wp_die(esc_html__('Unauthorized', 'aiomatic-automatic-ai-content-writer'));
    }
    $table = $wpdb->prefix . 'aiomatic_agent_runs';

    if ($after_id > 0) {

        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM $table 
                 WHERE agent_id = %d AND id > %d 
                 ORDER BY id ASC 
                 LIMIT 50",
                $agent_id,
                $after_id
            )
        );
    } elseif ($before_id > 0) {
        
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM $table 
                WHERE agent_id = %d AND id < %d 
                ORDER BY id DESC 
                LIMIT 50",
                $agent_id,
                $before_id
            )
        );

        if ($rows) {
            $rows = array_reverse($rows);
        }

    }
    else {

        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM $table 
                 WHERE agent_id = %d 
                 ORDER BY id DESC 
                 LIMIT 50",
                $agent_id
            )
        );

        if ($rows) {
            $rows = array_reverse($rows); 
        }
    }

    if (!$rows) {
        wp_send_json_success([]);
    }

    $logs = [];

    foreach ($rows as $row) {

        $logs[] = [
            'id'        => (int)$row->id,
            'type'      => $row->type,
            'step'      => (int)$row->step,
            'tool'      => $row->tool_name,
            'tool_name' => $row->tool_name,
            'prompt'    => $row->prompt,
            'response'  => $row->response,
            'result'    => $row->result,
            'params'    => $row->params,
            'time'      => $row->created_at,
        ];
    }

    wp_send_json_success($logs);
});
add_action('wp_ajax_aiomatic_delete_agent_logs', function(){
    check_ajax_referer('aiomatic_agents_nonce', 'nonce');
    global $wpdb;

    $agent_id = isset($_POST['agent_id']) ? absint($_POST['agent_id']) : 0;
    if (!$agent_id) {
        wp_send_json_error('Missing agent id');
    }
    if (!current_user_can('edit_posts')) {
        wp_die(esc_html__('Unauthorized', 'aiomatic-automatic-ai-content-writer'));
    }
    $table = $wpdb->prefix . 'aiomatic_agent_runs';

    $wpdb->delete($table, ['agent_id' => $agent_id], ['%d']);

    wp_send_json_success(['deleted' => true]);
});
add_action('wp_ajax_aiomatic_start_task_ajax', function(){
    check_ajax_referer('aiomatic_agents_nonce', 'nonce');
    $agent_id = isset($_POST['agent_id']) ? absint($_POST['agent_id']) : 0;
    if (!current_user_can('edit_posts')) {
        wp_die(esc_html__('Unauthorized', 'aiomatic-automatic-ai-content-writer'));
    }
    $task_raw = isset($_POST['task']) ? wp_unslash($_POST['task']) : '';

    $task = json_decode($task_raw, true);

    if (empty($task['goal'])) {
        wp_die(esc_html__('Goal is required.', 'aiomatic-automatic-ai-content-writer'));
    }
    $schedule_time_raw = isset($_POST['schedule_time']) ? sanitize_text_field($_POST['schedule_time']) : '';
    $schedule_timestamp = 0;

    if (!empty($schedule_time_raw)) {
        $schedule_timestamp = strtotime($schedule_time_raw);
        if (!$schedule_timestamp || $schedule_timestamp <= time()) {
            wp_die(esc_html__('Invalid schedule time.', 'aiomatic-automatic-ai-content-writer'));
        }
    }
    $agent = new Aiomatic_Agent($agent_id);
    $result = $agent->start_task($task, $schedule_timestamp);

    wp_send_json_success([
        'result' => $result,
        'stop_url' => wp_nonce_url(
            admin_url('admin-post.php?action=aiomatic_stop_task&agent_id=' . $agent_id),
            'aiomatic_stop_task'
        ),
    ]);
});
add_action('wp_ajax_aiomatic_get_agents_status', function(){

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('no_access');
    }

    if (
        !isset($_POST['nonce']) ||
        !wp_verify_nonce($_POST['nonce'], 'aiomatic_agents_nonce')
    ) {
        wp_send_json_error('invalid_nonce');
    }

    $ids = isset($_POST['agent_ids']) ? (array) $_POST['agent_ids'] : [];

    if (empty($ids)) {
        wp_send_json_success([]);
    }

    $result = [];

    foreach ($ids as $id) {

        $id = intval($id);
        if (!$id) continue;

        $status = get_post_meta($id, '_agent_status', true) ?: 'idle';
        $task   = get_post_meta($id, '_current_task', true);
        $last   = get_post_meta($id, '_last_activity', true);

        if (!is_string($task)) {
            $task = is_array($task) && isset($task['goal']) ? $task['goal'] : 'New Task';
        }

        $result[$id] = [
            'status' => $status,
            'task'   => wp_trim_words($task ?: '-', 10),
            'last'   => $last ? wp_date('Y-m-d H:i:s', intval($last)) : '-'
        ];
    }

    wp_send_json_success($result);
});
add_action('wp_ajax_aiomatic_get_agent_status', function(){

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('no_access');
    }
    if (
        !isset($_POST['nonce']) ||
        !wp_verify_nonce($_POST['nonce'], 'aiomatic_agents_nonce')
    ) {
        wp_send_json_error('invalid_nonce');
    }
    $id = isset($_POST['agent_id']) ? intval($_POST['agent_id']) : 0;

    if (!$id) {
        wp_send_json_error('invalid_id');
    }

    $status = get_post_meta($id, '_agent_status', true) ?: 'idle';
    $task   = get_post_meta($id, '_current_task', true);
    $last   = get_post_meta($id, '_last_activity', true);

    if (!is_string($task)) {
        $task = is_array($task) && isset($task['goal']) ? $task['goal'] : 'New Task';
    }

    wp_send_json_success([
        'status' => $status,
        'task'   => wp_trim_words($task ?: '-', 10),
        'last'   => $last ? wp_date('Y-m-d H:i:s', intval($last)) : '-'
    ]);
});
add_action('wp_ajax_aiomatic_stop_task_ajax', function(){

    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'Permission denied.']);
    }

    if (
        !isset($_POST['nonce']) ||
        !wp_verify_nonce($_POST['nonce'], 'aiomatic_agents_nonce')
    ) {
        wp_send_json_error(['message' => 'Invalid nonce.']);
    }

    $id = intval($_POST['agent_id'] ?? 0);

    if (!$id) {
        wp_send_json_error(['message' => 'Invalid agent ID.']);
    }

    $agent = new Aiomatic_Agent($id);
    $agent->stop_task();

    wp_send_json_success([
        'message' => 'Task stopped'
    ]);
});
add_action('wp_ajax_aiomatic_get_agent_task_info', function () {
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'Permission denied.']);
    }

    check_ajax_referer('aiomatic_agents_nonce', 'nonce');

    $agent_id = isset($_POST['agent_id']) ? intval($_POST['agent_id']) : 0;
    if (!$agent_id) {
        wp_send_json_error(['message' => 'Invalid agent ID.']);
    }

    $agent = new Aiomatic_Agent($agent_id);
    wp_send_json_success($agent->get_current_task_info());
});
add_action('wp_ajax_aiomatic_agents_upload', function(){

    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'No access']);
    }

    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aiomatic_agents_nonce')) {
        wp_send_json_error(['message' => 'Invalid nonce']);
    }

    if (empty($_FILES['file']['tmp_name'])) {
        wp_send_json_error(['message' => 'No file uploaded']);
    }

    $overwrite = isset($_POST['overwrite']) && $_POST['overwrite'] === '1';

    $json = file_get_contents($_FILES['file']['tmp_name']);
    if (!$json) {
        wp_send_json_error(['message' => 'Failed to read uploaded file']);
    }

    $data = json_decode($json, true);

    if (!is_array($data)) {
        wp_send_json_error(['message' => 'Invalid JSON']);
    }

    foreach ($data as $agent) {

        if (!is_array($agent)) {
            continue;
        }

        $name        = isset($agent['name']) ? sanitize_text_field($agent['name']) : 'Agent';
        $prompt      = isset($agent['prompt']) ? wp_kses_post($agent['prompt']) : '';
        $description = isset($agent['description']) ? sanitize_text_field($agent['description']) : '';
        $expertise = isset($agent['expertise']) ? sanitize_text_field($agent['expertise']) : '';
        $allowed_statuses = ['publish','draft','pending','private','future'];
        $post_status = in_array($agent['post_status'] ?? '', $allowed_statuses, true)
            ? $agent['post_status']
            : 'publish';
        $existing = null;

        if ($overwrite && !empty($name)) {
            $existing = aiomatic_get_page_by_title($name, OBJECT, 'aiomatic_agent');
        }

        if ($existing) {
            $post_id = $existing->ID;

            $update = wp_update_post([
                'ID'           => $post_id,
                'post_title'   => $name,
                'post_content' => $prompt,
                'post_status'  => $post_status
            ], true);

            if (is_wp_error($update)) {
                continue;
            }
        } else {
            $post_id = wp_insert_post([
                'post_type'   => 'aiomatic_agent',
                'post_title'  => $name,
                'post_content'=> $prompt,
                'post_status' => $post_status
            ], true);

            if (is_wp_error($post_id)) {
                continue;
            }
        }

        if (!empty($agent['model'])) {
            update_post_meta($post_id, '_model', sanitize_text_field($agent['model']));
        }
        update_post_meta($post_id, 'aiomatic_agent_description', $description);
        update_post_meta($post_id, 'aiomatic_agent_expertise', $expertise);

        if (!empty($agent['config'])) {
            $config = $agent['config'];

            if (is_string($config)) {
                $decoded = json_decode($config, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $config = $decoded;
                }
            }

            if (is_array($config)) {
                update_post_meta($post_id, '_agent_config', $config);
            }
        }
        if (!empty($agent['avatar'])) {
            $image_url = esc_url_raw($agent['avatar']);

            require_once(ABSPATH . 'wp-admin/includes/media.php');
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/image.php');

            $attachment_id = media_sideload_image($image_url, $post_id, null, 'id');

            if (!is_wp_error($attachment_id)) {
                set_post_thumbnail($post_id, $attachment_id);
            }
        }
    }

    wp_send_json_success(['message' => 'Agents imported successfully']);
});
add_action('do_meta_boxes', function() {
    remove_meta_box('postimagediv', 'aiomatic_agent', 'side');
    add_meta_box('postimagediv', 'Agent Avatar', 'post_thumbnail_meta_box', 'aiomatic_agent', 'side', 'high');
});
add_action('wp_ajax_aiomatic_default_agents', function(){

    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'No access']);
    }

    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aiomatic_agents_nonce')) {
        wp_send_json_error(['message' => 'Invalid nonce']);
    }

    $overwrite = !empty($_POST['overwrite']);

    $count = aiomatic_import_default_agents($overwrite);

    wp_send_json_success([
        'message' => "Imported {$count} agents"
    ]);
});
?>