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

class Dori_Chatbot_Bot_Creator
{
    public static function create_bot($user_id, $from_extraction = false)
    {
        $max_retries = 2;
        $retry_count = 0;
        $last_error = null;

        while ($retry_count < $max_retries) {
            try {
                $extracted_data = get_transient('dori-chatbot-extract-response-data');
                if ($extracted_data === false) {
                    $extracted_data = array();
                }

                if (empty($extracted_data)) {
                    if (!$from_extraction) {
                        self::extract_bot_data($user_id);
                        return;
                    } else {
                        throw new Exception('No extracted data found. Please run data extraction first.');
                    }
                }

                $shop_data = isset($extracted_data['shop']) ? $extracted_data['shop'] : array();

                $request_body = array(
                    'shop' => array_merge(array(
                        'currency' => 'IRT',
                        'language' => 'Persian',
                        'isRTL' => true,
                        'country' => 'iran',
                        'is_widget_enabled' => false,
                        'onboarding_completed' => false
                    ), $shop_data),
                    'user_id' => $user_id
                );

                if (isset($extracted_data['faqs']) && !empty($extracted_data['faqs'])) {
                    $request_body['shop']['faqs'] = $extracted_data['faqs'];
                }

                if (isset($extracted_data['platform'])) {
                    $request_body['shop']['platform'] = $extracted_data['platform'];
                }

                $api_url = Dori_Chatbot_API_Constants::get_server_base_url() . Dori_Chatbot_API_Constants::ENDPOINT_CREATE_BOT . '?auth_token=' . Dori_Chatbot_API_Constants::BOT_CREATION_AUTH_TOKEN;

                set_transient('dori-chatbot-bot-creation-status', 'pending', HOUR_IN_SECONDS);

                $response = Dori_Chatbot_API_Client::call_api_simple($api_url, $request_body);

                if (is_wp_error($response)) {
                    throw new Exception('API request failed: ' . $response->get_error_message());
                }

                $response_code = wp_remote_retrieve_response_code($response);
                $response_body = wp_remote_retrieve_body($response);
                $response_data = json_decode($response_body, true);

                if ($response_code === 200) {
                    set_transient('dori-chatbot-bot-creation-status', 'success', HOUR_IN_SECONDS);
                    set_transient('dori-chatbot-bot-creation-retries', 0, HOUR_IN_SECONDS);
                    return;
                } else {
                    throw new Exception('Server returned error code: ' . $response_code);
                }
            } catch (Exception $e) {
                $last_error = $e->getMessage();
                $retry_count++;

                if ($retry_count < $max_retries) {
                    sleep(2);
                } else {
                    set_transient('dori-chatbot-bot-creation-status', 'failed', HOUR_IN_SECONDS);
                    set_transient('dori-chatbot-bot-creation-error', $last_error, HOUR_IN_SECONDS);
                    set_transient('dori-chatbot-bot-creation-retries', 0, HOUR_IN_SECONDS);
                    return;
                }
            }
        }
    }

    public static function get_seller_health_check($user_id)
    {
        $api_url = Dori_Chatbot_API_Constants::get_server_base_url() . Dori_Chatbot_API_Constants::ENDPOINT_HEALTH_CHECK . "/" . $user_id;

        $response = Dori_Chatbot_API_Client::call_api_get($api_url);

        if (is_wp_error($response)) {
            throw new Exception('Health check failed: ' . esc_html($response->get_error_message()));
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);
            throw new Exception('Health check failed - Status code ' . esc_html($response_code) . ': ' . esc_html($response_body));
        }

        $response_body = wp_remote_retrieve_body($response);
        $response_data = json_decode($response_body, true);

        if (!$response_data) {
            throw new Exception('Invalid response from health check endpoint');
        }

        return $response_data;
    }

    public static function extract_bot_data($user_id)
    {
        try {
            $extract_api_url = Dori_Chatbot_API_Constants::get_crawler_base_url() . Dori_Chatbot_API_Constants::ENDPOINT_EXTRACT_BOT_DATA;

            $extract_data = array(
                'seller_id' => $user_id
            );

            $extract_response = Dori_Chatbot_API_Client::call_api_simple($extract_api_url, $extract_data);

            if (!is_wp_error($extract_response)) {
                $extract_response_code = wp_remote_retrieve_response_code($extract_response);
                if ($extract_response_code === 200) {
                    $extract_response_body = wp_remote_retrieve_body($extract_response);
                    $extract_response_data = json_decode($extract_response_body, true);

                    set_transient('dori-chatbot-extract-response-data', $extract_response_data, HOUR_IN_SECONDS);
                    set_transient('dori-chatbot-bot-creation-status', 'not-sent-yet', HOUR_IN_SECONDS);

                    self::create_bot($user_id, true);
                }
            }
        } catch (Exception $e) {
        }
    }
}
