# Fusion Accounting - Chart Template Post-Load Hook
# Configures tax periodicity and generates initial tax-closing reminders

from odoo import fields, models, _
from odoo.exceptions import ValidationError


class FusionChartTemplatePostLoad(models.AbstractModel):
    """Runs post-installation configuration after chart-of-accounts
    data is loaded: sets the tax periodicity journal, enables the
    totals-below-sections option, and schedules the first tax-closing
    reminder activity."""

    _inherit = 'account.chart.template'

    def _post_load_data(self, template_code, company, template_data):
        """Apply Fusion Accounting defaults after chart template data
        has been loaded for *company*."""
        super()._post_load_data(template_code, company, template_data)

        target_company = company or self.env.company

        # Locate the default miscellaneous journal
        misc_journal = self.env['account.journal'].search([
            *self.env['account.journal']._check_company_domain(target_company),
            ('type', '=', 'general'),
        ], limit=1)

        if not misc_journal:
            raise ValidationError(
                _("No miscellaneous journal could be found for the active company.")
            )

        target_company.update({
            'totals_below_sections': target_company.anglo_saxon_accounting,
            'account_tax_periodicity_journal_id': misc_journal,
            'account_tax_periodicity_reminder_day': 7,
        })
        misc_journal.show_on_dashboard = True

        # Determine the appropriate tax report (country-specific or generic)
        generic_report = self.env.ref('account.generic_tax_report')
        country_report = self.env['account.report'].search([
            ('availability_condition', '=', 'country'),
            ('country_id', '=', target_company.country_id.id),
            ('root_report_id', '=', generic_report.id),
        ], limit=1)
        effective_report = country_report or generic_report

        # Schedule the initial tax-closing reminder activity
        _start, period_end = target_company._get_tax_closing_period_boundaries(
            fields.Date.today(), effective_report,
        )
        existing_activity = target_company._get_tax_closing_reminder_activity(
            effective_report.id, period_end,
        )
        if not existing_activity:
            target_company._generate_tax_closing_reminder_activity(
                effective_report, period_end,
            )
