<?php
/**
 * Z-AI Web SDK PHP Equivalent
 * Replaces z-ai-web-dev-sdk with direct cURL HTTP calls
 */
class ZaiApi {
    private string $baseUrl;
    private string $apiKey;

    public function __construct() {
        $this->baseUrl = defined('ZAI_BASE_URL') && ZAI_BASE_URL ? ZAI_BASE_URL : '';
        $this->apiKey = defined('ZAI_API_KEY') && ZAI_API_KEY ? ZAI_API_KEY : '';
        if (!$this->baseUrl || !$this->apiKey) {
            throw new RuntimeException('Z-AI configuration missing. Run install.php first.');
        }
    }

    private function request(string $endpoint, array $body): array {
        $url = rtrim($this->baseUrl, '/') . $endpoint;
        $payload = json_encode($body);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 180,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->apiKey,
                'X-Z-AI-From: Z',
            ],
        ]);

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

        if ($error) {
            throw new RuntimeException("cURL error: $error");
        }

        if ($httpCode >= 400) {
            throw new RuntimeException("API request failed with status $httpCode: $response");
        }

        return json_decode($response, true) ?: [];
    }

    /**
     * Chat completion (LLM)
     */
    public function chatCompletion(string $model, array $messages): array {
        return $this->request('/chat/completions', [
            'model' => $model,
            'messages' => $messages,
            'thinking' => ['type' => 'disabled'],
        ]);
    }

    /**
     * Vision completion (VLM)
     */
    public function visionCompletion(array $messages): array {
        return $this->request('/chat/completions/vision', [
            'messages' => $messages,
            'thinking' => ['type' => 'disabled'],
        ]);
    }

    /**
     * Image generation (text-to-image)
     * Returns array with 'data' containing items with 'url' or 'base64'
     */
    public function imageGeneration(string $prompt, string $size = '1024x1024'): array {
        $result = $this->request('/images/generations', [
            'prompt' => $prompt,
            'size' => $size,
        ]);

        // Download URLs to base64 (same as Node SDK)
        if (isset($result['data'])) {
            foreach ($result['data'] as &$item) {
                if (isset($item['url'])) {
                    $item['base64'] = $this->downloadImageAsBase64($item['url']);
                    $item['format'] = 'png';
                }
            }
        }

        return $result;
    }

    /**
     * Image edit (image-to-image)
     */
    public function imageEdit(string $prompt, string $imageUrl, string $size = '1024x1024'): array {
        $result = $this->request('/images/generations/edit', [
            'prompt' => $prompt,
            'images' => [['url' => $imageUrl]],
            'size' => $size,
        ]);

        // Download URLs to base64
        if (isset($result['data'])) {
            foreach ($result['data'] as &$item) {
                if (isset($item['url'])) {
                    $item['base64'] = $this->downloadImageAsBase64($item['url']);
                    $item['format'] = 'png';
                }
            }
        }

        return $result;
    }

    private function downloadImageAsBase64(string $url): string {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true,
        ]);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($error || $code !== 200) {
            throw new RuntimeException("Failed to download image: $error (HTTP $code)");
        }

        return base64_encode($data);
    }
}