# -*- coding: utf-8 -*-
# Copyright (c) 2025, Your Company and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.utils import getdate, add_years

class TaxArticle(Document):
    def autoname(self):
        """
        Auto-generate document name from article_name
        """
        if not self.article_name:
            return
            
        name = str(self.article_name)
        
        # Обрезаем, если длиннее 140 символов
        if len(name) > 140:
            name = name[:137] + "..."
        
        # Проверяем уникальность
        counter = 1
        original_name = name
        while frappe.db.exists("Tax Article", name):
            suffix = f"-{counter}"
            max_length = 140 - len(suffix)
            name = original_name[:max_length] + suffix
            counter += 1
        
        self.name = name
    
    def validate(self):
        """
        Validate Tax Article fields and auto-calculate missing values
        """
        # Автоматический расчет полей
        self.auto_calculate_validity_fields()
        
        # Валидация дат
        self.validate_date_range()
    
    def auto_calculate_validity_fields(self):
        """
        Auto-calculate missing validity fields based on available data
        """
        # Если есть date_from и duration, но нет date_to
        if self.date_from and self.duration and not self.date_to:
            self.date_to = add_years(getdate(self.date_from), self.duration)
        
        # Если есть date_from и date_to, но нет duration
        elif self.date_from and self.date_to and not self.duration:
            from_date = getdate(self.date_from)
            to_date = getdate(self.date_to)
            
            # Рассчитываем разницу в годах
            years = (to_date - from_date).days / 365.25
            self.duration = round(years)
    
    def validate_date_range(self):
        """
        Validate that date_to is not earlier than date_from
        """
        if self.date_from and self.date_to:
            from_date = getdate(self.date_from)
            to_date = getdate(self.date_to)
            
            if to_date < from_date:
                frappe.throw(
                    frappe._("Date To cannot be earlier than Date From"),
                    title=frappe._("Invalid Date Range")
                )