<?php

defined('ABSPATH') or die();

register_activation_hook(__FILE__, function () {
    Aiomatic_Agent::install_schema();
    update_option('aimogen_agents_db_version', Aiomatic_Agent::DB_VERSION);
});
add_action('admin_init', function () {
    $installed = get_option('aimogen_agents_db_version');
    if ($installed !== Aiomatic_Agent::DB_VERSION) {
        Aiomatic_Agent::install_schema();
        update_option('aimogen_agents_db_version', Aiomatic_Agent::DB_VERSION);
    }
});
add_action('before_delete_post', function ($post_id) {
    $post = get_post($post_id);
    if (!$post || $post->post_type !== 'aiomatic_agent') {
        return;
    }
    Aiomatic_Agent::cleanup_agent_data($post_id);
});


add_action('admin_post_aiomatic_run_agent', function(){
    check_admin_referer('aiomatic_run_agent');

    $id = isset($_GET['agent_id']) ? absint($_GET['agent_id']) : 0;

    if (!current_user_can('edit_post', $id)) {
        wp_die(esc_html__('Permission denied.', 'aiomatic-automatic-ai-content-writer'));
    }
    update_post_meta($id, '_agent_status', 'running');

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

    wp_safe_redirect(wp_get_referer() ?: admin_url());
    exit;
});

add_action('admin_post_aiomatic_pause_agent', function(){
    check_admin_referer('aiomatic_pause_agent');

    $id = isset($_GET['agent_id']) ? absint($_GET['agent_id']) : 0;

    if (!current_user_can('edit_post', $id)) {
        wp_die(esc_html__('Permission denied.', 'aiomatic-automatic-ai-content-writer'));
    }
    $agent = new Aiomatic_Agent($id);
    $agent->kill();

    wp_safe_redirect(wp_get_referer() ?: admin_url());
    exit;
});

add_action('admin_post_aiomatic_resume_agent', function(){
    check_admin_referer('aiomatic_resume_agent');

    $id = isset($_GET['agent_id']) ? absint($_GET['agent_id']) : 0;

    if (!current_user_can('edit_post', $id)) {
        wp_die('Permission denied.');
    }

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

    wp_safe_redirect(wp_get_referer() ?: admin_url());
    exit;
});

