<?php

declare(strict_types=1);

namespace SiteFort\Modules\Firewall;

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

// robots.txt AI-training opt-out. Google-Extended/Applebot-Extended have no
// blockable UA, so robots.txt is the only lever for them.
final class AiTrainingRobots {
	private const TOKENS = [
		'Google-Extended',
		'Applebot-Extended',
		'GPTBot',
		'ClaudeBot',
		'anthropic-ai',
		'Meta-ExternalAgent',
		'FacebookBot',
		'Amazonbot',
		'Bytespider',
		'CCBot',
		'cohere-ai',
		'cohere-training-data-crawler',
		'Diffbot',
		'ImagesiftBot',
		'Timpibot',
		'AI2Bot',
		'PanguBot',
		'GrokBot',
	];

	// Append the opt-out block when enabled, skipping any token already present.
	public static function append_directives( string $robots, bool $enabled ): string {
		if ( ! $enabled ) {
			return $robots;
		}

		$groups = [];
		foreach ( self::TOKENS as $token ) {
			if ( stripos( $robots, $token ) === false ) {
				$groups[] = 'User-agent: ' . $token . "\nDisallow: /";
			}
		}

		if ( $groups === [] ) {
			return $robots;
		}

		$block = "# SiteFort: opt out of AI model training\n" . implode( "\n\n", $groups );

		return rtrim( $robots ) . "\n\n" . $block . "\n";
	}

	// A physical robots.txt at the site root overrides WordPress's virtual one, so the
	// filter has no effect while it exists. get_home_path() resolves the served root
	// correctly even when WordPress lives in a subdirectory.
	public static function static_robots_txt_present(): bool {
		if ( ! function_exists( 'get_home_path' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}

		return file_exists( get_home_path() . 'robots.txt' );
	}
}
