<?php
/**
 * Local CLI runner for Telegram/admin autonomy work.
 *
 * @package Niwa_AI
 */

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

define( 'NIWA_AI_CLI_RUNNER', true );

$reason    = 'cli';
$runner_id = '';
foreach ( array_slice( $argv, 1 ) as $arg ) {
    if ( 0 === strpos( $arg, '--reason=' ) ) {
        $reason = substr( $arg, 9 );
    } elseif ( 0 === strpos( $arg, '--runner-id=' ) ) {
        $runner_id = substr( $arg, 12 );
    }
}

$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_cli_runner' ) ) {
    fwrite( STDERR, "Niwa AI plugin instance unavailable\n" );
    exit( 1 );
}

$niwa_cli_lock_handle = null;
$lock_dir = defined( 'WP_CONTENT_DIR' ) ? trailingslashit( WP_CONTENT_DIR ) . 'uploads/niwa-ai/locks' : sys_get_temp_dir();
if ( function_exists( 'wp_mkdir_p' ) ) {
    wp_mkdir_p( $lock_dir );
}
$lock_path = trailingslashit( $lock_dir ) . 'telegram-runner.lock';
$niwa_cli_lock_handle = @fopen( $lock_path, 'c' );
if ( is_resource( $niwa_cli_lock_handle ) && ! @flock( $niwa_cli_lock_handle, LOCK_EX | LOCK_NB ) ) {
    exit( 0 );
}
if ( is_resource( $niwa_cli_lock_handle ) ) {
    register_shutdown_function(
        static function () use ( &$niwa_cli_lock_handle ) {
            if ( is_resource( $niwa_cli_lock_handle ) ) {
                @flock( $niwa_cli_lock_handle, LOCK_UN );
                @fclose( $niwa_cli_lock_handle );
            }
        }
    );
}

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

exit( 0 );
