<?php

declare(strict_types=1);

namespace App\Services\AiAssistant\Tools;

use App\Models\Category;
use App\Models\Product;
use App\Services\AiAssistant\StructuredResponse;

class DoWeHaveItTool
{
    /**
     * Check if we have products matching a category/type.
     * Returns quick yes/no with count and available options.
     */
    public function check(string $query): StructuredResponse
    {
        // Normalize the query - extract key terms
        $searchTerms = $this->extractSearchTerms($query);

        // First check categories for exact match
        $category = $this->findMatchingCategory($searchTerms);

        if ($category) {
            $productCount = $category->products()->count();

            if ($productCount > 0) {
                return StructuredResponse::fromText(
                    "Yes, we have **{$productCount}** products in **{$category->name_en}**.\n\n".
                    "I can help you find the best options. Would you like me to:\n".
                    "- Show you the top-rated products\n".
                    "- Find products within a specific budget\n".
                    "- Show you current deals and discounts\n".
                    '- Help you compare specific options'
                );
            }

            return StructuredResponse::fromText(
                "We have the category **{$category->name_en}**, but there are currently no products available in it."
            );
        }

        // If no category match, check products directly
        $productCount = Product::query()
            ->where(function ($q) use ($searchTerms) {
                foreach ($searchTerms as $term) {
                    $q->orWhere('name_en', 'like', "%{$term}%")
                        ->orWhere('name_ar', 'like', "%{$term}%")
                        ->orWhere('description_en', 'like', "%{$term}%")
                        ->orWhere('description_ar', 'like', "%{$term}%");
                }
            })
            ->count();

        if ($productCount > 0) {
            return StructuredResponse::fromText(
                "Yes, we have **{$productCount}** products matching **\"{$query}\"**.\n\n".
                "I can help you find what you're looking for. What's your budget, or would you like me to show you the top options?"
            );
        }

        // No products found - list available categories to help
        $availableCategories = Category::query()
            ->whereHas('products')
            ->withCount('products')
            ->orderByDesc('products_count')
            ->limit(10)
            ->get()
            ->map(fn ($c) => "- {$c->name_en} ({$c->products_count} products)")
            ->implode("\n");

        return StructuredResponse::fromText(
            "Sorry, we don't have products matching **\"{$query}\"** at the moment.\n\n".
            "**Here are some categories we do have:**\n".
            $availableCategories."\n\n".
            'Would you like to explore any of these categories instead?'
        );
    }

    /**
     * Extract meaningful search terms from the query.
     */
    protected function extractSearchTerms(string $query): array
    {
        // Remove common words and keep meaningful terms
        $stopWords = [
            // English stop words
            'i', 'want', 'need', 'looking', 'for', 'find', 'show', 'me', 'get',
            'any', 'some', 'the', 'a', 'an', 'do', 'you', 'have', 'are',
            'there', 'is', 'available', 'in', 'stock', 'sell', 'buy',
            // Arabic stop words
            'انا', 'عايز', 'عايزة', 'ابغى', 'أبغى', 'اريد', 'أريد', 'محتاج', 'محتاجة',
            'شوف', 'وريني', 'أظهر', 'عندي', 'عندك', 'لديك', 'هل', 'موجود',
            'في', 'من', 'على', 'ال', 'بيع', 'تبيع', 'تشتري', 'أرخص', 'غالي',
            'اقل', 'أقل', 'أكثر', 'حاجة', 'شيء', 'شخص', 'حاجات', 'اشياء',
            'معاك', 'عندكم', 'لدكم', 'عدد', 'كم', 'كام', 'متى', 'اين',
        ];

        $terms = explode(' ', trim($query));
        $meaningfulTerms = [];

        foreach ($terms as $term) {
            $term = trim($term);
            $lowerTerm = strtolower($term);
            // Check both English and Arabic stop words
            if (strlen($term) > 1 && ! in_array($lowerTerm, $stopWords)) {
                $meaningfulTerms[] = $term;
            }
        }

        return $meaningfulTerms ?: [$query];
    }

    /**
     * Find a category matching the search terms.
     */
    protected function findMatchingCategory(array $terms): ?Category
    {
        // Try exact match first
        foreach ($terms as $term) {
            $category = Category::query()
                ->where('name_en', 'like', "%{$term}%")
                ->orWhere('name_ar', 'like', "%{$term}%")
                ->first();

            if ($category) {
                return $category;
            }
        }

        return null;
    }
}
