<?php
/**
 * Runtime stop/cancel orchestration.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Runtime_Stopper {
	private $chat_agent;
	private $control_plane;
	private $telegram;
	private $callbacks;

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

	public function stop_session( $session_id, $chat_id = '', $message_id = 0, $source = 'command' ) {
		$session_id = trim( (string) $session_id );
		$chat_id    = trim( (string) $chat_id );
		$message_id = intval( $message_id );
		$source     = sanitize_key( (string) $source );
		$actor      = array();
		$subagents  = array();

		if ( '' !== $session_id && $this->control_plane && method_exists( $this->control_plane, 'cancel_actor_session' ) ) {
			$actor = (array) $this->control_plane->cancel_actor_session( $session_id, 'Cancelled by founder /stop.' );
			if ( method_exists( $this->control_plane, 'force_release_session_lane' ) ) {
				$this->control_plane->force_release_session_lane( $session_id );
				$this->control_plane->force_release_session_lane( 'actor-run:' . $session_id );
			}
		}

		if ( '' !== $session_id && $this->chat_agent && method_exists( $this->chat_agent, 'cancel_subagents_for_session_text' ) ) {
			$subagents = (array) $this->chat_agent->cancel_subagents_for_session_text( $session_id, 'Cancelled by founder /stop.' );
		}

		$heartbeats = $this->stop_operative_heartbeats();
		$this->reset_runner_state();

		if ( '' !== $chat_id ) {
			$this->call( 'clear_turn_stream_state', array( $chat_id, $message_id ) );
			$this->call( 'end_typing_feedback', array( $chat_id ) );
		}

		$active_actor      = ! empty( $actor['active_cancelled'] ) ? intval( $actor['active_cancelled'] ) : 0;
		$pending_actor     = ! empty( $actor['pending_cancelled'] ) ? intval( $actor['pending_cancelled'] ) : 0;
		$queued_subagents  = ! empty( $subagents['queued_cancelled'] ) ? intval( $subagents['queued_cancelled'] ) : 0;
		$running_subagents = ! empty( $subagents['running_signaled'] ) ? intval( $subagents['running_signaled'] ) : 0;

		$this->call(
			'log_turn_debug',
			array(
				'runtime_stop_command',
				array(
					'source'             => $source,
					'session_id'         => $session_id,
					'active_actor'       => $active_actor,
					'pending_actor'      => $pending_actor,
					'queued_subagents'   => $queued_subagents,
					'running_subagents'  => $running_subagents,
					'heartbeats_stopped' => $heartbeats,
				),
			)
		);

		return 'Stopirano. Aktivni autonomy agent: ' . $active_actor
			. ', pending poruke: ' . $pending_actor
			. ', queued coding/subagent poslovi: ' . $queued_subagents
			. ', running coding/subagent poslovi signalizirani: ' . $running_subagents
			. ', operative heartbeat kanali ugaseni: ' . $heartbeats . '.';
	}

	private function reset_runner_state() {
		if ( ! $this->telegram || ! method_exists( $this->telegram, 'get_runner_state' ) || ! method_exists( $this->telegram, 'update_runner_state' ) ) {
			return;
		}

		$state                 = (array) $this->telegram->get_runner_state();
		$state['active_until'] = 0;
		$state['active_runner_id'] = '';
		$state['active_transport'] = '';
		$state['active_pid'] = 0;
		$state['wake_pending'] = 0;
		$state['wake_reason']  = '';
		$state['last_error']   = 'stopped_by_founder';
		$this->telegram->update_runner_state( $state );
	}

	private function stop_operative_heartbeats() {
		if ( ! $this->chat_agent || ! method_exists( $this->chat_agent, 'get_operative_heartbeat_config' ) || ! method_exists( $this->chat_agent, 'save_operative_heartbeat_config' ) ) {
			return 0;
		}

		$stopped = 0;
		foreach ( array( 'admin', 'stock_manager' ) as $role ) {
			$config = (array) $this->chat_agent->get_operative_heartbeat_config( $role );
			if ( empty( $config['enabled'] ) ) {
				continue;
			}

			$config['enabled'] = false;
			$this->chat_agent->save_operative_heartbeat_config( $config, $role );
			$stopped++;
		}

		if ( $stopped > 0 && method_exists( $this->chat_agent, 'sync_operative_heartbeat_scheduler_interval' ) ) {
			$this->chat_agent->sync_operative_heartbeat_scheduler_interval();
		}

		return $stopped;
	}

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