<?php
/**
 * ClearPost MCP server registration.
 *
 * Boots the bundled WordPress/mcp-adapter (lib/mcp/) and registers a custom
 * MCP server at /wp-json/clearpost/mcp exposing the ClearPost abilities as
 * first-class named tools.
 *
 * This file must stay parseable on PHP 7.2 (plugin minimum). The adapter
 * itself requires PHP 7.4+, so its autoloader is only required behind a
 * runtime version guard.
 *
 * @package simple-ai-auto-post
 */

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

/**
 * Load the bundled WordPress Abilities API if it isn't already provided.
 *
 * The Abilities API ships in WP core starting 6.9. Until then, our bundled
 * copy (lib/abilities-api/, vendored from wordpress/abilities-api ^0.5.0)
 * supplies wp_register_ability() so the MCP server can boot on the WP
 * versions our customers run today.
 */
function saiap_load_bundled_abilities_api() {
	if ( function_exists( 'wp_register_ability' ) ) {
		return; // Provided by WP core or another plugin — don't double-load.
	}
	$autoload = plugin_dir_path( __FILE__ ) . '../lib/abilities-api/autoload.php';
	if ( file_exists( $autoload ) ) {
		require_once $autoload;
	}
}
// Plugin load order — must run before saiap_mcp_server_boot so the
// function_exists check inside it passes.
add_action( 'plugins_loaded', 'saiap_load_bundled_abilities_api', 1 );

/**
 * Whether the MCP server can run in this environment.
 *
 * @return bool
 */
function saiap_mcp_server_supported() {
	// Adapter requires PHP 7.4+.
	if ( version_compare( PHP_VERSION, '7.4', '<' ) ) {
		return false;
	}
	// Bundled lib/abilities-api/ loads at plugins_loaded:1, so by the time
	// saiap_mcp_server_boot() (plugins_loaded:10 default) runs this should
	// always be true. The check remains as a safety net in case the bundle
	// is missing on disk (e.g. a malformed release zip).
	if ( ! function_exists( 'wp_register_ability' ) ) {
		return false;
	}
	return true;
}

/**
 * Load the bundled mcp-adapter and boot the adapter singleton.
 */
