<?php
/**
 * CLI entrypoint for Niwa IMAP IDLE listener.
 * Usage: php wp-content/plugins/niwa-ai-1/includes/admin-autonomy/niwa-imap-idle-listener-cli.php --once
 */

define( 'NIWA_IMAP_IDLE_LISTENER_CLI', true );

$root = dirname( __DIR__, 5 );
require_once $root . '/wp-load.php';

if ( ! class_exists( 'Niwa_AI_Admin_Autonomy_IMAP_IDLE_Listener' ) ) {
    fwrite( STDERR, "Niwa IMAP IDLE listener class is unavailable.\n" );
    exit( 1 );
}

$niwa_cli_lock_handle = null;
$private_root = class_exists( 'Niwa_AI_Admin_Autonomy_Workspace' ) ? Niwa_AI_Admin_Autonomy_Workspace::get_private_data_root() : '';
$lock_dir = '' !== $private_root ? trailingslashit( $private_root ) . 'locks' : sys_get_temp_dir();
$old_umask = umask( 0077 );
try {
    if ( function_exists( 'wp_mkdir_p' ) ) {
        wp_mkdir_p( $lock_dir );
    }
} finally {
    umask( $old_umask );
}
if ( '' !== $private_root ) {
    @chmod( $lock_dir, 0700 );
}
$lock_path = trailingslashit( $lock_dir ) . 'imap-idle-listener.lock';
$old_umask = umask( 0077 );
try {
    $niwa_cli_lock_handle = @fopen( $lock_path, 'c' );
} finally {
    umask( $old_umask );
}
@chmod( $lock_path, 0600 );
if ( is_resource( $niwa_cli_lock_handle ) && ! @flock( $niwa_cli_lock_handle, LOCK_EX | LOCK_NB ) ) {
    echo wp_json_encode( array( 'success' => true, 'started' => false, 'reason' => 'imap_listener_already_locked' ), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . PHP_EOL;
    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 );
            }
        }
    );
}

$args = array(
    'once' => in_array( '--once', $argv, true ),
    'notify' => ! in_array( '--no-notify', $argv, true ),
    'supervised' => in_array( '--supervised', $argv, true ),
);
foreach ( $argv as $arg ) {
    if ( 0 === strpos( $arg, '--idle-seconds=' ) ) {
        $args['idle_seconds'] = (int) substr( $arg, 15 );
    }
    if ( 0 === strpos( $arg, '--max-runtime=' ) ) {
        $args['max_runtime_seconds'] = (int) substr( $arg, 14 );
    }
}

$listener = new Niwa_AI_Admin_Autonomy_IMAP_IDLE_Listener();
$result = $listener->run( $args );
echo wp_json_encode( $result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . PHP_EOL;
exit( ! empty( $result['success'] ) ? 0 : 1 );
