import logging

from odoo import models

_logger = logging.getLogger(__name__)


class Model(models.AbstractModel):
    _inherit = "base"

    def _get_record_modules(self):
        """Возвращает список модулей, в которых определены текущие записи."""
        xml_items = (
            self.env["ir.model.data"]
            .sudo()
            .search(
                [
                    ("res_id", "in", self.ids),
                    ("model", "=", self._name),
                ]
            )
        )
        return list({item.module for item in xml_items if item.module})

    def update_field_translations(self, field_name, translations):
        """OVERRIDE
        Update the values of a translated field.

        :param str field_name: field name
        :param dict translations: if the field has ``translate=True``, it should be a dictionary
            like ``{lang: new_value}``; if ``translate`` is a callable, it should be like
            ``{lang: {old_term: new_term}}``

        Odoo 19: calls super().update_field_translations() to preserve original behaviour,
        which internally dispatches to _update_field_translations.
        """
        modules = self._get_record_modules()
        if not modules:
            _logger.warning(
                "Не удалось определить модуль для модели %s (ids: %s)",
                self._name,
                self.ids,
            )
            return super().update_field_translations(field_name, translations)

        original_value = self.with_context(lang=None)[field_name]
        if not original_value:
            _logger.warning(
                "Оригинальное значение поля '%s' пустое для модели %s (ids: %s)",
                field_name,
                self._name,
                self.ids,
            )
            return super().update_field_translations(field_name, translations)

        # Обновляем перевод для каждой локали
        for lang, translated_value in translations.items():
            if not translated_value:
                _logger.info("Пропущен пустой перевод для языка: %s", lang)
                continue

            lang_record = (
                self.env["res.lang"].sudo().search([("code", "=", lang)], limit=1)
            )
            iso_code = lang_record.iso_code or lang.split("_")[0]
            source_value = original_value
            translated_value_string = translated_value
            if isinstance(translated_value, dict):
                source_value = translated_value.get("source", original_value)
                translated_value_string = list(translated_value.values())[0]

            self.env[
                "translation.helper.wizard"
            ].sudo().update_term_translation_in_module(
                modules[0], source_value, translated_value_string, iso_code
            )
            _logger.info(
                "Обновлен перевод для '%s' (%s -> %s) [lang: %s]",
                field_name,
                original_value,
                translated_value,
                lang,
            )

        # Odoo 19: use super() instead of calling _update_field_translations directly,
        # as the internal method signature may have changed between versions.
        return super().update_field_translations(field_name, translations)
