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

if (! function_exists('reeid_build_translated_slug_pack')) {
    function reeid_build_translated_slug_pack(
        $post,
        string $source_lang,
        string $target_lang,
        string $editor,
        string $system_prompt
    ): string {
        $title_src = $post ? $post->post_title : 'translation';
        $slug = '';

                $title_tr = reeid_translate_html_with_openai(
            $title_src,
            $source_lang,
            $target_lang,
            $editor,
            'neutral',
            $system_prompt
        );

        if (is_wp_error($title_tr) || empty($title_tr)) {
            $title_tr = $title_src;
        }

        if (function_exists('reeid_sanitize_native_slug')) {
            $slug = reeid_sanitize_native_slug(
                mb_substr(wp_strip_all_tags((string) $title_tr), 0, 60)
            );
        } else {
            $slug = sanitize_title(
                mb_substr(wp_strip_all_tags((string) $title_tr), 0, 60)
            );
        }

        return (string) $slug;
    }
}

if (! function_exists('reeid_normalize_translation_pack')) {
    function reeid_normalize_translation_pack(array $pack): array
    {
        $ok      = !empty($pack['success']) || !empty($pack['ok']);
        $content = isset($pack['content']) && is_string($pack['content']) ? $pack['content'] : '';
        $title   = isset($pack['title']) && is_string($pack['title']) && $pack['title'] !== ''
            ? $pack['title']
            : $content;
        $excerpt = isset($pack['excerpt']) && is_string($pack['excerpt']) ? $pack['excerpt'] : '';
        $slug    = isset($pack['slug']) && is_string($pack['slug']) ? $pack['slug'] : '';
        $error   = isset($pack['error']) && is_string($pack['error']) ? $pack['error'] : '';

        return [
            'success' => $ok,
            'ok'      => $ok,
            'title'   => $title,
            'content' => $content,
            'excerpt' => $excerpt,
            'slug'    => $slug,
            'error'   => $error,
            'data'    => (isset($pack['data']) && is_array($pack['data'])) ? $pack['data'] : [],
        ];
    }
}