<?php
namespace TeknoTok\AiTranslator\Database;

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

/**
 * Repository to interface with the Translation Memory database table.
 */
class MemoryRepository {
	/**
	 * Static in-memory cache for loaded translations.
	 * Format: array( target_lang => array( source_hash => translated_text ) )
	 *
	 * @var array
	 */
	private static $static_cache = array();

	/**
	 * Get table name.
	 *
	 * @return string
	 */
	private static function get_table_name() {
		global $wpdb;
		return $wpdb->prefix . 'teknotok_translations';
	}

	/**
	 * Initialize static cache for the given target language if not already loaded.
	 *
	 * @param string $target_lang Target language code.
	 * @return void
	 */
	private static function init_static_cache( $target_lang ) {
		global $wpdb;

		if ( isset( self::$static_cache[ $target_lang ] ) ) {
			return;
		}

		self::$static_cache[ $target_lang ] = array();

		$table = self::get_table_name();
		$query = $wpdb->prepare(
			"SELECT source_hash, translated_text FROM {$table} WHERE target_lang = %s",
			$target_lang
		);

		$results = $wpdb->get_results( $query );

		if ( ! empty( $results ) ) {
			foreach ( $results as $row ) {
				self::$static_cache[ $target_lang ][ $row->source_hash ] = $row->translated_text;
			}
		}
	}

	/**
	 * Retrieve a translation from cache.
	 *
	 * @param string $source_text Raw original text.
	 * @param string $target_lang Target language code.
	 * @return string|false Translated string on success, false if not cached.
	 */
	public static function get_translation( $source_text, $target_lang ) {
		if ( empty( $source_text ) ) {
			return $source_text;
		}

		$hash = md5( trim( $source_text ) );
		self::init_static_cache( $target_lang );

		if ( isset( self::$static_cache[ $target_lang ][ $hash ] ) ) {
			return self::$static_cache[ $target_lang ][ $hash ];
		}

		return false;
	}

	/**
	 * Retrieve a batch of translations in a single database query.
	 *
	 * @param array  $source_texts List of raw original strings.
	 * @param string $target_lang  Target language code.
	 * @return array Array mapping MD5 hash to translated text.
	 */
	public static function get_translations_batch( $source_texts, $target_lang ) {
		if ( empty( $source_texts ) ) {
			return array();
		}

		self::init_static_cache( $target_lang );

		$translations = array();
		foreach ( $source_texts as $text ) {
			$trimmed = trim( $text );
			if ( empty( $trimmed ) ) {
				continue;
			}
			$hash = md5( $trimmed );
			if ( isset( self::$static_cache[ $target_lang ][ $hash ] ) ) {
				$translations[ $hash ] = self::$static_cache[ $target_lang ][ $hash ];
			}
		}

		return $translations;
	}

	/**
	 * Store a translation in the translation memory table.
	 *
	 * @param string $source_text Original text string.
	 * @param string $translated_text Translated text string.
	 * @param string $source_lang Source language code.
	 * @param string $target_lang Target language code.
	 * @return bool True on success, false on failure.
	 */
	public static function save_translation( $source_text, $translated_text, $source_lang, $target_lang ) {
		global $wpdb;

		if ( empty( $source_text ) || empty( $translated_text ) ) {
			return false;
		}

		$hash = md5( trim( $source_text ) );
		$table = self::get_table_name();

		$data = array(
			'source_hash'     => $hash,
			'source_text'     => $source_text,
			'translated_text' => $translated_text,
			'source_lang'     => $source_lang,
			'target_lang'     => $target_lang,
			'last_used'       => current_time( 'mysql' ),
		);

		$format = array( '%s', '%s', '%s', '%s', '%s', '%s' );

		$inserted = $wpdb->replace( $table, $data, $format );

		if ( false !== $inserted ) {
			self::init_static_cache( $target_lang );
			self::$static_cache[ $target_lang ][ $hash ] = $translated_text;
			return true;
		}

		return false;
	}

	/**
	 * Clear translation cache data.
	 *
	 * @return void
	 */
	public static function clear_cache() {
		global $wpdb;
		$table = self::get_table_name();
		$wpdb->query( "TRUNCATE TABLE {$table}" );
		self::$static_cache = array();
	}
}
