<?php
/**
 * AI crawler robots.txt preferences.
 *
 * @package MicropediaAISearchOptimizer
 */

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

/** Robots.txt manager. */
class Micropedia_AI_Robots {
	/** Init hooks. */
	public static function init() {
		add_filter( 'robots_txt', array( __CLASS__, 'filter_robots_txt' ), 20, 2 );
	}

	/**
	 * Filter robots.txt.
	 *
	 * @param string $output Robots output.
	 * @param bool   $public Whether site is public.
	 * @return string
	 */
	public static function filter_robots_txt( $output, $public ) {
		if ( ! $public || ! micropedia_ai_get_option( 'enable_crawler_control', 1 ) ) {
			return $output;
		}

		$crawlers = array(
			'OAI-SearchBot'    => micropedia_ai_get_option( 'crawler_oai_searchbot', 'neutral' ),
			'GPTBot'           => micropedia_ai_get_option( 'crawler_gptbot', 'neutral' ),
			'Google-Extended'  => micropedia_ai_get_option( 'crawler_google_extended', 'neutral' ),
			'PerplexityBot'    => micropedia_ai_get_option( 'crawler_perplexitybot', 'neutral' ),
			'ClaudeBot'        => micropedia_ai_get_option( 'crawler_claudebot', 'neutral' ),
		);

		$lines = array();
		foreach ( $crawlers as $bot => $rule ) {
			$rule = sanitize_key( $rule );
			if ( ! in_array( $rule, array( 'allow', 'disallow' ), true ) ) {
				continue;
			}
			$lines[] = 'User-agent: ' . $bot;
			$lines[] = ( 'allow' === $rule ) ? 'Allow: /' : 'Disallow: /';
			$lines[] = '';
		}

		if ( empty( $lines ) ) {
			return $output;
		}

		return rtrim( $output ) . "\n\n# Micropedia AI Search Optimizer\n" . implode( "\n", array_map( 'sanitize_text_field', $lines ) );
	}
}
