<?php

namespace ZenoChatbot\Services\Chat;

use ZenoChatbot\Services\Chat\Contracts\SavedReplyMatcherInterface;
use ZenoChatbot\Services\Chat\Support\TextNormalizer;


if (!defined('ABSPATH')) {
    exit;
}
class DefaultSavedReplyMatcher implements SavedReplyMatcherInterface
{
    /**
     * Match user message against saved replies
     * Priority: exact > keywords > contains
     *
     * @param string $message User's message
     * @param array $replies Array of SavedReply objects grouped by match_type
     * @return array|null Matched reply data or null
     */
    public function match(string $message, array $replies): ?array
    {
        $normalizedMessage = TextNormalizer::normalize($message);

        if (empty($normalizedMessage)) {
            return null;
        }

        // 1. Exact match (highest priority)
        if (!empty($replies['exact'])) {
            foreach ($replies['exact'] as $reply) {
                $normalizedQuestion = TextNormalizer::normalize($reply->question);
                if ($normalizedQuestion === $normalizedMessage) {
                    return $this->formatMatch($reply);
                }
            }
        }

        // 2. Keyword match
        if (!empty($replies['keyword'])) {
            foreach ($replies['keyword'] as $reply) {
                if (empty($reply->keywords)) {
                    continue;
                }
                $keywords = array_map('trim', explode(',', strtolower($reply->keywords)));
                foreach ($keywords as $keyword) {
                    if (!empty($keyword) && str_contains($normalizedMessage, $keyword)) {
                        return $this->formatMatch($reply);
                    }
                }
            }
        }

        // 3. Contains match
        if (!empty($replies['contains'])) {
            foreach ($replies['contains'] as $reply) {
                $normalizedQuestion = TextNormalizer::normalize($reply->question);
                if (str_contains($normalizedMessage, $normalizedQuestion)) {
                    return $this->formatMatch($reply);
                }
            }
        }

        return null;
    }

    /**
     * Format matched reply into standard array
     */
    protected function formatMatch($reply): array
    {
        return [
            'id' => $reply->id,
            'answer' => $reply->answer,
            'match_type' => $reply->match_type,
            'question' => $reply->question
        ];
    }
}
