<?php
/**
 * Handles slash/runtime commands before normal agent execution.
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Runtime_Command_Handler {

    private $chat_agent;
    private $control_plane;
    private $conversation_store;
    private $callbacks;

    public function __construct( $chat_agent = null, $control_plane = null, $conversation_store = null, $callbacks = array() ) {
        $this->chat_agent         = $chat_agent;
        $this->control_plane      = $control_plane;
        $this->conversation_store = $conversation_store;
        $this->callbacks          = is_array( $callbacks ) ? $callbacks : array();
    }

    public function handle( $text, $context, $normalized_command, $callback_command ) {
        if ( in_array( $callback_command, array( 'rollback', 'help' ), true ) ) {
            return null;
        }

        $context          = is_array( $context ) ? $context : array();
        $raw              = trim( (string) $text );
        $trimmed          = ltrim( $raw, '/' );
        $parts            = preg_split( '/\s+/', $trimmed, 2 );
        $command          = sanitize_key( isset( $parts[0] ) ? (string) $parts[0] : '' );
        $argument         = isset( $parts[1] ) ? trim( (string) $parts[1] ) : '';
        $session_id       = isset( $context['session_id'] ) ? (string) $context['session_id'] : '';
        $is_slash_command = 0 === strpos( $raw, '/' );

        if ( '' === $command ) {
            return null;
        }

        if ( ! in_array( $command, array( 'status', 'rollback', 'help', 'start', 'stop', 'new', 'reset', 'restart', 'compact', 'subagents', 'sessions', 'heartbeat' ), true ) ) {
            return null;
        }

        if ( ! $is_slash_command ) {
            if ( ! in_array( $command, array( 'rollback', 'help', 'start' ), true ) ) {
                return null;
            }
            if ( $normalized_command !== $command ) {
                return null;
            }
        }

        switch ( $command ) {
            case 'status':
                return $this->reply( (string) $this->call( 'build_status_message', array( $context ), '' ) );
            case 'rollback':
                return array(
                    'reply'             => (string) $this->call( 'rollback_last_successful_run', array(), '' ),
                    'reply_markup'      => $this->call( 'build_remove_keyboard', array(), null ),
                    'remember_exchange' => false,
                );
            case 'help':
                return $this->reply( (string) $this->call( 'build_help_message', array(), '' ) );
            case 'start':
                return $this->handle_start( $context );
            case 'stop':
                return $this->reply( (string) $this->call(
                    'stop_runtime_for_session',
                    array(
                        $session_id,
                        isset( $context['chat_id'] ) ? (string) $context['chat_id'] : '',
                        isset( $context['message_id'] ) ? intval( $context['message_id'] ) : 0,
                        'command',
                    ),
                    ''
                ) );
            case 'new':
            case 'reset':
            case 'restart':
                return $this->handle_reset( $session_id, $context );
            case 'compact':
                return $this->handle_compact( $session_id, $argument );
            case 'subagents':
                return $this->handle_subagents( $session_id, $argument );
            case 'sessions':
                return $this->handle_sessions( $session_id, $argument, $context );
            case 'heartbeat':
                return $this->handle_heartbeat();
        }

        return null;
    }

    private function handle_start( $context ) {
        if ( 'stock_manager' === ( isset( $context['user_role'] ) ? (string) $context['user_role'] : 'admin' ) ) {
            return $this->reply( (string) $this->call( 'build_stock_manager_help_message', array(), '' ) );
        }

        $reply = $this->chat_agent && method_exists( $this->chat_agent, 'build_founder_start_message' )
            ? (string) $this->chat_agent->build_founder_start_message( $context )
            : (string) $this->call( 'build_help_message', array(), '' );

        return $this->reply( $reply );
    }

    private function handle_reset( $session_id, $context ) {
        $chat_id    = isset( $context['chat_id'] ) ? (string) $context['chat_id'] : '';
        $message_id = isset( $context['message_id'] ) ? intval( $context['message_id'] ) : 0;

        if ( $this->control_plane && method_exists( $this->control_plane, 'clear_legacy_session_locks' ) ) {
            $this->control_plane->clear_legacy_session_locks();
        }
        if ( '' !== $chat_id ) {
            $this->call( 'clear_turn_stream_state', array( $chat_id, $message_id ), null );
        }

        $reply = $this->chat_agent && method_exists( $this->chat_agent, 'reset_session_text' )
            ? (string) $this->chat_agent->reset_session_text( $session_id, true )
            : 'Session reset runtime nije dostupan.';
        if ( $this->conversation_store && method_exists( $this->conversation_store, 'clear' ) ) {
            $this->conversation_store->clear( $session_id );
        }

        return $this->reply( $reply );
    }

    private function handle_compact( $session_id, $argument ) {
        $reply = $this->chat_agent && method_exists( $this->chat_agent, 'compact_session_text' )
            ? (string) $this->chat_agent->compact_session_text( $session_id, $argument )
            : 'Session compaction runtime nije dostupan.';

        if ( $this->conversation_store && method_exists( $this->conversation_store, 'replace' ) ) {
            $history = $this->conversation_store->get( $session_id );
            $history = is_array( $history ) ? array_slice( $history, -6 ) : array();
            $this->conversation_store->replace( $session_id, $history );
        }

        return $this->reply( $reply );
    }

    private function handle_subagents( $session_id, $argument ) {
        $parts  = preg_split( '/\s+/', $argument, 3 );
        $action = sanitize_key( isset( $parts[0] ) ? (string) $parts[0] : '' );
        $job_id = isset( $parts[1] ) ? trim( (string) $parts[1] ) : '';
        $extra  = isset( $parts[2] ) ? trim( (string) $parts[2] ) : '';

        if ( '' === $action || 'list' === $action ) {
            $reply = $this->chat_agent && method_exists( $this->chat_agent, 'get_subagents_status_text' )
                ? (string) $this->chat_agent->get_subagents_status_text( $session_id )
                : 'Subagent runtime nije dostupan.';
        } else {
            $reply = $this->chat_agent && method_exists( $this->chat_agent, 'control_subagents_text' )
                ? (string) $this->chat_agent->control_subagents_text(
                    $session_id,
                    $action,
                    array(
                        'job_id'      => $job_id,
                        'instruction' => $extra,
                        'limit'       => 12,
                    )
                )
                : 'Subagent runtime nije dostupan.';
        }

        return $this->reply( $reply );
    }

    private function handle_sessions( $session_id, $argument, $context ) {
        $parts   = preg_split( '/\s+/', $argument, 3 );
        $action  = sanitize_key( isset( $parts[0] ) ? (string) $parts[0] : '' );
        $target  = isset( $parts[1] ) ? trim( (string) $parts[1] ) : '';
        $payload = isset( $parts[2] ) ? trim( (string) $parts[2] ) : '';

        if ( '' === $action || 'list' === $action ) {
            $reply = $this->chat_agent && method_exists( $this->chat_agent, 'get_sessions_list_text' )
                ? (string) $this->chat_agent->get_sessions_list_text( 'admin-telegram-', 10 )
                : 'Session runtime nije dostupan.';
        } elseif ( 'status' === $action ) {
            $reply = $this->chat_agent && method_exists( $this->chat_agent, 'get_session_status_text' )
                ? (string) $this->chat_agent->get_session_status_text( $target )
                : 'Session runtime nije dostupan.';
        } elseif ( 'history' === $action ) {
            $reply = $this->chat_agent && method_exists( $this->chat_agent, 'get_session_history_text' )
                ? (string) $this->chat_agent->get_session_history_text( $target, 14 )
                : 'Session runtime nije dostupan.';
        } elseif ( 'send' === $action ) {
            $reply = $this->chat_agent && method_exists( $this->chat_agent, 'send_to_session_text' )
                ? (string) $this->chat_agent->send_to_session_text( $session_id, $target, $payload, $context )
                : 'Session runtime nije dostupan.';
        } else {
            $reply = 'Nepodrzana /sessions akcija. Koristi /sessions, /sessions status <session_id>, /sessions history <session_id> ili /sessions send <session_id> <task>.';
        }

        return $this->reply( $reply );
    }

    private function handle_heartbeat() {
        if ( $this->chat_agent && method_exists( $this->chat_agent, 'run_workspace_heartbeat_now' ) ) {
            $result = $this->chat_agent->run_workspace_heartbeat_now();
            $reply  = ! empty( $result['sent'] )
                ? 'Heartbeat je poslat founder chatu.'
                : 'Heartbeat check zavrsen: ' . ( isset( $result['reason'] ) ? (string) $result['reason'] : 'ok' );
        } else {
            $reply = 'Heartbeat runtime nije dostupan.';
        }

        return $this->reply( $reply );
    }

    private function reply( $reply ) {
        return array(
            'reply'             => (string) $reply,
            'remember_exchange' => false,
        );
    }

    private function call( $name, $args = array(), $default = null ) {
        return Niwa_AI_Admin_Autonomy_Callbacks::call( $this->callbacks, $name, $args, $default );
    }
}
