<?php

namespace App\Services\AI;

use App\Models\User;
use App\Repositories\AIConversationRepository;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;

class AgentService
{
    protected $promptBuilder;
    protected $contextManager;
    protected $memoryManager;
    protected $decisionEngine;
    protected $recommendationEngine;
    protected $conversationRepo;
    protected $provider;
    protected $apiKey;
    protected $model;

    public function __construct(
        PromptBuilder $promptBuilder,
        ContextManager $contextManager,
        MemoryManager $memoryManager,
        DecisionEngine $decisionEngine,
        RecommendationEngine $recommendationEngine,
        AIConversationRepository $conversationRepo
    ) {
        $this->promptBuilder = $promptBuilder;
        $this->contextManager = $contextManager;
        $this->memoryManager = $memoryManager;
        $this->decisionEngine = $decisionEngine;
        $this->recommendationEngine = $recommendationEngine;
        $this->conversationRepo = $conversationRepo;

        $this->provider = config('mindease.ai.provider', 'openai');
        $this->apiKey = config("services.{$this->provider}.api_key");
        $this->model = config("services.{$this->provider}.model", 'gpt-3.5-turbo');
    }

    public function processMessage(User $user, string $message): array
    {
        $context = $this->contextManager->buildContext($user);
        $memory = $this->memoryManager->getRecentMemory($user);
        $prompt = $this->promptBuilder->build($message, $context, $memory);
        $action = $this->decisionEngine->decide($prompt);
        $response = $this->callAIProvider($prompt);
        $recommendations = $this->recommendationEngine->generate($user, $message, $response);

        $conversation = $this->conversationRepo->create([
            'user_id' => $user->id,
            'user_message' => $message,
            'assistant_response' => $response,
            'context' => $context,
            'model_used' => $this->model,
            'tokens_used' => $this->estimateTokens($prompt . $response),
        ]);

        $this->memoryManager->store($user, $message, $response);

        return [
            'response' => $response,
            'conversation_id' => $conversation->id,
            'recommendations' => $recommendations,
        ];
    }

    protected function callAIProvider(string $prompt): string
    {
        if ($this->provider === 'openai') {
            $response = Http::withToken($this->apiKey)
                ->post('https://api.openai.com/v1/chat/completions', [
                    'model' => $this->model,
                    'messages' => [
                        ['role' => 'system', 'content' => 'You are a helpful mental wellness assistant.'],
                        ['role' => 'user', 'content' => $prompt],
                    ],
                    'temperature' => 0.7,
                ]);

            if ($response->failed()) {
                Log::error('OpenAI API error: ' . $response->body());
                return 'Sorry, I am having trouble responding right now.';
            }

            return $response->json('choices.0.message.content');
        }

        return 'AI response placeholder';
    }

    protected function estimateTokens(string $text): int
    {
        return (int) (strlen($text) / 4);
    }
}
