import frappe
import json
import re
import difflib
from frappe.utils import now, cstr, cint, flt, get_datetime
from frappe.model.document import Document

class ETaxesSettings(Document):
    def validate(self):
        # Проверка на единственную активную настройку
        if self.is_active:
            active_settings = frappe.get_all('E-Taxes Settings',
                                            filters={'is_active': 1, 'name': ['!=', self.name]})
            for setting in active_settings:
                frappe.db.set_value('E-Taxes Settings', setting.name, 'is_active', 0)

        # Проверка уникальности VAT Account Mappings
        self.validate_vat_account_mappings()

    def validate_vat_account_mappings(self):
        """
        Проверка уникальности комбинаций operation_type + expense_income + classification_code
        в таблице VAT Account Mappings
        """
        if not self.vat_account_mappings:
            return

        seen_combinations = set()

        for idx, mapping in enumerate(self.vat_account_mappings, start=1):
            # Нормализуем classification_code (None и пустая строка считаются одинаковыми)
            operation_type = mapping.operation_type
            expense_income = mapping.expense_income
            classification_code = mapping.classification_code or None

            # Создаем ключ для проверки уникальности (operation_type + expense_income + classification_code)
            combination_key = (operation_type, expense_income, classification_code)

            if combination_key in seen_combinations:
                # Формируем понятное сообщение об ошибке
                if classification_code:
                    frappe.throw(
                        f'Row #{idx}: Duplicate mapping found. '
                        f'Operation Type "{operation_type}", Expense/Income "{expense_income}", '
                        f'Classification Code "{classification_code}" '
                        f'already exists in this settings. Each combination must be unique.'
                    )
                else:
                    frappe.throw(
                        f'Row #{idx}: Duplicate mapping found. '
                        f'Operation Type "{operation_type}", Expense/Income "{expense_income}" '
                        f'with empty Classification Code '
                        f'already exists in this settings. Each combination must be unique.'
                    )

            seen_combinations.add(combination_key)