# Fusion Accounting - Currency Extensions
# Incorporates manual fiscal year boundaries into the currency rate table

from odoo import models


class FusionResCurrency(models.Model):
    """Extends the currency rate table generation to honour manually
    defined fiscal years when computing period boundaries."""

    _inherit = 'res.currency'

    def _get_currency_table_fiscal_year_bounds(self, main_company):
        """Merge automatically computed fiscal-year boundaries with
        any manually defined ``account.fiscal.year`` records, ensuring
        that manual periods take precedence within their date ranges."""
        auto_bounds = super()._get_currency_table_fiscal_year_bounds(main_company)

        manual_fy_records = self.env['account.fiscal.year'].search(
            self.env['account.fiscal.year']._check_company_domain(main_company),
            order='date_from ASC',
        )
        manual_periods = manual_fy_records.mapped(lambda fy: (fy.date_from, fy.date_to))

        merged = []
        for auto_start, auto_end in auto_bounds:
            # Pop manual periods that fall within this automatic boundary
            while (
                manual_periods
                and (
                    not auto_end
                    or (auto_start and auto_start <= manual_periods[0][0] and auto_end >= manual_periods[0][0])
                    or auto_end >= manual_periods[0][1]
                )
            ):
                merged.append(manual_periods.pop(0))

            if not merged or merged[-1][1] < auto_start:
                merged.append((auto_start, auto_end))

        return merged
