<?php

namespace App\Services\Ai;

use App\Models\Conversation;
use App\Models\Setting;
use App\Services\AiService;
use Exception;

class AiChatAssistant
{
    protected $aiService;

    public function __construct(AiService $aiService)
    {
        $this->aiService = $aiService;
    }

    public function generateReply(Conversation $conversation, $userId)
    {
        $messages = $conversation->messages()->latest()->take(5)->get()->reverse();
        
        if ($messages->isEmpty()) {
            throw new Exception("Not enough chat history to generate a reply.");
        }

        $isSeller = $userId === $conversation->seller_id;
        $roleName = $isSeller ? 'Seller' : 'Buyer';
        
        // 1. Fetch Dynamic Admin Prompt
        $basePrompt = Setting::where('key', 'ai_chat_assistant_prompt')->value('value');
        if (empty(trim($basePrompt))) {
            $basePrompt = "You are a helpful, professional eCommerce {role}. You are replying to the other party in a marketplace chat. Keep the reply concise, polite, and directly address their last message. Do not include placeholders like [Your Name]. Just provide the raw message text.";
        }

        // 2. Replace variables
        $context = str_replace('{role}', $roleName, $basePrompt);

        // 3. Append required system context
        $context .= "\n\n--- CHAT HISTORY ---\n";

        foreach ($messages as $msg) {
            $sender = $msg->sender_id === $userId ? 'Me' : 'Them';
            $context .= "{$sender}: {$msg->body}\n";
        }
        
        $context .= "\n--- END HISTORY ---\nProvide the best next reply for 'Me':";

        return $this->aiService->generateText($context, 'You are an expert customer service AI.');
    }
}