<?php
defined('ABSPATH') || exit;

if (! function_exists('reeid_translate_product_attributes')) {
    /**
     * Translate product attributes from $src_product and attach them to $dst_product.
     *
     * @param WC_Product $src_product
     * @param WC_Product $dst_product
     * @param string     $src_lang
     * @param string     $dst_lang
     * @param string     $tone
     */
    function reeid_translate_product_attributes($src_product, $dst_product, $src_lang, $dst_lang, $tone = 'neutral')
    {
        if (! class_exists('WC_Product')) {
            return;
        }

        if (! $src_product || ! $dst_product) {
            return;
        }

        $src_attrs = $src_product->get_attributes();
        if (empty($src_attrs) || ! is_array($src_attrs)) {
            return;
        }

        $batch_map  = [];
        $attrs_meta = [];

        foreach ($src_attrs as $attr_key => $attr) {
            if (is_object($attr) && method_exists($attr, 'get_options')) {
                $label     = (string) $attr->get_name();
                $options   = (array) $attr->get_options();
                $visible   = (bool) $attr->get_visible();
                $variation = (bool) $attr->get_variation();
                $is_tax    = method_exists($attr, 'is_taxonomy') ? (bool) $attr->is_taxonomy() : false;
                $tax_name  = method_exists($attr, 'get_name') ? $attr->get_name() : '';
            } else {
                $label     = isset($attr['name']) ? (string) $attr['name'] : (string) $attr_key;
                $options   = isset($attr['options']) ? (array) $attr['options'] : (isset($attr['value']) ? array_map('trim', explode('|', $attr['value'])) : []);
                $visible   = ! empty($attr['visible']);
                $variation = ! empty($attr['variation']);
                $is_tax    = ! empty($attr['is_taxonomy']);
                $tax_name  = isset($attr['taxonomy']) ? $attr['taxonomy'] : '';
            }

            $label_key = "attr:label:{$attr_key}";
            $batch_map[$label_key] = $label;

            $opt_keys = [];
            foreach ($options as $oi => $opt) {
                $opt_key   = "attr:opt:{$attr_key}:{$oi}";
                $opt_value = (string) $opt;

                if ($is_tax && ! empty($tax_name)) {
                    $resolved = null;
                    if (is_numeric($opt_value)) {
                        $t = get_term((int) $opt_value, $tax_name);
                        if ($t && ! is_wp_error($t)) {
                            $resolved = $t->name;
                        }
                    }
                    if ($resolved === null) {
                        $t = get_term_by('slug', $opt_value, $tax_name);
                        if ($t && ! is_wp_error($t)) {
                            $resolved = $t->name;
                        }
                    }
                    if ($resolved !== null) {
                        $opt_value = (string) $resolved;
                    }
                }

                $batch_map[$opt_key] = $opt_value;
                $opt_keys[] = $opt_key;
            }

            $attrs_meta[$attr_key] = [
                'label_key' => $label_key,
                'opt_keys' => $opt_keys,
                'visible' => $visible,
                'variation' => $variation,
            ];
        }

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

        $json_in = wp_json_encode($batch_map, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        $prompt = "Task: Translate the JSON VALUES to {$dst_lang}. Keep keys EXACTLY unchanged.\n"
            . "- Preserve HTML tags/attributes if values contain HTML. Do NOT alter placeholders like %s, numbers, or punctuation.\n"
            . "- Return STRICT JSON object only.";

        $api_args = ['response_format' => ['type' => 'json_object']];

        $out = reeid_translate_html_with_openai($prompt . "\n" . $json_in, $src_lang, $dst_lang, 'classic', $tone, $api_args);

        $translated_map = [];
        if (is_string($out)) {
            if (preg_match('/\{.*\}/s', $out, $m)) {
                $clean = $m[0];
            } else {
                $clean = $out;
            }
            if (function_exists('reeid_json_sanitize_controls_v2')) {
                $clean = reeid_json_sanitize_controls_v2($clean, []);
            }
            if (function_exists('reeid_safe_json_decode')) {
                $decoded = reeid_safe_json_decode($clean);
            } else {
                $decoded = json_decode($clean, true);
            }
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $translated_map = $decoded;
            }
        }

        if (empty($translated_map)) {
            foreach ($batch_map as $k => $v) {
                $tr = reeid_translate_html_with_openai($v, $src_lang, $dst_lang, 'classic', $tone);
                $translated_map[$k] = (is_wp_error($tr) || empty($tr)) ? $v : (string) $tr;
            }
        }

        $new_attrs = [];

        foreach ($attrs_meta as $attr_key => $meta) {
            $label_tr = isset($translated_map[$meta['label_key']]) ? (string) $translated_map[$meta['label_key']] : '';

            $options_tr = [];
            foreach ($meta['opt_keys'] as $ok) {
                $val = isset($translated_map[$ok]) ? (string) $translated_map[$ok] : '';
                if ($val !== '') {
                    $options_tr[] = $val;
                }
            }

            if (class_exists('WC_Product_Attribute')) {
                $new_attr = new WC_Product_Attribute();
                if (method_exists($new_attr, 'set_id')) {
                    $new_attr->set_id(0);
                }
                if (method_exists($new_attr, 'set_name')) {
                    $new_attr->set_name($label_tr !== '' ? $label_tr : $attr_key);
                }
                if (method_exists($new_attr, 'set_options')) {
                    $new_attr->set_options($options_tr);
                } else {
                    $new_attr->options = $options_tr;
                }
                if (method_exists($new_attr, 'set_visible')) {
                    $new_attr->set_visible($meta['visible']);
                } else {
                    $new_attr->visible = $meta['visible'];
                }
                if (method_exists($new_attr, 'set_variation')) {
                    $new_attr->set_variation($meta['variation']);
                } else {
                    $new_attr->variation = $meta['variation'];
                }
                if (method_exists($new_attr, 'set_taxonomy')) {
                    $new_attr->set_taxonomy(false);
                }

                $new_attrs[] = $new_attr;
            } else {
                $key = sanitize_title($label_tr !== '' ? $label_tr : $attr_key);
                $new_attrs[$key] = [
                    'name' => ($label_tr !== '' ? $label_tr : $attr_key),
                    'value' => implode(' | ', $options_tr),
                    'is_visible' => $meta['visible'] ? 1 : 0,
                    'is_variation' => $meta['variation'] ? 1 : 0,
                    'is_taxonomy' => 0,
                ];
            }
        }

        try {
            if (! empty($new_attrs)) {
                if (method_exists($dst_product, 'set_attributes')) {
                    $dst_product->set_attributes($new_attrs);
                } else {
                    $post_id = method_exists($dst_product, 'get_id') ? $dst_product->get_id() : 0;
                    if ($post_id) {
                        update_post_meta($post_id, '_product_attributes', $new_attrs);
                    }
                }
                if (method_exists($dst_product, 'save')) {
                    $dst_product->save();
                }
            }
        } catch (Throwable $e) {
        }
    }
}