<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Services;

use ImovelZapAi\AiGateway\Application\Data\AiCompletionRequest;
use ImovelZapAi\AiGateway\Application\Data\AiMessageData;
use ImovelZapAi\AiGateway\Application\Services\AiGateway;
use ImovelZapAi\AiGateway\Domain\Enums\AiTaskType;
use ImovelZapAi\AiGateway\Infrastructure\Providers\OpenAiProvider;
use ImovelZapAi\Conversations\Application\Data\BrokerReplySuggestionContextData;
use ImovelZapAi\Conversations\Application\Data\BrokerReplySuggestionResultData;
use Throwable;

final class BrokerReplySuggestionAiGenerator
{
    public function __construct(
        private readonly AiGateway $aiGateway,
        private readonly OpenAiProvider $openAiProvider,
        private readonly BrokerReplySuggestionRuleGenerator $fallback,
    ) {}

    public function canGenerate(): bool
    {
        return $this->aiGateway->isEnabled() && $this->openAiProvider->isConfigured();
    }

    public function generate(BrokerReplySuggestionContextData $context): ?BrokerReplySuggestionResultData
    {
        if (! $this->canGenerate()) {
            return null;
        }

        try {
            $response = $this->aiGateway->complete(new AiCompletionRequest(
                tenantId: $context->tenantId,
                taskType: AiTaskType::ReplySuggestion,
                messages: [
                    new AiMessageData('system', $this->systemPrompt()),
                    new AiMessageData('user', json_encode($this->payload($context), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)),
                ],
                metadata: [
                    'conversation_id' => $context->conversationId,
                ],
                temperature: 0.6,
                maxTokens: 500,
            ));

            $text = trim($response->text);

            if ($text === '' || str_starts_with($text, '[IA desabilitada]')) {
                return null;
            }

            return new BrokerReplySuggestionResultData(
                suggestion: $this->personalize($text, $context),
                generatedBy: 'ai',
            );
        } catch (Throwable) {
            return null;
        }
    }

    private function systemPrompt(): string
    {
        return <<<'PROMPT'
Você redige mensagens de WhatsApp para corretores imobiliários no Brasil.

Objetivo: sugerir UMA mensagem pronta para o corretor revisar e enviar.

Regras:
- Português do Brasil, tom humano, profissional e acolhedor.
- Mensagens curtas (2 a 4 parágrafos), sem markdown.
- Pode confirmar interesse, responder dúvidas comuns, explicar documentação ou orientar próximos passos.
- Use apenas informações do contexto fornecido.
- Não invente valores, horários ou imóveis.
- Não use placeholders como [nome] — escreva a mensagem completa.
- Responda APENAS com o texto da mensagem, sem JSON e sem aspas.
PROMPT;
    }

    /**
     * @return array<string, mixed>
     */
    private function payload(BrokerReplySuggestionContextData $context): array
    {
        return [
            'client_name' => $context->clientName,
            'broker_name' => $context->brokerName,
            'last_client_message' => $context->lastClientMessage,
            'conversation_excerpts' => $context->recentMessages,
            'summary_bullets' => $context->summaryBullets,
            'recommended_next_step' => $context->recommendedNextStep,
            'favorite_property_codes' => $context->favoritePropertyCodes,
            'requested_visit' => $context->requestedVisit,
        ];
    }

    private function personalize(string $text, BrokerReplySuggestionContextData $context): string
    {
        return str_replace('{{corretor}}', $context->brokerName, $text);
    }
}
