<?php
/**
 * Bot & non-human traffic filtering.
 *
 * @package Defog
 */

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

class Defog_Bot_Filter {

	/**
	 * Decide whether a request should be ignored (bot, crawler, headless,
	 * prefetch/prerender, or empty UA).
	 *
	 * @param string $user_agent Raw user-agent.
	 * @return bool True if the hit should be discarded.
	 */
	public static function is_bot( $user_agent ) {
		$ua = trim( (string) $user_agent );

		// No UA at all → not a real browser.
		if ( '' === $ua ) {
			return true;
		}

		// Browser prefetch / prerender should never count as a visit.
		if ( ! empty( $_SERVER['HTTP_SEC_PURPOSE'] ) ) {
			$purpose = strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_SEC_PURPOSE'] ) ) );
			if ( false !== strpos( $purpose, 'prefetch' ) || false !== strpos( $purpose, 'prerender' ) ) {
				return true;
			}
		}
		if ( ! empty( $_SERVER['HTTP_PURPOSE'] ) ) {
			$purpose = strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_PURPOSE'] ) ) );
			if ( false !== strpos( $purpose, 'prefetch' ) ) {
				return true;
			}
		}

		$patterns = array(
			'bot', 'crawl', 'spider', 'slurp', 'mediapartners', 'archiver',
			'headless', 'puppeteer', 'playwright', 'selenium', 'phantomjs',
			'lighthouse', 'pagespeed', 'gtmetrix', 'pingdom', 'uptime', 'monitor',
			'preview', 'scan', 'facebookexternalhit', 'embedly', 'curl', 'wget',
			'python-requests', 'python-urllib', 'go-http-client', 'java/', 'okhttp',
			'apache-httpclient', 'libwww', 'feedfetcher', 'dataminr', 'ahrefs',
			'semrush', 'mj12', 'dotbot', 'petalbot', 'bytespider', 'gptbot', 'ccbot',
			'claudebot', 'perplexitybot', 'google-extended', 'applebot',
		);

		$ua_l = strtolower( $ua );
		foreach ( $patterns as $needle ) {
			if ( false !== strpos( $ua_l, $needle ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Allow themes/plugins to extend the bot signature list.
	 * (Reserved for a future filter hook in production.)
	 */
}