add_action('aiomatic_agent_run_single', function($agent_id, $task){

    try {
        update_post_meta($agent_id, '_agent_status', 'running');
        $agent = new Aiomatic_Agent($agent_id);
        $result = $agent->run($task);

        update_post_meta($agent_id, '_task_finished_at', time());
        update_post_meta($agent_id, '_task_result', $result);

    } catch (Throwable $e) {

        update_post_meta($agent_id, '_agent_status', 'failed');
        update_post_meta($agent_id, '_task_result', $e->getMessage());
    }

}, 10, 2);
add_action('aiomatic_agents_watchdog', function() {
    $agents = get_posts([
        'post_type'      => 'aiomatic_agent',
        'post_status'    => 'publish',
        'posts_per_page' => 50,
        'fields'         => 'ids',
        'no_found_rows'  => true,
        'update_post_meta_cache' => false,
        'update_post_term_cache' => false,
        'meta_query'     => [
            [
                'key'   => '_agent_status',
                'value' => 'running',
            ]
        ],
    ]);

    if (empty($agents)) {
        wp_clear_scheduled_hook('aiomatic_agents_watchdog');
        return;
    }
    foreach ($agents as $agent_id) {
        $last = (int) get_post_meta($agent_id, '_last_activity', true);

        if (!$last) {
            continue;
        }

        if ((time() - $last) > 3600) {
            $recover_count = (int) get_post_meta($agent_id, '_agent_recover_count', true);
            if ($recover_count >= 2) {
                update_post_meta($agent_id, '_agent_status', 'failed');
            }
            else
            {
                $status = get_post_meta($agent_id, '_agent_status', true);
                if ($status !== 'running') {
                    continue;
                }
                update_post_meta($agent_id, '_agent_status', 'interrupted');
                update_post_meta($agent_id, '_agent_recover_count', $recover_count + 1);

                if (!wp_next_scheduled('aiomatic_agent_recover', [$agent_id])) {
                    wp_schedule_single_event(time() + 5, 'aiomatic_agent_recover', [$agent_id]);
                }
            }
        }
    }
});
add_action('aiomatic_agent_recover', function($agent_id){
    $status = get_post_meta($agent_id, '_agent_status', true);
    $last = (int) get_post_meta($agent_id, '_last_activity', true);
    if ($status === 'running') {
        if ($last && (time() - $last > 86400)) {
            update_post_meta($agent_id, '_agent_status', 'interrupted');
            $status = 'interrupted';
        } else {
            return;
        }
    }
    if ($status !== 'interrupted') {
        return;
    }
    update_post_meta($agent_id, '_agent_status', 'running');
    $agent = new Aiomatic_Agent($agent_id);
    $agent->run();
});
add_action('admin_post_aiomatic_kill_agent', function() {
    check_admin_referer('aiomatic_kill_agent');
    $agent_id = isset($_GET['agent_id']) ? absint($_GET['agent_id']) : 0;
    if (!current_user_can('edit_post', $agent_id)) 
    {
        wp_die(esc_html__('Unauthorized', 'aiomatic-automatic-ai-content-writer'));
    }
    $agent = new Aiomatic_Agent($agent_id);
    $agent->kill();

    wp_safe_redirect(admin_url("post.php?post={$agent_id}&action=edit&message=agent_killed"));
    exit;
});
add_filter('default_content', function($content, $post){

    if ($post->post_type === 'aiomatic_agent') {
        return "You are an autonomous AI agent that executes tasks step by step until they are completed. You run on a WordPress site.

Role:
- Define your role clearly (e.g. content writer, SEO analyst, automation agent)
- Stay consistent with this role

Behavior:
- Understand the user goal before acting
- Break tasks into steps if needed
- Use tools only when required to achieve the goal
- Do NOT repeat the same action if it already succeeded
- Do NOT ask the user questions. You must act autonomously.
- If information is missing, make reasonable assumptions and proceed.
- Never wait for user confirmation.
- If a tool returns success and the goal is achieved, STOP

Completion rules:
- A task is complete when the user goal is fulfilled
- After completion, you MUST return a FINAL ANSWER
- Do NOT continue working after the goal is achieved
- Do NOT call the same tool multiple times for the same result

Tool usage:
- Only call tools when necessary
- Always provide correct and complete parameters
- If a tool fails, fix the input and retry (within limits)
- If a tool succeeds, do not call it again unless absolutely required

Constraints:
- Follow all user-defined constraints strictly
- Avoid unnecessary steps, loops, or repeated actions
- Be efficient (each step has cost)

Output format:
- Always follow the requested output format
- If no format is specified, return a clear and concise answer

Notes:
- You can customize this behavior by editing this prompt.
- Clear instructions lead to better and more predictable results.";
    }

    return $content;

}, 10, 2);
add_action('edit_form_after_editor', function($post){
    if ($post->post_type !== 'aiomatic_agent') return;

    echo '<div class="aiomatic-editor-wrapper">';
    echo '<div class="aiomatic-tip">';
    echo '<strong>' . esc_html__('Tip:', 'aiomatic-automatic-ai-content-writer') . '</strong> Be explicit. Define role, tone, and output format.<br>';
    echo 'Example: "You are an SEO expert. Always provide structured, actionable recommendations."';
    echo '</div>';
    $agent_tmp = new Aiomatic_Agent($post->ID);
    $tools = $agent_tmp->get_agent_tools();
    
    echo '<div class="aiomatic-tip">';
    echo '<div class="aiomatic-tools-info">';

    echo '<div class="aiomatic-tools-toggle" style="cursor:pointer; font-weight:600; margin-top:10px;">';
    echo '▶ Available Tools (' . count($tools) . ')';
    echo '</div>';

    echo '<div class="aiomatic-tools-list" style="display:none; margin-top:10px; border:1px solid #ddd; padding:10px; max-height:250px; overflow:auto;">';

    foreach ($tools as $tool) {
        echo '<div class="aiomatic-tool-item" style="margin-bottom:8px;">';

        echo '<div class="aiomatic-tool-header" style="cursor:pointer;">';
        echo '<strong>' . esc_html($tool['name']) . '</strong>';
        echo '</div>';

        echo '<div class="aiomatic-tool-body" style="display:none; margin-left:10px;">';
        echo '<div style="color:#666;">' . esc_html($tool['description']) . '</div>';

        if (!empty($tool['parameters']['properties']) && is_array($tool['parameters']['properties'])) {
            echo '<ul style="margin-top:5px;">';
            foreach ($tool['parameters']['properties'] as $pname => $p) {
                echo '<li><strong>' . esc_html($pname) . '</strong>: ' . esc_html($p['description'] ?? '') . '</li>';
            }
            echo '</ul>';
        }

        echo '</div>';
        echo '</div>';
    }

    echo '</div>';
    echo '</div>';
    echo '</div>';
    echo '</div>';
});
add_action('admin_head', function () {

    $screen = get_current_screen();

    if ($screen && $screen->post_type === 'aiomatic_agent') {
        remove_action('media_buttons', 'media_buttons');
    }

});
add_action('admin_enqueue_scripts', function($hook){
    if ($hook !== 'post.php' && $hook !== 'post-new.php') {
        return;
    }
    $screen = get_current_screen();
    if (!$screen || $screen->post_type !== 'aiomatic_agent') {
        return;
    }
    wp_enqueue_script(
        'aiomatic-agent-admin',
        plugin_dir_url(__FILE__) . '../scripts/aiomatic-agent-admin.js',
        ['jquery'],
        '1.0',
        true
    );
    wp_localize_script('aiomatic-agent-admin', 'aiomaticAgent', [
        'backUrl' => admin_url('admin.php?page=aiomatic_agents_panel#tab-6'),
        'nonce' => wp_create_nonce('aiomatic_agents_nonce'),
        'ajaxurl' => admin_url('admin-ajax.php')
    ]);
    wp_enqueue_style(
        'aiomatic-agent-admin',
        plugin_dir_url(__FILE__) . '../styles/aiomatic-agent-admin.css',
        [],
        '1.0'
    );
});
add_action('edit_form_after_title', function($post){
    if ($post->post_type !== 'aiomatic_agent') return;
    echo '<div class="aiomatic-prompt-header">';
    echo '<div class="aiomatic-prompt-title">Define The System Prompt Below</div>';
    echo '<div class="aiomatic-prompt-desc">';
    echo 'Define how this AI agent behaves. This controls role, tone, rules, and output.';
    echo '</div>';
    echo '</div>';
});
add_action('post_submitbox_misc_actions', function($post){

    if ($post->post_type !== 'aiomatic_agent') return;

    $url = admin_url('admin.php?page=aiomatic_agents_panel#tab-6');

    echo '<div class="misc-pub-section">';
    echo '<a href="' . esc_url($url) . '">← Back to Agents</a>';
    echo '</div>';

});
add_filter('views_edit-aiomatic_agent', function ($views) {

    foreach ($views as $key => $link) {

        $views[$key] = preg_replace_callback(
            '/href="([^"]+)"/',
            function ($matches) {

                $url = $matches[1];

                parse_str(parse_url($url, PHP_URL_QUERY), $query);

                $new_url = admin_url('admin.php?page=aiomatic_agents_panel#tab-6');

                if (!empty($query['post_status'])) {
                    $new_url = add_query_arg('post_status', $query['post_status'], $new_url);
                }

                return 'href="' . esc_url($new_url) . '"';
            },
            $link
        );
    }

    return $views;

});
add_filter('months_dropdown_results', function ($months, $post_type) {

    if ($post_type === 'aiomatic_agent') {
        return []; 
    }

    return $months;

}, 10, 2);
add_action('before_delete_post', function ($post_id) {

    if (get_post_type($post_id) !== 'aiomatic_agent') {
        return;
    }

    $thumbnail_id = get_post_thumbnail_id($post_id);
    if ($thumbnail_id) {
        wp_delete_attachment($thumbnail_id, true);
    }

    $attachments = get_children([
        'post_parent' => $post_id,
        'post_type'   => 'attachment',
        'numberposts' => -1
    ]);

    if (!empty($attachments)) {
        foreach ($attachments as $attachment) {
            wp_delete_attachment($attachment->ID, true);
        }
    }

});
add_filter('post_row_actions', function($actions, $post){

    if ($post->post_type !== 'aiomatic_agent') {
        return $actions;
    }
    unset($actions['inline hide-if-no-js']);
    $id = $post->ID;
    if (isset($actions['edit'])) {
        $actions['edit'] = str_replace(
            '<a',
            '<a class="aiomatic-action aiomatic-action-edit"',
            $actions['edit']
        );
    }

    if (isset($actions['trash'])) {
        $actions['trash'] = str_replace(
            '<a',
            '<a class="aiomatic-action aiomatic-action-danger"',
            $actions['trash']
        );
    }
    if (isset($actions['untrash'])) {
        $actions['untrash'] = str_replace(
            '<a',
            '<a class="aiomatic-action aiomatic-action-success"',
            $actions['untrash']
        );

        $actions['untrash'] = preg_replace(
            '/>(.*?)</',
            '><span class="dashicons dashicons-undo"></span> $1<',
            $actions['untrash']
        );
    }

    if (isset($actions['delete'])) {
        $actions['delete'] = str_replace(
            '<a',
            '<a class="aiomatic-action aiomatic-action-danger"',
            $actions['delete']
        );

        $actions['delete'] = preg_replace(
            '/>(.*?)</',
            '><span class="dashicons dashicons-trash"></span> $1<',
            $actions['delete']
        );
    }

    $status = get_post_meta($id, '_agent_status', true);
    if ($post->post_status === 'publish') {
        if ($status === 'running') {
            $stop = wp_nonce_url(
                admin_url("admin-post.php?action=aiomatic_stop_task&agent_id=$id"),
                'aiomatic_stop_task'
            );
            $actions['stop_task'] = '<a href="' . esc_url($stop) . '" 
        class="aiomatic-action aiomatic-action-danger">
        <span class="dashicons dashicons-controls-pause"></span>
        ' . esc_html__('Stop', 'aiomatic-automatic-ai-content-writer') . '</a>';
        } else {
            if($status == 'scheduled')
            {
                $cancel = wp_nonce_url(
                    admin_url("admin-post.php?action=aiomatic_cancel_schedule&agent_id=$id"),
                    'aiomatic_cancel_schedule'
                );
                $actions['cancel_schedule'] = '<a href="' . esc_url($cancel) . '" 
            class="aiomatic-action aiomatic-action-danger">
            <span class="dashicons dashicons-controls-pause"></span>
            ' . esc_html__('Cancel Schedule', 'aiomatic-automatic-ai-content-writer') . '</a>';
            }
            else
            {
                $actions['start_task'] = '<a href="javascript:void(0)" 
            class="aiomatic-action aiomatic-action-success start-agent-task" 
            data-id="' . esc_attr($id) . '">
            <span class="dashicons dashicons-controls-play"></span>
            ' . esc_html__('Start', 'aiomatic-automatic-ai-content-writer') . '</a>';
            }
        }
    }

    $actions['view_logs'] = '<a href="javascript:void(0)" 
    class="aiomatic-action aiomatic-action-logs view-agent-logs" 
    data-id="' . esc_attr($id) . '">
    <span class="dashicons dashicons-list-view"></span>
    ' . esc_html__('Logs', 'aiomatic-automatic-ai-content-writer') . '</a>';

    $actions['clear_long'] = '<a href="javascript:void(0)" 
    class="aiomatic-action aiomatic-action-warning clear-agent-long-memory" 
    data-id="' . esc_attr($id) . '">
    <span class="dashicons dashicons-trash"></span>
    ' . esc_html__('Clear', 'aiomatic-automatic-ai-content-writer') . '</a>';

    if (isset($actions['edit'])) {
        $actions['edit'] = preg_replace(
            '/>(.*?)</',
            '><span class="dashicons dashicons-edit"></span> $1<',
            $actions['edit']
        );
    }

    if (isset($actions['trash'])) {
        $actions['trash'] = preg_replace(
            '/>(.*?)</',
            '><span class="dashicons dashicons-trash"></span> $1<',
            $actions['trash']
        );
    }
    return $actions;

}, 10, 2);
add_filter('bulk_actions-edit-aiomatic_agent', function ($actions) {
    unset($actions['edit']);
    $actions['stop_agents']  = esc_html__('Stop Agents & Clear Schedules', 'aiomatic-automatic-ai-content-writer');
    $actions['clear_memory'] = esc_html__('Clear Long Term Memory', 'aiomatic-automatic-ai-content-writer');
    return $actions;
});

