<?php
/**
 * Wave Access – Leichte Sprache.
 * Besucher schaltet im Widget um; die Site holt die Übersetzung vom KI-Proxy
 * und cacht sie dauerhaft als Post-Meta (Inhalts-Hash → nur EINE Übersetzung
 * pro Seite und Inhaltsstand, egal wie viele Besucher umschalten).
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

class Wave_Easy_Language {

	const META_HTML = '_wave_easy_lang_html';
	const META_HASH = '_wave_easy_lang_hash';
	const MAX_CHARS = 20000; // Limit des Proxys
	const RATE_MAX  = 10;    // ungecachte Übersetzungen pro IP und Stunde

	public static function init() {
		add_action( 'rest_api_init', array( __CLASS__, 'routes' ) );
	}

	/** Leichte Sprache verfügbar? (AI-Plan + Proxy-Zugang + Website-Schalter aktiv) */
	public static function available() {
		if ( ! Wave_License::is_ai() ) {
			return false;
		}
		$o = WAVE_AI_Client::get_options();
		return ! empty( $o['easy_language'] ) && ! empty( $o['license_key'] ) && ! empty( $o['server_url'] );
	}

	public static function routes() {
		register_rest_route(
			'wave/v1',
			'/easy-language',
			array(
				'methods'             => 'POST',
				'permission_callback' => '__return_true',
				'callback'            => array( __CLASS__, 'rest_translate' ),
			)
		);
	}

	/** Quelltext der Seite als Klartext (gerenderte Blöcke/Shortcodes, ohne Markup). */
	private static function source_text( WP_Post $post ) {
		$html = apply_filters( 'the_content', $post->post_content );
		// Überschriften/Absätze als Absatzgrenzen erhalten.
		$html = preg_replace( '/<\/(p|h[1-6]|li|blockquote|figcaption|div)>/i', "$0\n\n", $html );
		$text = wp_strip_all_tags( $html );
		$text = preg_replace( "/[ \t]+/u", ' ', $text );
		$text = preg_replace( "/\n{3,}/u", "\n\n", trim( $text ) );
		return $text;
	}

	public static function rest_translate( WP_REST_Request $request ) {
		if ( ! self::available() ) {
			return new WP_REST_Response( array( 'ok' => false, 'message' => 'Leichte Sprache ist nicht verfügbar.' ), 403 );
		}

		$post_id = (int) $request->get_param( 'post_id' );
		$post    = $post_id ? get_post( $post_id ) : null;
		if ( ! $post || 'publish' !== $post->post_status || ! is_post_type_viewable( $post->post_type ) ) {
			return new WP_REST_Response( array( 'ok' => false, 'message' => 'Seite nicht gefunden.' ), 404 );
		}
		if ( post_password_required( $post ) ) {
			return new WP_REST_Response( array( 'ok' => false, 'message' => 'Seite ist geschützt.' ), 403 );
		}

		$text = self::source_text( $post );
		if ( '' === $text ) {
			return new WP_REST_Response( array( 'ok' => false, 'message' => 'Kein übersetzbarer Inhalt.' ), 400 );
		}
		if ( mb_strlen( $text ) > self::MAX_CHARS ) {
			$text = mb_substr( $text, 0, self::MAX_CHARS );
		}

		// Cache: gleiche Inhaltsfassung wird nie zweimal übersetzt.
		$hash = md5( $text );
		if ( get_post_meta( $post->ID, self::META_HASH, true ) === $hash ) {
			$html = (string) get_post_meta( $post->ID, self::META_HTML, true );
			if ( '' !== $html ) {
				return new WP_REST_Response( array( 'ok' => true, 'html' => $html, 'cached' => true ), 200 );
			}
		}

		// Rate-Limit nur für echte Proxy-Anfragen.
		$ip  = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
		$rk  = 'wave_easy_rate_' . md5( $ip );
		$cnt = (int) get_transient( $rk );
		if ( $cnt >= self::RATE_MAX ) {
			return new WP_REST_Response( array( 'ok' => false, 'message' => 'Zu viele Anfragen – bitte später erneut versuchen.' ), 429 );
		}
		set_transient( $rk, $cnt + 1, HOUR_IN_SECONDS );

		$result = WAVE_AI_Client::easy_language( $text );
		if ( is_wp_error( $result ) ) {
			return new WP_REST_Response( array( 'ok' => false, 'message' => $result->get_error_message() ), 502 );
		}

		$easy = trim( (string) $result['text'] );
		if ( '' === $easy ) {
			return new WP_REST_Response( array( 'ok' => false, 'message' => 'Leere Antwort vom KI-Proxy.' ), 502 );
		}

		$html = self::to_html( $easy );
		update_post_meta( $post->ID, self::META_HTML, $html );
		update_post_meta( $post->ID, self::META_HASH, $hash );

		return new WP_REST_Response( array( 'ok' => true, 'html' => $html, 'cached' => false ), 200 );
	}

	/** Klartext (mit "- "-Aufzählungen) → sicheres HTML mit <p>/<ul>. */
	private static function to_html( $text ) {
		$out    = '';
		$in_ul  = false;
		$blocks = preg_split( "/\n{2,}/u", $text );
		foreach ( $blocks as $block ) {
			$lines = explode( "\n", trim( $block ) );
			foreach ( $lines as $line ) {
				$line = trim( $line );
				if ( '' === $line ) {
					continue;
				}
				if ( preg_match( '/^#{1,6}\s+(.+)$/u', $line, $m ) ) {
					// Markdown-Überschriften des Modells → hervorgehobener Absatz
					if ( $in_ul ) { $out .= '</ul>'; $in_ul = false; }
					$out .= '<p><strong>' . esc_html( $m[1] ) . '</strong></p>';
				} elseif ( preg_match( '/^[-•*]\s+(.+)$/u', $line, $m ) ) {
					if ( ! $in_ul ) { $out .= '<ul>'; $in_ul = true; }
					$out .= '<li>' . esc_html( $m[1] ) . '</li>';
				} else {
					if ( $in_ul ) { $out .= '</ul>'; $in_ul = false; }
					$out .= '<p>' . esc_html( $line ) . '</p>';
				}
			}
			if ( $in_ul ) { $out .= '</ul>'; $in_ul = false; }
		}
		return $out;
	}
}

Wave_Easy_Language::init();
