<?php
/**
 * Dedicated local CLI runner for one subagent job.
 *
 * @package Niwa_AI
 */

if ( 'cli' !== PHP_SAPI ) {
    exit( 1 );
}

define( 'NIWA_AI_CLI_RUNNER', true );

$job_id = '';
foreach ( array_slice( $argv, 1 ) as $arg ) {
    if ( 0 === strpos( $arg, '--job-id=' ) ) {
        $job_id = substr( $arg, 9 );
    }
}
if ( '' === trim( $job_id ) ) {
    fwrite( STDERR, "job id missing\n" );
    exit( 1 );
}

$dir          = __DIR__;
$wp_load_path = '';
for ( $i = 0; $i < 8; $i++ ) {
    $candidate = $dir . '/wp-load.php';
    if ( is_readable( $candidate ) ) {
        $wp_load_path = $candidate;
        break;
    }
    $parent = dirname( $dir );
    if ( $parent === $dir ) {
        break;
    }
    $dir = $parent;
}
if ( '' === $wp_load_path ) {
    fwrite( STDERR, "wp-load.php not found\n" );
    exit( 1 );
}

$_SERVER['REQUEST_METHOD']  = 'GET';
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
$_SERVER['HTTP_HOST']       = isset( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : 'localhost';
$_SERVER['REQUEST_URI']     = '/';

require_once $wp_load_path;

$plugin = isset( $GLOBALS['niwa_ai_plugin_instance'] ) ? $GLOBALS['niwa_ai_plugin_instance'] : null;
if ( ! $plugin || ! method_exists( $plugin, 'run_admin_autonomy_subagent_worker' ) ) {
    fwrite( STDERR, "Niwa AI plugin instance unavailable\n" );
    exit( 1 );
}

$result = $plugin->run_admin_autonomy_subagent_worker( $job_id );
if ( empty( $result['success'] ) ) {
    fwrite( STDERR, wp_json_encode( $result ) . "\n" );
    exit( 1 );
}

exit( 0 );
