<?php
/**
 * Generation language service.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Builds strict target-language instructions for every generation pipeline.
 */
class SmartyPress_AI_Content_Generator_Generation_Language_Service {

	/**
	 * Site language fallback.
	 *
	 * @var string
	 */
	private $site_language;

	/**
	 * Constructor.
	 *
	 * @param string $site_language Site language fallback.
	 */
	public function __construct( $site_language = '' ) {
		$this->site_language = trim( (string) $site_language );
	}

	/**
	 * Build strict target-language instruction.
	 *
	 * @param string $language Target output language.
	 * @param string $artifact Reader-facing artifact type.
	 * @return string
	 */
	public function get_output_language_instruction( $language, $artifact = 'content' ) {
		$language = $this->resolve_language( $language );
		$artifact = sanitize_key( $artifact );

		$artifact_notes = array(
			'title'          => 'Generate a new natural title in the target language. Treat the source topic as an idea, not as a ready title.',
			'sections'       => 'Generate headings only in the target language.',
			'content'        => 'Generate article body, headings, excerpt, and reader-facing text only in the target language.',
			'excerpt'        => 'Generate summary text only in the target language.',
			'seo_metadata'   => 'Generate SEO title, meta description, slug words, and keywords only in the target language.',
			'image_metadata' => 'Generate image title, alt text, caption, and description only in the target language. The visual image prompt itself may remain in the user language.',
		);

		$note = $artifact_notes[ $artifact ] ?? $artifact_notes['content'];

		return sprintf(
			'TARGET OUTPUT LANGUAGE: %1$s. The source topic, context, title, or user prompt may be written in any language. Translate or adapt source-language ideas into %1$s before writing reader-facing output. Do not copy source text verbatim unless it is already a natural phrase in %1$s. %2$s',
			$language,
			$note
		);
	}

	/**
	 * Resolve target output language.
	 *
	 * @param string $language Target output language.
	 * @return string
	 */
	public function resolve_language( $language ) {
		$language = trim( (string) $language );
		if ( '' === $language ) {
			$language = '' !== $this->site_language ? $this->site_language : smartypress_ai_get_language_by_locale();
		}

		return $language;
	}
}
