<?php

defined('ABSPATH') or die();

if (defined('WP_CLI') && WP_CLI) {

    WP_CLI::add_command('aimogen-agent', function ($args, $assoc_args) {

        if (empty($args[0])) {
            WP_CLI::error('Missing agent_id');
        }

        $agent_id = (int) $args[0];

        try {
            $agent = new Aiomatic_Agent($agent_id);
        } catch (Throwable $e) {
            WP_CLI::error($e->getMessage());
        }

        $task      = $assoc_args['task'] ?? null;
        $verbose   = isset($assoc_args['verbose']);

        WP_CLI::log("Starting agent #{$agent_id}");

        if ($task) {
            WP_CLI::log("Task: {$task}");
        }

        delete_post_meta($agent_id, '_agent_memory');
        delete_post_meta($agent_id, '_current_task');
        update_post_meta($agent_id, '_agent_status', 'running');

        $start = microtime(true);

        try {

            $result = $agent->run($task);

            $duration = round(microtime(true) - $start, 2);

            WP_CLI::success("Finished in {$duration}s");

            if ($verbose) {
                WP_CLI::log("Result:");
                WP_CLI::log(is_string($result) ? $result : wp_json_encode($result));
            }

        } catch (Throwable $e) {
            WP_CLI::error("Agent crashed: " . $e->getMessage());
        }

    });
}
?>