<?php
/**
 * Memanto REST Controller
 *
 * Handles MEMANTO memory and preferences operations.
 *
 * @package WP_Agentic_Writer
 */

/**
 * Class WP_Agentic_Writer_Controller_Memanto
 *
 * REST controller for MEMANTO memory operations.
 *
 * @since 0.3.0
 */
class WP_Agentic_Writer_Controller_Memanto
{
    /**
     * Sidebar instance for dependency access.
     *
     * @var WP_Agentic_Writer_Gutenberg_Sidebar
     */
    private $sidebar;

    /**
     * Constructor.
     *
     * @since 0.3.0
     * @param WP_Agentic_Writer_Gutenberg_Sidebar $sidebar Sidebar instance.
     */
    public function __construct($sidebar)
    {
        $this->sidebar = $sidebar;
    }

    /**
     * Handle MEMANTO status check.
     *
     * Returns current MEMANTO connection status, health, and configuration
     * state for the frontend sidebar indicator.
     *
     * @since 0.3.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response Status response.
     */
    public function handle_memanto_status($request)
    {
        $client = WP_Agentic_Writer_Memanto_Client::get_instance();
        $settings = get_option("wp_agentic_writer_settings", []);

        $configured = $client->is_configured();
        $enabled = $client->is_enabled();
        $healthy = $configured && $enabled ? $client->is_healthy() : false;

        return new WP_REST_Response(
            [
                "configured" => $configured,
                "enabled" => $enabled,
                "healthy" => $healthy,
                "active" => $configured && $enabled && $healthy,
                "url_set" => !empty($settings["memanto_url"]),
                "key_set" => !empty($settings["memanto_moorcheh_key"]),
            ],
            200,
        );
    }

    /**
     * Handle MEMANTO recall request.
     *
     * Returns recent memories for a post and user preferences.
     * Used by the frontend to show "Restored from memory" indicator
     * and to carry preferences across posts.
     *
     * @since 0.3.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response|WP_Error Response.
     */
    public function handle_memanto_recall($request)
    {
        $post_id = (int) ($request->get_param("post_id") ?? 0);
        $user_id = get_current_user_id();

        if ($post_id > 0 && !$this->sidebar->check_post_permission($post_id)) {
            return new WP_Error(
                "forbidden",
                __(
                    "You do not have permission to access this post.",
                    "wp-agentic-writer",
                ),
                ["status" => 403],
            );
        }

        $enhancer = WP_Agentic_Writer_Memanto_Context_Enhancer::get_instance();
        $memories = $enhancer->recall_for_context(
            $post_id,
            $user_id,
            "", // No current message for restore — just recent + preferences.
        );

        // Separate preferences from other memories for frontend display.
        $preferences = [];
        $other = [];
        foreach ($memories as $memory) {
            if (($memory["type"] ?? "") === "preference") {
                $preferences[] = $memory;
            } else {
                $other[] = $memory;
            }
        }

        return new WP_REST_Response(
            [
                "memories" => $other,
                "preferences" => $preferences,
                "count" => count($memories),
                "post_id" => $post_id,
            ],
            200,
        );
    }

    /**
     * Handle MEMANTO session restore.
     *
     * Called when the post editor opens to restore prior session state.
     * Returns recent memories + preferences + a restore summary.
     *
     * @since 0.4.0
     * @param WP_REST_Request $request REST request with post_id param.
     * @return WP_REST_Response|WP_Error Restore payload.
     */
    public function handle_memanto_restore($request)
    {
        $post_id = (int) ($request->get_param("post_id") ?? 0);
        $user_id = get_current_user_id();

        if ($post_id > 0 && !$this->sidebar->check_post_permission($post_id)) {
            return new WP_Error(
                "forbidden",
                __(
                    "You do not have permission to access this post.",
                    "wp-agentic-writer",
                ),
                ["status" => 403],
            );
        }

        $enhancer = WP_Agentic_Writer_Memanto_Context_Enhancer::get_instance();
        $payload = $enhancer->restore_session($post_id, $user_id);

        // Build the restored system message for AI context.
        $system_message = "";
        if (!empty($payload["restored"])) {
            $system_message = $enhancer->build_session_restore_message(
                $payload,
            );
        }

        return new WP_REST_Response(
            [
                "restored" => $payload["restored"],
                "memories" => $payload["memories"],
                "preferences" => $payload["preferences"],
                "summary" => $payload["summary"],
                "system_message" => $system_message,
                "memory_count" => count($payload["memories"]),
                "preference_count" => count($payload["preferences"]),
                "post_id" => $post_id,
            ],
            200,
        );
    }

    /**
     * Handle MEMANTO user preferences recall.
     *
     * Returns extracted preference config for new-post config carry-over.
     *
     * @since 0.4.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response Preference payload.
     */
    public function handle_memanto_preferences($request)
    {
        $user_id = get_current_user_id();

        $enhancer = WP_Agentic_Writer_Memanto_Context_Enhancer::get_instance();
        $result = $enhancer->get_user_preferences_for_new_post($user_id);

        return new WP_REST_Response(
            [
                "restored" => $result["restored"],
                "config" => $result["config"],
            ],
            200,
        );
    }
}
