<?php

namespace ZenoChatbot\Services\LLMService\AIClient\Providers\Adapters;

use ZenoChatbot\Services\HttpClient;
use ZenoChatbot\Services\LLMService\AIClient\Config\AiConfig;
use ZenoChatbot\Services\LLMService\AIClient\Providers\Anthropic;
use ZenoChatbot\Services\LLMService\AIClient\Results\Candidate;
use ZenoChatbot\Services\LLMService\AIClient\Results\GenerativeAiResult;
use ZenoChatbot\Services\LLMService\AIClient\Results\TokenUsage;
use ZenoChatbot\Services\LLMService\AIClient\Support\ResponseParser;

if (!defined('ABSPATH')) {
    exit;
}

class AnthropicTextModel implements AdapterInterface
{
    public function generate(array $input, AiConfig $config): GenerativeAiResult
    {
        $payload = \ZenoChatbot\Services\LLMService\AIClient\Providers\PromptBuilders\AnthropicPromptBuilder::buildPayload($config, $input);

        $headers = [
            'x-api-key' => $config->getApiKey(),
            'anthropic-version' => Anthropic::API_VERSION,
        ];

        $client = new HttpClient();
        $url = Anthropic::API_V1 . Anthropic::MESSAGES_PATH;
        $resp = $client->post($url, $payload, $headers);
        $body = $resp['body'] ?? [];

        $candidates = [];
        $finishReason = $body['stop_reason'] ?? null;

        if (!empty($body['content']) && is_array($body['content'])) {
            $buf = '';
            foreach ($body['content'] as $block) {
                if (!is_array($block)) {
                    continue;
                }
                if (($block['type'] ?? '') === 'text') {
                    $buf .= (string)($block['text'] ?? '');
                }
            }
            if (trim($buf) !== '') {
                $candidates[] = new Candidate(trim($buf), $finishReason);
            }
        }

        if (empty($candidates) && !empty($input['fallback'])) {
            $candidates[] = new Candidate((string)$input['fallback'], 'end_turn');
        }

        $usage = $body['usage'] ?? [];
        $inputTokens = (int)($usage['input_tokens'] ?? 0);
        $outputTokens = (int)($usage['output_tokens'] ?? 0);
        $tokenUsage = new TokenUsage($inputTokens, $outputTokens, $inputTokens + $outputTokens);

        $citations = ResponseParser::extractCitations($candidates);

        $rawRequest = ResponseParser::sanitizeRequest($input, [
            'model' => $payload['model'] ?? null,
            'messages_count' => count($payload['messages'] ?? []),
            'has_system' => isset($payload['system']),
            'has_temperature' => isset($payload['temperature']),
        ]);

        return GenerativeAiResult::create([
            'candidates'    => $candidates,
            'token_usage'   => $tokenUsage,
            'finish_reason' => $finishReason,
            'citations'     => $citations,
            'provider'      => 'anthropic',
            'model'         => $config->getModel(),
            'raw_response'  => $body,
            'raw_request'   => $rawRequest,
        ]);
    }
}
