<?php
if (!defined('ABSPATH')) exit;

class SailWP_Copilot_AI_Client {
    public static function chat($messages, $opts = []) {
        $url = SailWP_Copilot_Plugin::get_ai_proxy_url() . '/copilot/chat';
        $body = array_merge([
            'messages' => $messages,
            'site' => home_url(),
        ], $opts);

        $response = wp_remote_post($url, [
            'timeout' => 60,
            'headers' => array_filter([
                'Content-Type' => 'application/json',
                'X-License-Key' => SailWP_Copilot_Plugin::get_license_key() ?: null,
                'X-Site-API-Key' => SailWP_Copilot_Plugin::get_site_api_key() ?: null,
            ]),
            'body' => wp_json_encode($body),
        ]);

        if (is_wp_error($response)) return $response;
        $code = wp_remote_retrieve_response_code($response);
        $payload = json_decode(wp_remote_retrieve_body($response), true);
        if ($code >= 400) {
            $msg = is_array($payload) && isset($payload['error']) ? $payload['error'] : 'AI proxy error';
            return new WP_Error('ai_proxy_error', $msg, ['status' => $code]);
        }
        return $payload;
    }
}
