<?php

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

class Niwa_AI_Memory_Embedder {
    /** @var Niwa_AI_Content_Store_Interface|null */
    private $content_store;
    private $embedding_client;

    public function __construct( Niwa_AI_Content_Store_Interface $content_store, $embedding_client ) {
        $this->content_store    = $content_store;
        $this->embedding_client = $embedding_client;
    }

    public function process_pending( $limit = null ) {
        if ( null === $limit ) {
            $limit = Niwa_AI_Constants::EMBEDDING_BATCH_SIZE;
        }
        if ( ! $this->content_store || ! $this->embedding_client ) {
            return 0;
        }

        $rows = $this->content_store->get_pending_embeddings( $limit );
        if ( empty( $rows ) ) {
            return 0;
        }

        $texts = array();
        foreach ( $rows as $row ) {
            $text = isset( $row['memory_text'] ) ? (string) $row['memory_text'] : '';
            $texts[] = $this->clip_text( $text, Niwa_AI_Constants::EMBEDDING_CLIP_CHARS );
        }

        $embeddings = $this->embedding_client->embed_texts( $texts );
        if ( empty( $embeddings ) ) {
            return 0;
        }

        $updated = 0;
        foreach ( $rows as $i => $row ) {
            if ( empty( $row['doc_key'] ) ) {
                continue;
            }
            if ( empty( $embeddings[ $i ] ) || ! is_array( $embeddings[ $i ] ) ) {
                continue;
            }
            $hash = isset( $row['embedding_hash'] ) ? (string) $row['embedding_hash'] : '';
            if ( $this->content_store->update_embedding( $row['doc_key'], $embeddings[ $i ], $hash ) ) {
                $updated++;
            }
        }

        return $updated;
    }

    private function clip_text( $text, $max_chars ) {
        $text = trim( (string) $text );
        $max_chars = max( 500, intval( $max_chars ) );
        if ( mb_strlen( $text ) <= $max_chars ) {
            return $text;
        }
        return rtrim( mb_substr( $text, 0, $max_chars ) );
    }
}
