<?php

namespace App\AiAgents;

use App\AiAgents\Contracts\LlmProviderInterface;
use App\Models\ChatHistory;
use App\Models\Product;
use App\Models\UserProductInteraction;
use App\Services\DealFinderService;
use App\Services\ProductComparisonService;
use App\Services\ProductQAService;
use App\Services\ProductRecommendationService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * @deprecated Use App\Services\AiAssistant\AiAssistantService instead
 */
class ProductAssistant
{
    protected LlmProviderInterface $provider;

    protected ProductRecommendationService $recommendationService;

    protected ProductComparisonService $comparisonService;

    protected ProductQAService $qaService;

    protected DealFinderService $dealService;

    public function __construct(
        ProductRecommendationService $recommendationService,
        ProductComparisonService $comparisonService,
        ProductQAService $qaService,
        DealFinderService $dealService,
        ?LlmProviderInterface $provider = null
    ) {
        $this->provider = $provider ?? LlmProviderFactory::create();
        $this->recommendationService = $recommendationService;
        $this->comparisonService = $comparisonService;
        $this->qaService = $qaService;
        $this->dealService = $dealService;
    }

    public function chat(string $message, ?string $sessionId = null, ?int $userId = null): array
    {
        $context = $this->buildContext($message);
        $systemPrompt = $this->getSystemPrompt();
        $conversationHistory = $this->getConversationHistory($userId, $sessionId);

        $response = $this->callAI([
            [
                'role' => 'system',
                'content' => $systemPrompt,
            ],
            ...$conversationHistory,
            [
                'role' => 'user',
                'content' => $this->buildUserMessage($message, $context),
            ],
        ]);

        $assistantResponse = $response['choices'][0]['message']['content'] ?? 'I apologize, but I couldn\'t generate a response.';

        $this->saveChatHistory($userId, $sessionId, $message, $assistantResponse, [
            'tools_used' => $context['tools_used'] ?? [],
            'products_mentioned' => $context['products_mentioned'] ?? [],
        ]);

        $this->trackProductInteractions($userId, $context['products_mentioned'] ?? []);

        return [
            'response' => $assistantResponse,
            'suggestions' => $this->generateFollowUpSuggestions($message, $context),
            'metadata' => [
                'provider' => $this->provider->getProviderName(),
                'model' => $this->provider->getModel(),
                'tools_used' => $context['tools_used'] ?? [],
            ],
        ];
    }

    protected function buildContext(string $message): array
    {
        $context = [
            'tools_used' => [],
            'products_mentioned' => [],
            'categories' => [],
        ];

        $lowerMessage = strtolower($message);

        if (str_contains($lowerMessage, 'deal') || str_contains($lowerMessage, 'discount') || str_contains($lowerMessage, 'offer')) {
            $context['tools_used'][] = 'findDeals';
            $deals = $this->dealService->findBestDeals(null, 5);
            $context['deals'] = $this->formatProducts($deals);
            $context['products_mentioned'] = array_merge($context['products_mentioned'], $deals->pluck('id')->toArray());
        }

        if (str_contains($lowerMessage, 'recommend') || str_contains($lowerMessage, 'suggest') || str_contains($lowerMessage, 'best')) {
            $context['tools_used'][] = 'getRecommendations';
            $recommendations = $this->recommendationService->getTrendingProducts(5);
            $context['recommendations'] = $this->formatProducts($recommendations);
            $context['products_mentioned'] = array_merge($context['products_mentioned'], $recommendations->pluck('id')->toArray());
        }

        if (str_contains($lowerMessage, 'compare') && preg_match_all('/\d+/', $message, $matches)) {
            $context['tools_used'][] = 'compareProducts';
            $productIds = array_slice($matches[0], 0, 5);
            $products = Product::with('category')->whereIn('id', $productIds)->get();
            if ($products->isNotEmpty()) {
                $context['comparison'] = $this->comparisonService->compare($products);
                $context['products_mentioned'] = array_merge($context['products_mentioned'], $productIds);
            }
        }

        if (preg_match('/product\s*(\d+)/i', $message, $matches)) {
            $context['tools_used'][] = 'getProductDetails';
            $productId = (int) $matches[1];
            $product = Product::with('category')->find($productId);
            if ($product) {
                $context['product'] = $this->formatProduct($product);
                $context['products_mentioned'][] = $productId;
            }
        }

        return $context;
    }

    protected function formatProducts($products): array
    {
        return $products->map(fn ($p) => $this->formatProduct($p))->toArray();
    }

    protected function formatProduct(Product $product): array
    {
        return [
            'id' => $product->id,
            'name' => $product->name_en ?? $product->name_ar,
            'price' => $product->price,
            'discount_price' => $product->discount_price,
            'discount' => $product->discount,
            'rating' => $product->positive_feedback,
            'sales' => $product->sales_180day,
            'category' => $product->category?->name_en ?? $product->category?->name_ar,
        ];
    }

