<?php
/**
 * AR Display AI - SF3D Provider
 */

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

require_once __DIR__ . '/class-ardisplay-ai-provider-interface.php';

if (!class_exists('Ardisplay_Ai_Provider_SF3D')) {
    class Ardisplay_Ai_Provider_SF3D implements Ardisplay_Ai_Provider_Interface {
        private $base_url;
        private $api_key; // site token used to call proxy

        public function __construct(?string $base_url = null, ?string $api_key = null)
        {
            // Hardcode proxy base URL; ignore setting if present
            $configured_base = $base_url !== null ? $base_url : 'https://ardisplay.ai';
            $this->base_url = rtrim((string) $configured_base, '/');
            // In client mode we call the proxy with site token
            $this->api_key = $api_key !== null ? $api_key : (string) get_option('ardisplay_ai_proxy_site_token', '');
        }

        public function provider_name(): string
        {
            return 'sf3d';
        }

        public function create_job(array $images, array $params = [], string $ai_credits_token = ''): array
        {
            // Always call proxy if configured
            $proxy_base = $this->base_url;
            if (!$proxy_base) {
                return [ 'error' => __('Proxy base URL not configured', 'ar-for-wordpress') ];
            }
            
            // Use the passed AI credits token if provided, otherwise fall back to the stored one
            $token = $ai_credits_token ?: $this->api_key;
            if (!$token) {
                return [ 'error' => __('Proxy AI credits token not configured', 'ar-for-wordpress') ];
            }

            $webhook = rest_url('ar/v1/provider/sf3d/webhook');
            $body = [
                'images' => array_values($images),
                'params' => array_merge([
                    'mode' => 'image_to_3d',
                    'return_format' => 'glb',
                ], $params),
                'webhook' => $webhook,
            ];

            $last_error = __('Proxy endpoint not available', 'ar-for-wordpress');
            foreach ($this->proxy_endpoint_urls('jobs') as $endpoint) {
                error_log('[AR AI] Creating job via proxy endpoint: ' . $endpoint);
                $response = wp_remote_post($endpoint, [
                    'headers' => [
                        'X-ARDISPLAY-AI-Token' => $token,
                        'Content-Type' => 'application/json',
                    ],
                    'body' => wp_json_encode($body),
                    'timeout' => 30,
                ]);

                if (is_wp_error($response)) {
                    $last_error = $response->get_error_message();
                    error_log('[AR AI] Proxy job error: ' . $response->get_error_message());
                    continue;
                }
                $code = wp_remote_retrieve_response_code($response);
                $body_raw = wp_remote_retrieve_body($response);
                $data = json_decode($body_raw, true);
                if ($code === 404 && is_array($data) && ($data['code'] ?? '') === 'rest_no_route') {
                    $last_error = __('Proxy endpoint not found (rest_no_route)', 'ar-for-wordpress');
                    continue;
                }
                if ($code >= 400) {
                    $last_error = $data['message'] ?? ('HTTP ' . $code);
                    error_log('[AR AI] Proxy job HTTP ' . $code . ' body: ' . $body_raw);
                    continue;
                }
                return $data ?: [];
            }
            return [ 'error' => $last_error ];
        }

        public function get_job(string $job_id, string $ai_credits_token = ''): array
        {
            $proxy_base = $this->base_url;
            if (!$proxy_base) {
                return [ 'error' => __('Proxy base URL not configured', 'ar-for-wordpress') ];
            }
            
            // Use the passed AI credits token if provided, otherwise fall back to the stored one
            $token = $ai_credits_token ?: $this->api_key;
            if (!$token) {
                return [ 'error' => __('Proxy AI credits token not configured', 'ar-for-wordpress') ];
            }
            
            $last_error = __('Proxy endpoint not available', 'ar-for-wordpress');
            foreach ($this->proxy_endpoint_urls('jobs/' . rawurlencode($job_id)) as $url) {
                error_log('[AR AI] Fetching job via proxy endpoint: ' . $url);
                $response = wp_remote_get($url, [
                    'headers' => [ 'X-ARDISPLAY-AI-Token' => $token ],
                    'timeout' => 20,
                ]);
                if (is_wp_error($response)) {
                    $last_error = $response->get_error_message();
                    continue;
                }
                $code = wp_remote_retrieve_response_code($response);
                $body = wp_remote_retrieve_body($response);
                $data = json_decode($body, true);
                if ($code === 404 && is_array($data) && ($data['code'] ?? '') === 'rest_no_route') {
                    $last_error = __('Proxy endpoint not found (rest_no_route)', 'ar-for-wordpress');
                    error_log('[AR AI] Proxy get_job rest_no_route: ' . $url);
                    continue;
                }
                if ($code >= 400) {
                    $last_error = $data['message'] ?? ('HTTP ' . $code);
                    error_log('[AR AI] Proxy get_job HTTP ' . $code . ' body: ' . $body);
                    continue;
                }
                return $data ?: [];
            }
            return [ 'error' => $last_error ];
        }

        public function cancel_job(string $job_id, string $ai_credits_token = ''): array
        {
            $proxy_base = $this->base_url;
            if (!$proxy_base) {
                return [ 'error' => __('Proxy base URL not configured', 'ar-for-wordpress') ];
            }
            
            // Use the passed AI credits token if provided, otherwise fall back to the stored one
            $token = $ai_credits_token ?: $this->api_key;
            if (!$token) {
                return [ 'error' => __('Proxy AI credits token not configured', 'ar-for-wordpress') ];
            }
            
            $last_error = __('Proxy endpoint not available', 'ar-for-wordpress');
            foreach ($this->proxy_endpoint_urls('jobs/' . rawurlencode($job_id)) as $url) {
                error_log('[AR AI] Cancelling job via proxy endpoint: ' . $url);
                $response = wp_remote_request($url, [
                    'method' => 'DELETE',
                    'headers' => [ 'X-ARDISPLAY-AI-Token' => $token ],
                    'timeout' => 20,
                ]);
                if (is_wp_error($response)) {
                    $last_error = $response->get_error_message();
                    continue;
                }
                $code = wp_remote_retrieve_response_code($response);
                $body = wp_remote_retrieve_body($response);
                $data = json_decode($body, true);
                if ($code === 404 && is_array($data) && ($data['code'] ?? '') === 'rest_no_route') {
                    $last_error = __('Proxy endpoint not found (rest_no_route)', 'ar-for-wordpress');
                    error_log('[AR AI] Proxy cancel_job rest_no_route: ' . $url);
                    continue;
                }
                if ($code >= 400) {
                    $last_error = $data['message'] ?? ('HTTP ' . $code);
                    error_log('[AR AI] Proxy cancel_job HTTP ' . $code . ' body: ' . $body);
                    continue;
                }
                return $data ?: [];
            }
            return [ 'error' => $last_error ];
        }

        private function proxy_endpoint_urls(string $path): array
        {
            $base = rtrim($this->base_url, '/');
            $path = '/' . ltrim($path, '/');
            $namespaces = [
                'ardisplay-ai-proxy/v1',
                'ardisplay-ai/v1',
                'ardisplay_ai-proxy/v1',
                'ardisplay_ai_proxy/v1',
            ];

            $urls = [];
            foreach ($namespaces as $ns) {
                $urls[] = $base . '/wp-json/' . $ns . $path;
                $urls[] = $base . '/wp-json/' . $ns . $path . '/';
                $urls[] = $base . '/?rest_route=/' . $ns . $path;
                $urls[] = $base . '/?rest_route=/' . $ns . $path . '/';
                $urls[] = $base . '/index.php?rest_route=/' . $ns . $path;
                $urls[] = $base . '/index.php?rest_route=/' . $ns . $path . '/';
            }

            return array_values(array_unique($urls));
        }
    }
}


