<?php
// ─────────────────────────────────────────────
// includes/anthropic.php
// Leichter Wrapper um die Anthropic Messages API
// Modell-Default: claude-sonnet-4-20250514
// ─────────────────────────────────────────────

class C2CAnthropic {

    const API_URL  = 'https://api.anthropic.com/v1/messages';
    const VERSION  = '2023-06-01';
    const MODEL    = 'claude-sonnet-4-20250514';
    const TIMEOUT  = 120; // Sekunden

    /**
     * Sendet einen Prompt an Claude und gibt das Ergebnis zurück.
     *
     * @param string $systemPrompt  System-Prompt (Rolle, Stil, Constraints)
     * @param string $userPrompt    User-Nachricht
     * @param int    $maxTokens     Max output tokens
     * @return array  ['ok' => bool, 'text' => string, 'usage' => array, 'error' => ?string, 'raw' => mixed]
     */
    public static function complete(string $systemPrompt, string $userPrompt, int $maxTokens = 2000): array {
        if (!defined('ANTHROPIC_API_KEY') || empty(ANTHROPIC_API_KEY)) {
            return ['ok' => false, 'error' => 'ANTHROPIC_API_KEY nicht in config.php definiert'];
        }

        $payload = [
            'model'      => self::MODEL,
            'max_tokens' => $maxTokens,
            'system'     => $systemPrompt,
            'messages'   => [
                ['role' => 'user', 'content' => $userPrompt],
            ],
        ];

        $ch = curl_init(self::API_URL);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_UNICODE),
            CURLOPT_TIMEOUT        => self::TIMEOUT,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'x-api-key: ' . ANTHROPIC_API_KEY,
                'anthropic-version: ' . self::VERSION,
            ],
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr  = curl_error($ch);
        curl_close($ch);

        if ($curlErr) {
            return ['ok' => false, 'error' => 'cURL: ' . $curlErr];
        }

        $data = json_decode($response, true);

        if ($httpCode < 200 || $httpCode >= 300) {
            $msg = $data['error']['message'] ?? "HTTP $httpCode";
            return ['ok' => false, 'error' => $msg, 'raw' => $data];
        }

        // Text aus content blocks zusammenbauen
        $text = '';
        if (!empty($data['content']) && is_array($data['content'])) {
            foreach ($data['content'] as $block) {
                if (($block['type'] ?? '') === 'text') {
                    $text .= $block['text'];
                }
            }
        }

        return [
            'ok'    => true,
            'text'  => trim($text),
            'usage' => [
                'input'  => (int)($data['usage']['input_tokens']  ?? 0),
                'output' => (int)($data['usage']['output_tokens'] ?? 0),
            ],
            'raw'   => $data,
        ];
    }
}
