<?php

/**
 * Loads Plugin Builder prompt definitions from disk.
 *
 * @package LolaCore\PluginBuilder\Generation
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\PluginBuilder\Generation;

// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Diagnostic exception messages; escaped at REST/chat presentation layer.

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

/**
 * Reads prompts/prompts.php once per request (OPcache-friendly).
 */
class PromptLoader {

	/**
	 * @var array<string, mixed>|null
	 */
	private static ?array $cache = null;

	/**
	 * @return array<string, mixed>
	 */
	public function load(): array {
		if (self::$cache !== null) {
			return self::$cache;
		}

		$path = LOLACORE_PLUGIN_DIR . 'src/PluginBuilder/prompts/prompts.php';
		if (! is_readable($path)) {
			throw new \RuntimeException(__('Plugin Builder prompts file is missing.', 'lolacore'));
		}

		/** @var mixed $prompts */
		$prompts = require $path;
		if (! is_array($prompts)) {
			throw new \RuntimeException(__('Plugin Builder prompts file is invalid.', 'lolacore'));
		}

		self::$cache = $prompts;
		return self::$cache;
	}

	/**
	 * Build the full developer system instruction string.
	 */
	public function buildDeveloperSystemPrompt(): string {
		$prompts = $this->load();
		$developer = $prompts['developer'] ?? array();
		if (! is_array($developer)) {
			throw new \RuntimeException(__('Developer prompts are misconfigured.', 'lolacore'));
		}

		$system = isset($developer['system']) ? (string) $developer['system'] : '';
		$rules  = $developer['rules'] ?? array();
		$format = isset($developer['output_format']) ? (string) $developer['output_format'] : '';

		$rulesText = '';
		if (is_array($rules)) {
			foreach ($rules as $index => $rule) {
				if (! is_scalar($rule)) {
					continue;
				}
				$rulesText .= ($index + 1) . '. ' . trim((string) $rule) . "\n";
			}
		}

		return trim($system . "\n\nCoding rules:\n" . $rulesText . "\n\nOutput format:\n" . $format);
	}

	/**
	 * Reviewer system instruction.
	 */
	public function buildReviewerSystemPrompt(): string {
		$prompts = $this->load();
		$reviewer = $prompts['reviewer'] ?? array();
		if (! is_array($reviewer) || ! isset($reviewer['system'])) {
			throw new \RuntimeException(__('Reviewer prompts are misconfigured.', 'lolacore'));
		}

		return trim((string) $reviewer['system']);
	}
}