    protected function getSystemPrompt(): string
    {
        return <<<'PROMPT'
You are a helpful AI shopping assistant for an e-commerce platform. Your role is to help users find products, compare options, get recommendations, and make informed purchasing decisions.

## Your Capabilities

1. **Product Search**: Help users find products by name, category, price range, or features
2. **Product Comparison**: Compare multiple products (3-5) across price, quality, features, and value
3. **Recommendations**: Suggest products based on user preferences, trending items, or similar products
4. **Deal Finding**: Find the best discounts, promotions, and coupon deals
5. **Product Q&A**: Answer specific questions about product features, pricing, and availability
6. **Category Guides**: Provide buying advice and category-specific recommendations
7. **Follow-up Suggestions**: Suggest relevant next questions to help users explore further

## Guidelines

- **Language**: Detect the user's language (Arabic or English) and respond in the same language
- **Scope**: Only help with shopping-related questions. Politely redirect off-topic queries
- **Tone**: Friendly, professional, and helpful. Be concise but informative
- **Accuracy**: Use only the provided product data. Don't invent information
- **Transparency**: If you don't have enough information, say so and suggest alternatives

## Product Information Available

When you receive context, it may contain:
- Product details (name, price, discount, rating, sales, category)
- Comparison data across multiple products
- Deal and discount information
- Recommendations based on various criteria

## Response Format

Structure your responses clearly:
1. **Direct Answer**: Address the user's question immediately
2. **Product Details**: Provide relevant product information when available
3. **Recommendations**: Suggest specific products when appropriate
4. **Next Steps**: Guide users on what they can do next

## Examples

**User**: "Find me gaming laptops under $1000"
**Response**: "I found several gaming laptops under $1000. Here are the top options:
1. [Product Name] - $899 with 15% discount
2. [Product Name] - $750 with excellent ratings
Would you like me to compare any of these?"

**User**: "What's the difference between products 123 and 456?"
**Response**: "Here's a comparison of the two products:
- Price: Product 123 ($500) vs Product 456 ($650)
- Rating: Product 123 (85%) vs Product 456 (92%)
- Best Value: Product 123 offers better value for money
- Best Quality: Product 456 has higher customer satisfaction

Which feature matters most to you?"

## Important Notes

- Prices are in the product's currency (shown in data)
- Ratings are based on customer feedback (0-100 scale)
- Sales data covers the last 180 days
- Discounts may include both percentage off and promo codes
- Always verify current prices and availability before purchasing

Help users make informed decisions and provide a great shopping experience!
PROMPT;
    }

    protected function buildUserMessage(string $message, array $context): string
    {
        $userMessage = "User message: {$message}\n\n";

        if (! empty($context)) {
            $userMessage .= "Relevant data:\n".json_encode($context, JSON_PRETTY_PRINT);
        }

        return $userMessage;
    }

    protected function getConversationHistory(?int $userId, ?string $sessionId): array
    {
        if (! $userId && ! $sessionId) {
            return [];
        }

        $history = ChatHistory::query()
            ->when($userId, fn ($q) => $q->where('user_id', $userId))
            ->when($sessionId && ! $userId, fn ($q) => $q->where('session_id', $sessionId))
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get()
            ->reverse();

        $messages = [];
        foreach ($history as $chat) {
            $messages[] = [
                'role' => 'user',
                'content' => $chat->user_message,
            ];
            $messages[] = [
                'role' => 'assistant',
                'content' => $chat->assistant_response,
            ];
        }

        return $messages;
    }

    protected function callAI(array $messages): array
    {
        try {
            return $this->provider->chat($messages);
        } catch (\Exception $e) {
            Log::error('AI chat error', ['error' => $e->getMessage()]);

            return $this->getFallbackResponse();
        }
    }

    protected function getFallbackResponse(): array
    {
        return [
            'choices' => [
                [
                    'message' => [
                        'content' => 'I apologize, but I\'m having trouble connecting to my AI service right now. Please try again in a moment. In the meantime, you can browse our products catalog or use specific filters to find what you\'re looking for.',
                    ],
                ],
            ],
        ];
    }

    protected function saveChatHistory(?int $userId, ?string $sessionId, string $userMessage, string $assistantResponse, array $metadata): void
    {
        ChatHistory::create([
            'user_id' => $userId,
            'session_id' => $userId ? null : $sessionId,
            'user_message' => $userMessage,
            'assistant_response' => $assistantResponse,
            'metadata' => $metadata,
        ]);
    }

    protected function trackProductInteractions(?int $userId, array $productIds): void
    {
        if (! $userId || empty($productIds)) {
            return;
        }

        foreach ($productIds as $productId) {
            UserProductInteraction::updateOrCreate(
                [
                    'user_id' => $userId,
                    'product_id' => $productId,
                    'interaction_type' => 'asked_about',
                ],
                [
                    'count' => DB::raw('count + 1'),
                    'last_interacted_at' => now(),
                ]
            );
        }
    }

    public function generateFollowUpSuggestions(string $currentMessage, array $context): array
    {
        $suggestions = [
            'Show me products under [price]',
            'Compare products [id1], [id2], [id3]',
            'What are the best deals today?',
            'Recommend products in [category]',
            'Tell me about product [id]',
        ];

        $lowerMessage = strtolower($currentMessage);

        if (str_contains($lowerMessage, 'laptop') || str_contains($lowerMessage, 'phone')) {
            $suggestions[] = 'Show me the top-rated options';
            $suggestions[] = 'What\'s the best value for money?';
        }

        if (str_contains($lowerMessage, 'deal') || str_contains($lowerMessage, 'discount')) {
            $suggestions[] = 'Find coupons and promo codes';
            $suggestions[] = 'Show me flash deals ending soon';
        }

        return array_slice($suggestions, 0, 5);
    }

    public function getHistory(?int $userId, ?string $sessionId): array
    {
        return ChatHistory::query()
            ->when($userId, fn ($q) => $q->where('user_id', $userId))
            ->when($sessionId && ! $userId, fn ($q) => $q->where('session_id', $sessionId))
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get()
            ->map(fn ($chat) => [
                'id' => $chat->id,
                'message' => $chat->user_message,
                'response' => $chat->assistant_response,
                'timestamp' => $chat->created_at->toISOString(),
            ])
            ->toArray();
    }

    public function clearHistory(?int $userId, ?string $sessionId): bool
    {
        return ChatHistory::query()
            ->when($userId, fn ($q) => $q->where('user_id', $userId))
            ->when($sessionId && ! $userId, fn ($q) => $q->where('session_id', $sessionId))
            ->delete() > 0;
    }
}
