<?php
defined('ABSPATH') or die();

function aiomatic_clear_agent_long_memory_internal($agent_id) {

    if (!aiomatic_long_term_memory_available()) {
        return ['success' => false, 'message' => 'Long term memory not available'];
    }

    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);

    $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id'] ?? ''));
    $appids = array_filter($appids);

    if (empty($appids)) {
        return ['success' => false, 'message' => 'Missing API key'];
    }

    $token = $appids[array_rand($appids)];
    $token = apply_filters('aimogen_openai_api_key', $token);
    $token = apply_filters('aiomatic_openai_api_key', $token);

    try {
        $embedding = new Aiomatic_Embeddings($token);
        $namespace = 'agents_' . $agent_id;

        $result = $embedding->aiomatic_delete_namespace_embeddings($namespace);

        if (isset($result['status']) && $result['status'] === 'success') {
            return [
                'success' => true,
                'deleted' => $result['deleted'] ?? 0
            ];
        }

        return [
            'success' => false,
            'message' => $result['msg'] ?? 'Failed to clear memory'
        ];

    } catch (Throwable $e) {
        return [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
}

function aiomatic_add_agent_tools($query, $forced_functions = false)
{
    if (is_array($query)) {
        $functions = $query;
    } else {
        $functions = array();
    }
    if (!isset($functions['functions']) || !is_array($functions['functions'])) {
        $functions['functions'] = array();
    }
    if (empty($forced_functions) || !is_array($forced_functions)) {
        return $functions;
    }
    $normalized = array();
    foreach ($forced_functions as $tool) {
        if (isset($tool['type']) && $tool['type'] === 'function' && isset($tool['function'])) {
            if (is_array($tool['function'])) {
                $tool['function'] = aiomatic_array_to_object_recursive($tool['function']);
            }
            if (is_object($tool['function'])) {
                $normalized[] = array(
                    'type' => 'function',
                    'name' => isset($tool['function']->name) ? $tool['function']->name : '',
                    'function' => $tool['function']
                );
            }
            continue;
        }
        if (!isset($tool['name']) || !isset($tool['parameters']) || !is_array($tool['parameters'])) {
            continue;
        }
        $function_obj = new stdClass();
        $function_obj->name = $tool['name'];
        $function_obj->description = isset($tool['description']) ? $tool['description'] : '';
        $function_obj->parameters = array();
        $required = array();
        if (isset($tool['parameters']['required']) && is_array($tool['parameters']['required'])) {
            $required = $tool['parameters']['required'];
        }
        if (isset($tool['parameters']['properties']) && is_array($tool['parameters']['properties'])) {
            foreach ($tool['parameters']['properties'] as $param_name => $param_def) {
                $param_obj = new stdClass();
                $param_obj->name = $param_name;
                $param_obj->type = isset($param_def['type']) ? $param_def['type'] : 'string';
                $param_obj->description = isset($param_def['description']) ? $param_def['description'] : '';
                $param_obj->required = in_array($param_name, $required, true);
                if (isset($param_def['enum'])) {
                    $param_obj->enum = $param_def['enum'];
                }
                $function_obj->parameters[] = $param_obj;
            }
        }
        $normalized[] = array(
            'type' => 'function',
            'name' => $tool['name'],
            'function' => $function_obj
        );
    }
    $functions['functions'] = array_merge($functions['functions'], $normalized);
    if (!isset($functions['message'])) {
        $functions['message'] = '';
    }
    return $functions;
}
function aiomatic_import_default_agents($overwrite = false){

    $file = plugin_dir_path(__FILE__) . '../defaults/agent-defaults.json';
    global $wp_filesystem;

    if (!is_a($wp_filesystem, 'WP_Filesystem_Base')) {
        include_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem();
    }
    if (!$wp_filesystem->exists($file)) {
        return 0;
    }

    $json = $wp_filesystem->get_contents($file);
    if (!$json) {
        return 0;
    }

    $data = json_decode($json, true);

    if (!is_array($data)) {
        return 0;
    }

    $created = 0;

    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_agent_by_title($name);
        }

        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);
            }
        }
        $avatar = $agent['avatar'] ?? '';

        if (!empty($avatar) && (!has_post_thumbnail($post_id) || $overwrite)) {

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

            $attachment_id = 0;

            if (filter_var($avatar, FILTER_VALIDATE_URL))
            {
                $tmp = download_url($avatar);

                if (!is_wp_error($tmp)) {

                    $file = [
                        'name'     => basename(parse_url($avatar, PHP_URL_PATH)),
                        'tmp_name' => $tmp
                    ];

                    $attachment_id = media_handle_sideload($file, $post_id);

                    if (is_wp_error($attachment_id)) {
                        @unlink($tmp);
                    }
                }

            }
            else {

                $local_path = plugin_dir_path(__FILE__) . '../images/agents/' . ltrim($avatar, '/');

                if (file_exists($local_path)) {

                    $tmp = wp_tempnam($local_path);

                    if ($tmp && copy($local_path, $tmp)) {

                        $file = [
                            'name'     => basename($local_path),
                            'tmp_name' => $tmp
                        ];

                        $attachment_id = media_handle_sideload($file, $post_id);

                        if (is_wp_error($attachment_id)) {
                            @unlink($tmp);
                        }

                    }
                }
                
            }

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

    return $created;
}