<?php
namespace TeknoTok\AiTranslator\Utils;

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

/**
 * Guards translation work so only public frontend URLs are processed.
 */
class UrlGuard {
	/**
	 * Check whether a URL is a public frontend URL on this site.
	 *
	 * @param string $url URL to inspect.
	 * @return bool True when the URL is safe for frontend warmup/translation.
	 */
	public static function is_frontend_url( $url ) {
		$url = trim( (string) $url );
		if ( '' === $url ) {
			return false;
		}

		$parts = self::parse_url( $url );
		if ( empty( $parts ) ) {
			return false;
		}

		if ( ! self::is_local_url( $parts ) ) {
			return false;
		}

		$path = isset( $parts['path'] ) ? '/' . ltrim( strtolower( (string) $parts['path'] ), '/' ) : '/';
		foreach ( self::blocked_path_prefixes() as $prefix ) {
			if ( 0 === strpos( $path, $prefix ) ) {
				return false;
			}
		}

		if ( isset( $parts['query'] ) && false !== stripos( (string) $parts['query'], 'rest_route=' ) ) {
			return false;
		}

		return true;
	}

	/**
	 * Parse a URL with WordPress helper when available.
	 *
	 * @param string $url URL.
	 * @return array|false Parsed parts.
	 */
	private static function parse_url( $url ) {
		if ( function_exists( 'wp_parse_url' ) ) {
			return wp_parse_url( $url );
		}

		return parse_url( $url );
	}

	/**
	 * Check whether parsed URL belongs to this site.
	 *
	 * @param array $parts Parsed URL parts.
	 * @return bool True when local.
	 */
	private static function is_local_url( $parts ) {
		if ( empty( $parts['host'] ) ) {
			return true;
		}

		$home = function_exists( 'home_url' ) ? home_url( '/' ) : ( function_exists( 'get_option' ) ? get_option( 'home', '' ) : '' );
		$home_parts = self::parse_url( $home );
		if ( empty( $home_parts['host'] ) ) {
			return true;
		}

		return strtolower( (string) $parts['host'] ) === strtolower( (string) $home_parts['host'] );
	}

	/**
	 * Paths that should never trigger translation work.
	 *
	 * @return array Blocked path prefixes.
	 */
	private static function blocked_path_prefixes() {
		return array(
			'/wp-admin',
			'/wp-login.php',
			'/wp-json',
			'/wp-cron.php',
			'/wp-content',
			'/wp-includes',
			'/xmlrpc.php',
			'/wp-admin/admin-ajax.php',
		);
	}
}
