# -*- coding: utf-8 -*-
# Copyright (c) 2026, Jey 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 TaxFreeIndicator(Document):
    def autoname(self):
        """
        Auto-generate document name from indicator_name.
        Truncates to 140 chars and appends -N on collision.
        """
        if not self.indicator_name:
            return

        name = str(self.indicator_name)

        if len(name) > 140:
            name = name[:137] + "..."

        counter = 1
        original_name = name
        while frappe.db.exists("Tax Free Indicator", name):
            suffix = f"-{counter}"
            max_length = 140 - len(suffix)
            name = original_name[:max_length] + suffix
            counter += 1

        self.name = name

    def validate(self):
        self.auto_calculate_validity_fields()
        self.validate_date_range()

    def auto_calculate_validity_fields(self):
        if self.date_from and self.duration and not self.date_to:
            self.date_to = add_years(getdate(self.date_from), self.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):
        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"),
                )
