<?php
/**
 * REST contract for the dashboard Activity island.
 *
 * Exposes a single admin-capability endpoint that returns the live activity
 * metrics (actions / tokens / estimated cost for a period) plus the ecosystem
 * agent counts shown on the dashboard, so the React Activity card can refresh
 * without a full page reload.
 *
 * @package    Agent_Builder
 * @subpackage REST
 * @author     Agent Builder Team <support@agentic-plugin.com>
 * @license    GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link       https://agentic-plugin.com
 * @since      2.12.0
 *
 * php version 8.1
 */

namespace Agentic;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Dashboard Activity REST controller.
 */
class Dashboard_REST {

	/**
	 * REST namespace.
	 *
	 * @var string
	 */
	const NS = 'agentic/v1';

	/**
	 * Boot the controller.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'rest_api_init', array( __CLASS__, 'register_routes' ) );
	}

	/**
	 * Register routes.
	 *
	 * @return void
	 */
	public static function register_routes(): void {
		register_rest_route(
			self::NS,
			'/dashboard-stats',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( __CLASS__, 'get_stats' ),
				'permission_callback' => array( __CLASS__, 'can_view' ),
				'args'                => array(
					'period' => array(
						'type'              => 'string',
						'default'           => 'week',
						'sanitize_callback' => 'sanitize_key',
						'validate_callback' => static function ( $value ) {
							return in_array( $value, array( 'day', 'week', 'month' ), true );
						},
					),
				),
			)
		);
	}

	/**
	 * Capability gate — mirrors the dashboard page capability.
	 *
	 * @return bool
	 */
	public static function can_view(): bool {
		return current_user_can( 'manage_options' );
	}

	/**
	 * GET /dashboard-stats — live activity metrics + ecosystem agent counts.
	 *
	 * @param \WP_REST_Request $request Request.
	 * @return \WP_REST_Response
	 */
	public static function get_stats( \WP_REST_Request $request ): \WP_REST_Response {
		$period = (string) $request->get_param( 'period' );
		if ( ! in_array( $period, array( 'day', 'week', 'month' ), true ) ) {
			$period = 'week';
		}

		$stats = ( new Audit_Log() )->get_stats( $period );

		return new \WP_REST_Response(
			array(
				'period'   => $period,
				'activity' => array(
					'actions' => (int) ( $stats['total_actions'] ?? 0 ),
					'tokens'  => (int) ( $stats['total_tokens'] ?? 0 ),
					'cost'    => round( (float) ( $stats['total_cost'] ?? 0 ), 4 ),
				),
				'agents'   => self::agent_counts(),
			),
			200
		);
	}

	/**
	 * Compute the ecosystem agent counts shown on the dashboard.
	 *
	 * @return array<string,int>
	 */
	private static function agent_counts(): array {
		$active       = 0;
		$uploaded     = 0;
		$user_created = 0;

		if ( class_exists( '\Agentic_Agent_Registry' ) ) {
			$registry = \Agentic_Agent_Registry::get_instance();
			$all      = $registry->get_installed_agents();

			$active_slugs = $registry->get_active_agents();
			if ( is_array( $active_slugs ) ) {
				$active_slugs = array_unique( array_filter( array_map( 'sanitize_key', $active_slugs ) ) );
				foreach ( $active_slugs as $slug ) {
					if ( isset( $all[ $slug ] ) ) {
						++$active;
					}
				}
			}

			foreach ( $all as $info ) {
				if ( empty( $info['bundled'] ) && ! empty( $info['directory'] ) ) {
					if ( file_exists( $info['directory'] . '/.uploaded' ) ) {
						++$uploaded;
					} else {
						++$user_created;
					}
				}
			}
		}

		// Reuse the dashboard's cached community count — never triggers a remote
		// call here; it is populated by the dashboard page render.
		$community = (int) get_transient( 'agentic_dashboard_marketplace_agent_count' );

		return array(
			'active'       => $active,
			'uploaded'     => $uploaded,
			'user_created' => $user_created,
			'community'    => $community,
		);
	}
}
