<?php
/**
 * Shared slug → plugin-file resolver for the plugin-lifecycle abilities.
 *
 * Activate / Deactivate / Delete all need to map an LLM-supplied slug
 * (or `folder/file` identifier) to the actual `plugin_file` key
 * WordPress core uses internally. Centralise the matching rules so
 * the four abilities agree on what shapes they accept and how the
 * lookup falls back.
 *
 * Accepted input shapes:
 *   - bare folder slug:                 "contact-form-7"
 *   - WP REST plugin id (no extension): "contact-form-7/wp-contact-form-7"
 *   - WP REST plugin id (with .php):    "contact-form-7/wp-contact-form-7.php"
 *
 * @since 0.0.5
 * @package zip-ai
 */

namespace ZipAI\MCP\Classes\Abilities\Zipai\System;

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

class PluginResolver {

	/**
	 * Resolve a slug-shaped identifier to the actual `folder/file.php`
	 * key WP core uses for installed plugins. Returns null when no
	 * installed plugin matches.
	 *
	 * Callers MUST `require_once ABSPATH . 'wp-admin/includes/plugin.php'`
	 * before invoking — `get_plugins()` is a wp-admin function.
	 *
	 * @param string $slug Slug, `folder/file`, or `folder/file.php`.
	 * @return string|null `folder/file.php` key, or null if not installed.
	 */
	public static function resolve_plugin_file( $slug ) {
		$slug    = (string) $slug;
		$plugins = function_exists( 'get_plugins' ) ? get_plugins() : array();

		if ( ! is_array( $plugins ) || array() === $plugins ) {
			return null;
		}

		// Direct match: caller already provided the canonical key.
		if ( isset( $plugins[ $slug ] ) ) {
			return $slug;
		}

		// Caller provided `folder/file` without `.php` — try appending.
		if ( isset( $plugins[ $slug . '.php' ] ) ) {
			return $slug . '.php';
		}

		// Bare-slug match against the folder component of every key.
		$lower_slug = strtolower( $slug );
		foreach ( $plugins as $file => $_data ) {
			$parts  = explode( '/', $file, 2 );
			$folder = isset( $parts[0] ) ? $parts[0] : '';
			if ( '' !== $folder && strtolower( $folder ) === $lower_slug ) {
				return $file;
			}
		}

		return null;
	}
}