add_action('admin_init', function () {

    if (!isset($_REQUEST['page']) || $_REQUEST['page'] !== 'aiomatic_agents_panel') {
        return;
    }

    if (!current_user_can('manage_options')) {
        return;
    }

    $action  = isset($_REQUEST['action']) ? sanitize_text_field($_REQUEST['action']) : '';
    $action2 = isset($_REQUEST['action2']) ? sanitize_text_field($_REQUEST['action2']) : '';

    $doaction = '';

    if ($action && $action !== '-1') {
        $doaction = $action;
    } elseif ($action2 && $action2 !== '-1') {
        $doaction = $action2;
    }

    if (isset($_REQUEST['delete_all'])) {
        $doaction = 'delete_all';
    }

    if (!in_array($doaction, ['trash', 'delete', 'untrash', 'delete_all', 'stop_agents', 'clear_memory'], true)) {
        return;
    }

    $post_ids = isset($_REQUEST['post']) ? array_map('intval', (array) $_REQUEST['post']) : [];

    if ($doaction === 'delete_all') {

        $count = 0;
        $paged = 1;
        $per_page = 100;

        do {

            $trashed_posts = get_posts([
                'post_type'      => 'aiomatic_agent',
                'post_status'    => 'trash',
                'posts_per_page' => $per_page,
                'paged'          => $paged,
                'fields'         => 'ids',
                'no_found_rows'  => true,
            ]);

            if (empty($trashed_posts)) {
                break;
            }

            foreach ($trashed_posts as $post_id) {
                wp_delete_post($post_id, true);
                $count++;
            }

            $paged++;

            if ($count % 500 === 0) {
                wp_cache_flush();
            }

        } while (!empty($trashed_posts));
    } else {

        if (empty($post_ids)) {
            return;
        }
        $count = 0;
        foreach ($post_ids as $post_id) {

            if (get_post_type($post_id) !== 'aiomatic_agent') {
                continue;
            }

            switch ($doaction) {
                case 'trash':
                    wp_trash_post($post_id);
                    $count++;
                    break;

                case 'delete':
                    wp_delete_post($post_id, true);
                    $count++;
                    break;

                case 'untrash':
                    wp_untrash_post($post_id);
                    $count++;
                    break;
                case 'stop_agents':
                    $agent = new Aiomatic_Agent($post_id);
                    $agent->stop_task();
                    $count++;
                    break;
                case 'clear_memory':
                    $res = aiomatic_clear_agent_long_memory_internal($post_id);
                    if (!empty($res['success'])) {
                        $count++;
                    }

                    break;
            }
        }
    }

    $redirect = admin_url('admin.php?page=aiomatic_agents_panel#tab-6');

    if (!empty($_REQUEST['s'])) {
        $redirect = add_query_arg('s', sanitize_text_field($_REQUEST['s']), $redirect);
    }

    if (!empty($_REQUEST['post_status']) && $doaction !== 'delete_all') {
        $redirect = add_query_arg('post_status', sanitize_text_field($_REQUEST['post_status']), $redirect);
    }

    $redirect = add_query_arg([
        'bulk_action' => $doaction,
        'count'       => $count,
    ], $redirect);

    wp_safe_redirect($redirect);
    exit;
});
add_action('admin_notices', function () {

    $screen = get_current_screen();

    if (!$screen || $screen->post_type !== 'aiomatic_agent') {
        return;
    }

    if (!isset($_GET['bulk_action'])) return;

    $count = isset($_GET['count']) ? intval($_GET['count']) : 0;

    if ($_GET['bulk_action'] === 'untrash') {
        printf(
    esc_html(_n('%d agent restored.', '%d agents restored.', $count, 'aiomatic-automatic-ai-content-writer')),
    $count
);
    }

    if ($_GET['bulk_action'] === 'delete') {
        printf(
    esc_html(_n('%d agent permanently deleted.', '%d agents permanently deleted.', $count, 'aiomatic-automatic-ai-content-writer')),
    $count
);
    }

    if ($_GET['bulk_action'] === 'delete_all') {
        printf(
    esc_html(_n(
        'Trash emptied (%d agent).',
        'Trash emptied (%d agents).',
        $count,
        'aiomatic-automatic-ai-content-writer'
    )),
    $count
);
    }

});