<?php

use Datalumo\PhpSdk\Datalumo as DatalumoSdk;

if (! function_exists('datalumo_sdk')) {
    /**
     * Create a Datalumo SDK instance.
     *
     * @param string|null $apiKey  Override the saved API key.
     */
    function datalumo_sdk(?string $apiKey = null): DatalumoSdk
    {
        $key = $apiKey ?? datalumo_get_api_key();
        $baseUrl = datalumo_get_base_url();

        return new DatalumoSdk($key, $baseUrl);
    }
}

if (! function_exists('datalumo_get_api_url')) {
    function datalumo_get_api_url(): string
    {
        if (defined('DATALUMO_API_URL')) {
            return rtrim(DATALUMO_API_URL, '/');
        }

        return 'https://datalumo.app/api/v1';
    }
}

if (! function_exists('datalumo_get_api_key')) {
    function datalumo_get_api_key(): string
    {
        return get_option('datalumo_api_key', '');
    }
}

if (! function_exists('datalumo_get_base_url')) {
    function datalumo_get_base_url(): string
    {
        $apiUrl = datalumo_get_api_url();

        return rtrim(preg_replace('#/api(/v\d+)?$#', '', $apiUrl), '/');
    }
}

if (! function_exists('datalumo_get_cdn_url')) {
    function datalumo_get_cdn_url(): string
    {
        if(defined('DATALUMO_CDN_URL')) {
            return rtrim(DATALUMO_CDN_URL, '/');
        }

        return 'https://cdn.datalumo.app';
    }
}

if (! function_exists('datalumo_is_configured')) {
    function datalumo_is_configured(): bool
    {
        return ! empty(datalumo_get_api_key());
    }
}

if (! function_exists('datalumo_get_content_syncs')) {
    /**
     * @return array<int, array{id: string, collection_id: string, post_types: string[]}>
     */
    function datalumo_get_content_syncs(): array
    {
        return get_option('datalumo_content_syncs', []);
    }
}

if (! function_exists('datalumo_get_content_sync')) {
    function datalumo_get_content_sync(string $syncId): ?array
    {
        foreach (datalumo_get_content_syncs() as $sync) {
            if (($sync['id'] ?? '') === $syncId) {
                return $sync;
            }
        }

        return null;
    }
}

if (! function_exists('datalumo_get_syncs_for_post_type')) {
    /**
     * @return array<int, array{id: string, collection_id: string, post_types: string[]}>
     */
    function datalumo_get_syncs_for_post_type(string $postType): array
    {
        return array_values(array_filter(
            datalumo_get_content_syncs(),
            fn (array $sync) => in_array($postType, $sync['post_types'] ?? [], true)
        ));
    }
}

if (! function_exists('datalumo_get_sync_states')) {
    /**
     * Aggregate sync states from individual options.
     *
     * Each sync's state is now stored in its own option
     * (datalumo_sync_state_{syncId}) to avoid race conditions
     * when concurrent batches update the processed counter.
     */
    function datalumo_get_sync_states(): array
    {
        $syncs = datalumo_get_content_syncs();
        $states = [];

        foreach ($syncs as $sync) {
            $syncId = $sync['id'] ?? '';

            if ($syncId === '') {
                continue;
            }

            $state = get_option('datalumo_sync_state_' . $syncId, []);

            if (is_array($state) && ! empty($state)) {
                $states[$syncId] = $state;
            }
        }

        // Also check the legacy shared option for backward compat.
        $legacy = get_option('datalumo_sync_states', []);

        if (is_array($legacy)) {
            foreach ($legacy as $id => $legacyState) {
                if (! isset($states[$id]) && is_array($legacyState)) {
                    $states[$id] = $legacyState;
                }
            }
        }

        return $states;
    }
}

if (! function_exists('datalumo_get_sync_state')) {
    function datalumo_get_sync_state(string $syncId): array
    {
        $state = get_option('datalumo_sync_state_' . $syncId, []);

        if (is_array($state) && ! empty($state)) {
            return $state;
        }

        // Fallback to legacy shared option.
        $states = get_option('datalumo_sync_states', []);

        if (is_array($states) && isset($states[$syncId])) {
            return $states[$syncId];
        }

        return [];
    }
}

if (! function_exists('datalumo_is_chatbot_enabled')) {
    function datalumo_is_chatbot_enabled(): bool
    {
        return (bool) get_option('datalumo_chatbot_enabled', false);
    }
}

if (! function_exists('datalumo_is_search_box_enabled')) {
    function datalumo_is_search_box_enabled(): bool
    {
        return (bool) get_option('datalumo_search_box_enabled', false);
    }
}

if (! function_exists('datalumo_get_chatbot_integration_id')) {
    function datalumo_get_chatbot_integration_id(): string
    {
        return get_option('datalumo_chatbot_integration_id', '');
    }
}

if (! function_exists('datalumo_get_chatbot_mode')) {
    function datalumo_get_chatbot_mode(): string
    {
        $mode = get_option('datalumo_chatbot_mode', 'popup');

        return in_array($mode, ['popup', 'sidebar'], true) ? $mode : 'popup';
    }
}

if (! function_exists('datalumo_get_chatbot_popup_position')) {
    function datalumo_get_chatbot_popup_position(): string
    {
        $pos = get_option('datalumo_chatbot_popup_position', 'bottom-right');

        return in_array($pos, ['bottom-right', 'bottom-left'], true) ? $pos : 'bottom-right';
    }
}

