<?php
/**
 * @package Hafenstudios\Wellenbrecher
 */

namespace Hafenstudios\Wellenbrecher\Rules;

use Hafenstudios\Wellenbrecher\Engine\Context;
use Hafenstudios\Wellenbrecher\Engine\RuleResult;

defined( 'ABSPATH' ) || exit;

/**
 * Fremdskript-Anteil ueber 50 Prozent: Skript-Analyse statt externer
 * Spracherkennung (ersetzt fuer DACH 90 Prozent einer Sprach-API). Die
 * Liste der als fremd geltenden Schriftsysteme ist konfigurierbar
 * (Settings lists.foreign_scripts).
 */
class ForeignScriptRule extends AbstractRule {

	public const ID             = 'foreign_script';
	public const DEFAULT_POINTS = 15;

	public const MAX_RATIO = 0.5;

	/**
	 * Unicode-Skriptnamen (\p{...}-tauglich).
	 *
	 * @var array<int, string>
	 */
	protected array $scripts;

	/**
	 * @param array<int, string> $scripts Fremde Schriftsysteme.
	 * @param int                $points  Punkte.
	 */
	public function __construct( array $scripts = array( 'Cyrillic', 'Han', 'Arabic', 'Hebrew', 'Thai' ), int $points = self::DEFAULT_POINTS ) {
		parent::__construct( $points );
		$this->scripts = $scripts;
	}

	public function id(): string {
		return self::ID;
	}

	public function stage(): int {
		return 2;
	}

	public function evaluate( Context $context ): RuleResult {
		$content = $context->field( 'content' );
		if ( '' === trim( $content ) ) {
			return $this->miss();
		}

		$total = preg_match_all( '/\p{L}/u', $content );
		if ( ! $total ) {
			return $this->miss();
		}

		$foreign = 0;
		foreach ( $this->scripts as $script ) {
			$script = preg_replace( '/[^A-Za-z_]/', '', (string) $script );
			if ( '' === $script ) {
				continue;
			}
			$count = preg_match_all( '/\p{' . $script . '}/u', $content );
			if ( is_int( $count ) ) {
				$foreign += $count;
			}
		}

		return ( $foreign / $total ) > self::MAX_RATIO ? $this->hit() : $this->miss();
	}
}
