<?php
/**
 * Multibyte-safe string helpers.
 *
 * @package AIAltTextGenerator
 * @since 2.4.3
 */

namespace AIAltTextGenerator;

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

/**
 * Thin wrappers so generation never fatals when mbstring is unavailable.
 *
 * @since 2.4.3
 */
class Text {

	public static function length( string $value ): int {
		if ( function_exists( 'mb_strlen' ) ) {
			return (int) mb_strlen( $value );
		}

		return strlen( $value );
	}

	public static function slice( string $value, int $start, ?int $length = null ): string {
		if ( function_exists( 'mb_substr' ) ) {
			return null === $length
				? (string) mb_substr( $value, $start )
				: (string) mb_substr( $value, $start, $length );
		}

		return null === $length
			? (string) substr( $value, $start )
			: (string) substr( $value, $start, $length );
	}

	/**
	 * Safe HTTP timeout that leaves headroom under PHP's max_execution_time.
	 */
	public static function safeHttpTimeout( int $requested, int $reserve_seconds = 8 ): int {
		$requested = max( 10, min( 180, $requested ) );
		$php_max   = (int) ini_get( 'max_execution_time' );

		if ( $php_max <= 0 ) {
			return $requested;
		}

		$available = max( 10, $php_max - max( 3, $reserve_seconds ) );

		return min( $requested, $available );
	}

	/**
	 * Best-effort raise of the PHP time limit for a bulk AJAX step.
	 */
	public static function bumpTimeLimit( int $seconds = 120 ): void {
		if ( ! function_exists( 'set_time_limit' ) ) {
			return;
		}

		$current = (int) ini_get( 'max_execution_time' );
		if ( $current === 0 ) {
			return;
		}

		@set_time_limit( max( $seconds, $current ) );
	}
}