function saiap_mcp_server_boot() {
	if ( ! saiap_mcp_server_supported() ) {
		return;
	}

	try {
		// If another plugin already loaded the adapter, reuse it instead of
		// loading our bundled copy (avoids duplicate-class conflicts).
		if ( ! class_exists( 'WP\\MCP\\Core\\McpAdapter' ) ) {
			$autoload = plugin_dir_path( __FILE__ ) . '../lib/mcp/autoload.php';
			if ( ! file_exists( $autoload ) ) {
				return;
			}
			require_once $autoload;
		}

		if ( ! class_exists( 'WP\\MCP\\Core\\McpAdapter' ) ) {
			return;
		}

		call_user_func( array( 'WP\\MCP\\Core\\McpAdapter', 'instance' ) );

		add_action( 'mcp_adapter_init', 'saiap_mcp_register_server' );
	} catch ( \Throwable $e ) {
		error_log( 'ClearPost MCP boot failed: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
	}
}
add_action( 'plugins_loaded', 'saiap_mcp_server_boot' );

/**
 * Register the ClearPost MCP server with the adapter.
 *
 * @param object $adapter WP\MCP\Core\McpAdapter instance.
 */
function saiap_mcp_register_server( $adapter ) {
	$result = $adapter->create_server(
		'clearpost',
		'clearpost',
		'mcp',
		'ClearPost MCP',
		'ClearPost SEO content tools: list, read, update, and generate posts, bulk find-replace, content calendar, keyword tracking, site strategy context, and Google Search Console performance.',
		defined( 'SAIAP_VERSION' ) ? SAIAP_VERSION : '1.0.0',
		array( 'WP\\MCP\\Transport\\HttpTransport' ),
		'WP\\MCP\\Infrastructure\\ErrorHandling\\ErrorLogMcpErrorHandler',
		null,
		array(
			'clearpost/list-posts',
			'clearpost/get-post',
			'clearpost/update-post',
			'clearpost/bulk-find-replace',
			'clearpost/get-post-performance',
			'clearpost/get-content-calendar',
			'clearpost/get-keywords',
			'clearpost/get-site-metrics',
			'clearpost/get-strategy-context',
			'clearpost/generate-post',
			'clearpost/add-to-calendar',
			'clearpost/set-keyword-tracking',
			'clearpost/get-seo-meta',
			'clearpost/update-seo-meta',
		),
		array(),
		array(),
		'saiap_mcp_transport_permission'
	);

	if ( is_wp_error( $result ) ) {
		error_log( 'ClearPost MCP server registration failed: ' . $result->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
	}
}

/**
 * Transport-level permission gate for the ClearPost MCP endpoint.
 *
 * Accepts either a logged-in user with edit_posts, or a Bearer token
 * matching the site's license key (saiap_license_key option).
 *
 * @return bool
 */
function saiap_mcp_transport_permission() {
	return current_user_can( 'edit_posts' ) || saiap_mcp_bearer_authenticated();
}

/**
 * Whether the MCP endpoint is live on this site (for the dashboard card).
 *
 * @return bool
 */
function saiap_mcp_server_active() {
	return saiap_mcp_server_supported() && class_exists( 'WP\\MCP\\Core\\McpAdapter' );
}

/**
 * Render the "AI Assistants (MCP)" dashboard card.
 */
function saiap_render_mcp_card() {
	if ( ! current_user_can( 'edit_posts' ) ) {
		return;
	}

	$active = saiap_mcp_server_active();
	?>
	<div class="saiap-mcp-card" style="background: #fff; border: 1px solid #e2e4e7; border-radius: 8px; padding: 20px 24px; margin-top: 24px;">
		<h3 style="margin: 0 0 4px;">
			<?php esc_html_e( 'AI Assistants (MCP)', 'clearpost-simple-ai-auto-post' ); ?>
			<?php if ( $active ) : ?>
				<span style="display: inline-block; margin-left: 8px; padding: 2px 10px; font-size: 12px; font-weight: 600; color: #00663d; background: #e5f5ec; border-radius: 10px; vertical-align: middle;"><?php esc_html_e( 'Enabled', 'clearpost-simple-ai-auto-post' ); ?></span>
			<?php endif; ?>
		</h3>
		<?php if ( ! $active ) : ?>
			<p style="margin: 8px 0 0; color: #646970;">
				<?php esc_html_e( 'Connect Claude, Cursor, or any MCP client to manage your ClearPost content. Requires PHP 7.4 or newer.', 'clearpost-simple-ai-auto-post' ); ?>
			</p>
		<?php else : ?>
			<?php
			$endpoint    = rest_url( 'clearpost/mcp' );
			$license_key = (string) get_option( 'saiap_license_key', '' );
			?>
			<p style="margin: 8px 0 12px; color: #646970;">
				<?php esc_html_e( 'Connect Claude, Cursor, or any MCP client to list, update, and measure your ClearPost posts. Ask your assistant "how is my latest post doing in Google?" and get real Search Console numbers.', 'clearpost-simple-ai-auto-post' ); ?>
			</p>
			<p style="margin: 0 0 12px; color: #1d2327;">
				<?php esc_html_e( 'Add the server to your AI client using the endpoint and license key below:', 'clearpost-simple-ai-auto-post' ); ?>
			</p>
			<p style="margin: 0 0 4px; font-weight: 600;"><?php esc_html_e( 'Endpoint', 'clearpost-simple-ai-auto-post' ); ?></p>
			<code style="display: block; padding: 8px 12px; background: #f6f7f7; border-radius: 4px; margin-bottom: 12px; user-select: all;"><?php echo esc_html( $endpoint ); ?></code>
			<p style="margin: 0 0 4px; font-weight: 600;"><?php esc_html_e( 'Claude Code', 'clearpost-simple-ai-auto-post' ); ?></p>
			<code style="display: block; padding: 8px 12px; background: #f6f7f7; border-radius: 4px; margin-bottom: 12px; user-select: all; white-space: pre-wrap; word-break: break-all;">claude mcp add --transport http clearpost <?php echo esc_html( $endpoint ); ?> --header "Authorization: Bearer <?php echo esc_html( $license_key ); ?>"</code>
			<p style="margin: 0 0 4px; font-weight: 600;"><?php esc_html_e( 'Claude Desktop / Cursor (JSON config)', 'clearpost-simple-ai-auto-post' ); ?></p>
			<code style="display: block; padding: 8px 12px; background: #f6f7f7; border-radius: 4px; margin-bottom: 12px; user-select: all; white-space: pre-wrap; word-break: break-all;">{
  "mcpServers": {
    "clearpost": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "<?php echo esc_html( $endpoint ); ?>", "--header", "Authorization: Bearer <?php echo esc_html( $license_key ); ?>"]
    }
  }
}</code>
			<p style="margin: 0 0 4px; font-weight: 600;"><?php esc_html_e( 'ChatGPT (Pro / Plus with Developer Mode)', 'clearpost-simple-ai-auto-post' ); ?></p>
			<div style="display: block; padding: 12px 16px; background: #f6f7f7; border-radius: 4px; margin-bottom: 4px; color: #1d2327; font-size: 13px; line-height: 1.6;">
				<ol style="margin: 0; padding-left: 20px;">
					<li><?php esc_html_e( 'In ChatGPT, open Settings → Connectors → Create.', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><?php
						printf(
							/* translators: %s: URL endpoint */
							esc_html__( 'Paste the endpoint URL: %s', 'clearpost-simple-ai-auto-post' ),
							'<code style="background:#fff;padding:1px 4px;border-radius:3px;">' . esc_html( $endpoint ) . '</code>'
						);
					?></li>
					<li><?php esc_html_e( 'Choose Bearer authentication and paste the license key shown above.', 'clearpost-simple-ai-auto-post' ); ?></li>
				</ol>
				<p style="margin: 8px 0 0; color: #646970; font-size: 12px;">
					<?php esc_html_e( 'Developer Mode is in beta and only available on ChatGPT Pro and Plus. The free tier and Enterprise standard tier do not yet support arbitrary custom MCP tools — only the built-in search/fetch tools. If your connector setup rejects the Bearer header, OpenAI is still expanding auth support; check their connector docs for the current state.', 'clearpost-simple-ai-auto-post' ); ?>
				</p>
			</div>
			<details style="margin: 16px 0 0;">
				<summary style="cursor: pointer; font-weight: 600; color: #1d2327;"><?php esc_html_e( 'Available tools (14)', 'clearpost-simple-ai-auto-post' ); ?></summary>
				<ul style="margin: 8px 0 0 20px; color: #1d2327; font-size: 13px; line-height: 1.8;">
					<li><strong>list-posts</strong> &mdash; <?php esc_html_e( 'Browse published, draft, or all posts with metadata', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>get-post</strong> &mdash; <?php esc_html_e( 'Read full content and ClearPost metadata for a post', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>update-post</strong> &mdash; <?php esc_html_e( 'Edit title, content, or excerpt of any post', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>get-seo-meta</strong> &mdash; <?php esc_html_e( 'Read SEO fields (meta description, focus keyword, excerpt, primary category) — detects Yoast, Rank Math, or AIOSEO automatically', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>update-seo-meta</strong> &mdash; <?php esc_html_e( 'Update one or more SEO fields on a post; writes to whichever SEO plugin is active', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>generate-post</strong> &mdash; <?php esc_html_e( 'Create a new post with the ClearPost AI pipeline', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>bulk-find-replace</strong> &mdash; <?php esc_html_e( 'Search and replace text across all posts', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>get-post-performance</strong> &mdash; <?php esc_html_e( 'Clicks, impressions, CTR, and ranking queries from Search Console', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>get-site-metrics</strong> &mdash; <?php esc_html_e( 'Site-wide Search Console trends over time', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>get-keywords</strong> &mdash; <?php esc_html_e( 'View researched keywords with volume, difficulty, and tracking status', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>set-keyword-tracking</strong> &mdash; <?php esc_html_e( 'Add or toggle rank tracking for a keyword', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>get-content-calendar</strong> &mdash; <?php esc_html_e( 'See planned posts, scheduled dates, and statuses', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>add-to-calendar</strong> &mdash; <?php esc_html_e( 'Schedule a new post for a future date', 'clearpost-simple-ai-auto-post' ); ?></li>
					<li><strong>get-strategy-context</strong> &mdash; <?php esc_html_e( 'Read the AI-generated site strategy and business summary', 'clearpost-simple-ai-auto-post' ); ?></li>
				</ul>
			</details>
			<p style="margin: 12px 0 0; color: #646970; font-size: 12px;">
				<?php esc_html_e( 'Your license key is shown above so you can paste it into your AI client. Tools respect your WordPress permissions; Search Console data additionally requires an administrator account.', 'clearpost-simple-ai-auto-post' ); ?>
			</p>
		<?php endif; ?>
	</div>
	<?php
}
