<?php

/**
 * MemoryHandler — Domain handler for Lola's persistent memory system.
 *
 * Owns: add_memory_fact
 *
 * Note: get_memory, search_memory, prune_memory are delegated to the
 * MemoryManager class directly. This handler exposes add_memory_fact
 * as the primary write action available through the tool schema.
 *
 * @package LolaCore\Actions\Handlers
 * @license GPL-2.0-or-later
 */

declare( strict_types=1 );

namespace LolaCore\Actions\Handlers;

use LolaCore\Actions\Contracts\ActionHandlerInterface;
use LolaCore\Memory\MemoryManager;

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

class MemoryHandler implements ActionHandlerInterface {

	/** @var string[] Valid fact type values accepted by MemoryManager. */
	private const VALID_TYPES = array( 'user_preference', 'business_context', 'site_state', 'decision_history' );

	public function getSupportedActions(): array {
		return array( 'add_memory_fact' );
	}

	public function handle( string $actionId, array $params, bool $dryRun ): array {
		return match ( $actionId ) {
			'add_memory_fact' => $this->addMemoryFact( $params ),
			default           => throw new \Exception( esc_html( "MemoryHandler: unknown action '{$actionId}'." ) ),
		};
	}

	/**
	 * Saves an explicit fact to Lola's persistent memory.
	 *
	 * Always executes regardless of dryRun — memory saves are non-destructive,
	 * user-initiated, and reversible via the maintenance panel.
	 *
	 * @param array $params Must contain 'content' and 'fact_type'. Optional: 'importance' (1-10).
	 * @return array Result with success, entry_id, and message.
	 * @throws \Exception On validation failure.
	 */
	private function addMemoryFact( array $params ): array {
		$content    = isset( $params['content'] ) ? sanitize_text_field( $params['content'] ) : '';
		$fact_type  = isset( $params['fact_type'] ) ? sanitize_text_field( $params['fact_type'] ) : '';
		$importance = isset( $params['importance'] ) ? max( 1, min( 10, (int) $params['importance'] ) ) : 5;

		if ( empty( $content ) || empty( $fact_type ) ) {
			throw new \Exception( 'Both content and fact_type are required.' );
		}

		if ( ! in_array( $fact_type, self::VALID_TYPES, true ) ) {
			throw new \Exception( 'Invalid fact_type. Use: ' . esc_html( implode( ', ', self::VALID_TYPES ) ) );
		}

		$memory   = new MemoryManager();
		$entry_id = $memory->saveFact( $fact_type, $content, $importance, 'explicit' );

		return array(
			'success'  => $entry_id > 0,
			'entry_id' => $entry_id,
			'message'  => $entry_id > 0 ? 'Fact saved to memory.' : 'Failed to save fact.',
		);
	}
}