if (! function_exists('datalumo_get_chatbot_sidebar_side')) {
    function datalumo_get_chatbot_sidebar_side(): string
    {
        $side = get_option('datalumo_chatbot_sidebar_side', 'right');

        return in_array($side, ['right', 'left'], true) ? $side : 'right';
    }
}

if (! function_exists('datalumo_chatbot_sidebar_pushes')) {
    function datalumo_chatbot_sidebar_pushes(): bool
    {
        return (bool) get_option('datalumo_chatbot_sidebar_push', false);
    }
}

if (! function_exists('datalumo_chatbot_shows_avatar')) {
    function datalumo_chatbot_shows_avatar(): bool
    {
        return (bool) get_option('datalumo_chatbot_show_avatar', true);
    }
}

if (! function_exists('datalumo_get_search_box_integration_id')) {
    function datalumo_get_search_box_integration_id(): string
    {
        return get_option('datalumo_search_box_integration_id', '');
    }
}

if (! function_exists('datalumo_is_search_enhanced')) {
    function datalumo_is_search_enhanced(): bool
    {
        return (bool) get_option('datalumo_search_enhanced', false);
    }
}

if (! function_exists('datalumo_get_search_post_types')) {
    /**
     * @return string[] Post types that should use Datalumo search. Empty means all.
     */
    function datalumo_get_search_post_types(): array
    {
        return get_option('datalumo_search_post_types', []);
    }
}

if (! function_exists('datalumo_get_search_integration_id')) {
    function datalumo_get_search_integration_id(): string
    {
        return get_option('datalumo_search_integration_id', '');
    }
}

if (! function_exists('datalumo_is_search_summary_enabled')) {
    function datalumo_is_search_summary_enabled(): bool
    {
        return (bool) get_option('datalumo_search_summary_enabled', false);
    }
}

if (! function_exists('datalumo_get_search_summary_selector')) {
    function datalumo_get_search_summary_selector(): string
    {
        return get_option('datalumo_search_summary_selector', '');
    }
}

if (! function_exists('datalumo_enqueue_click_tracking')) {
    /**
     * Enqueue click tracking for Datalumo search results.
     *
     * @param string|null $integrationId Optional integration ID. Defaults to the configured search integration.
     * @param string      $container     CSS selector for the container holding result links.
     */
    function datalumo_enqueue_click_tracking(?string $integrationId = null, string $container = '.wp-block-query, main, #content, .site-content'): void
    {
        if (! datalumo_is_configured()) {
            return;
        }

        $integrationId = $integrationId ?: datalumo_get_search_integration_id();

        if (empty($integrationId)) {
            return;
        }

        $baseUrl = datalumo_get_base_url();

        wp_enqueue_script(
            'datalumo-sdk',
            $baseUrl . '/embed/datalumo.js',
            [],
            null,
            ['strategy' => 'defer', 'in_footer' => true]
        );

        wp_add_inline_script('datalumo-sdk', sprintf(
            'document.addEventListener("DOMContentLoaded",function(){Datalumo.trackClicks("%s",{container:"%s",baseUrl:"%s"})});',
            esc_js($integrationId),
            esc_js($container),
            esc_url($baseUrl)
        ));
    }
}

if (! function_exists('datalumo_enqueue_summary')) {
    /**
     * Enqueue the AI summary assets for use on any page.
     *
     * @param string      $query           The search query to summarise.
     * @param array       $options         Optional settings:
     *                                     - integration_id: string — Override the default integration.
     *                                     - locale: string — Override the site locale (e.g. 'en', 'nl').
     *                                     - selector: string — CSS selector for summary placement.
     *                                     - position: string — 'prepend' or 'append' (default: 'prepend').
     *                                     - click_tracking: bool — Enable click tracking (default: true).
     *                                     - click_container: string — CSS selector for click tracking container.
     */
    function datalumo_enqueue_summary(string $query, array $options = []): void
    {
        if (! datalumo_is_configured() || empty($query)) {
            return;
        }

        wp_enqueue_style('datalumo-search-summary', plugins_url('resources/css/search-summary.css', DATALUMO_FILE), [], DATALUMO_VERSION);
        wp_enqueue_script('datalumo-search-summary', plugins_url('resources/js/search-summary.js', DATALUMO_FILE), [], DATALUMO_VERSION, true);

        $data = [
            'ajaxUrl'          => admin_url('admin-ajax.php'),
            'nonce'            => wp_create_nonce('datalumo_summarise'),
            'query'            => $query,
            'loadingText'      => __('Generating AI summary...', 'datalumo'),
            'headingText'      => __('AI Summary', 'datalumo'),
            'showMoreText'     => __('Show more', 'datalumo'),
            'showLessText'     => __('Show less', 'datalumo'),
            'summarySelector'  => $options['selector'] ?? '',
            'summaryPosition'  => $options['position'] ?? 'prepend',
        ];

        if (! empty($options['integration_id'])) {
            $data['integrationId'] = $options['integration_id'];
        }

        if (! empty($options['locale'])) {
            $data['locale'] = $options['locale'];
        }

        wp_localize_script('datalumo-search-summary', 'datalumoSearch', $data);

        // Enqueue click tracking
        if (($options['click_tracking'] ?? true) !== false) {
            datalumo_enqueue_click_tracking(
                $options['integration_id'] ?? null,
                $options['click_container'] ?? '.wp-block-query, main, #content, .site-content'
            );
        }
    }
}

if (! function_exists('datalumo_get_search_summary_position')) {
    function datalumo_get_search_summary_position(): string
    {
        $position = get_option('datalumo_search_summary_position', 'prepend');

        return in_array($position, ['prepend', 'append'], true) ? $position : 'prepend';
    }
}
