from . import models
from . import wizard
from . import controllers

from odoo import Command

import logging

_logger = logging.getLogger(__name__)


def _fusion_accounting_post_init(env):
    """Post-installation hook for Fusion Accounting module.

    Sets up SEPA-related modules for applicable countries,
    configures chart of accounts data, and initiates onboarding.
    """
    _install_regional_modules(env)
    _load_chart_template_data(env)
    _configure_tax_journals(env)


def _install_regional_modules(env):
    """Install region-specific modules based on company country."""
    country_code = env.company.country_id.code
    if not country_code:
        return

    modules_to_install = []

    sepa_zone = env.ref('base.sepa_zone', raise_if_not_found=False)
    if sepa_zone:
        sepa_countries = sepa_zone.mapped('country_ids.code')
        if country_code in sepa_countries:
            modules_to_install.extend([
                'account_iso20022',
                'account_bank_statement_import_camt',
            ])

    if country_code in ('AU', 'CA', 'US'):
        modules_to_install.append('account_reports_cash_basis')

    pending = env['ir.module.module'].search([
        ('name', 'in', modules_to_install),
        ('state', '=', 'uninstalled'),
    ])
    if pending:
        pending.sudo().button_install()


def _load_chart_template_data(env):
    """Load Fusion Accounting company data for existing chart templates."""
    companies = env['res.company'].search(
        [('chart_template', '!=', False)],
        order='parent_path',
    )
    for company in companies:
        chart = env['account.chart.template'].with_company(company)
        chart._load_data({
            'res.company': chart._get_fusion_accounting_res_company(
                company.chart_template
            ),
        })


def _configure_tax_journals(env):
    """Set up default tax periodicity journal and enable onboarding."""
    for company in env['res.company'].search([]):
        misc_journal = company._get_default_misc_journal()
        company.account_tax_periodicity_journal_id = misc_journal
        if misc_journal:
            misc_journal.show_on_dashboard = True
        company._initiate_account_onboardings()


def uninstall_hook(env):
    """Clean up accounting groups and menus when uninstalling."""
    _reset_account_groups(env)
    _restore_invoicing_menus(env)


def _reset_account_groups(env):
    """Reset account security groups to their pre-install state."""
    hidden_category = env.ref('base.module_category_hidden')

    basic_group = env.ref('account.group_account_basic', raise_if_not_found=False)
    manager_group = env.ref('account.group_account_manager', raise_if_not_found=False)

    if basic_group and manager_group:
        basic_group.write({
            'users': [Command.clear()],
            'category_id': hidden_category.id,
        })
        manager_group.write({
            'implied_ids': [Command.unlink(basic_group.id)],
        })

    try:
        user_group = env.ref('account.group_account_user')
        user_group.write({
            'name': 'Show Full Accounting Features',
            'implied_ids': [(3, env.ref('account.group_account_invoice').id)],
            'category_id': hidden_category.id,
        })
        readonly_group = env.ref('account.group_account_readonly')
        readonly_group.write({
            'name': 'Show Full Accounting Features - Readonly',
            'category_id': hidden_category.id,
        })
    except ValueError as exc:
        _logger.warning('Could not reset account user/readonly groups: %s', exc)

    try:
        manager = env.ref('account.group_account_manager')
        invoice_group = env.ref('account.group_account_invoice')
        readonly = env.ref('account.group_account_readonly')
        user = env.ref('account.group_account_user')
        manager.write({
            'name': 'Billing Manager',
            'implied_ids': [
                (4, invoice_group.id),
                (3, readonly.id),
                (3, user.id),
            ],
        })
    except ValueError as exc:
        _logger.warning('Could not reset account manager group: %s', exc)

    # Remove advanced accounting feature visibility
    user_ref = env.ref('account.group_account_user', raise_if_not_found=False)
    readonly_ref = env.ref('account.group_account_readonly', raise_if_not_found=False)
    if user_ref:
        user_ref.write({'users': [(5, False, False)]})
    if readonly_ref:
        readonly_ref.write({'users': [(5, False, False)]})


def _restore_invoicing_menus(env):
    """Move accounting menus back under the Invoicing parent menu."""
    invoicing_menu = env.ref('account.menu_finance', raise_if_not_found=False)
    if not invoicing_menu:
        return

    menu_refs = [
        'account.menu_finance_receivables',
        'account.menu_finance_payables',
        'account.menu_finance_entries',
        'account.menu_finance_reports',
        'account.menu_finance_configuration',
        'account.menu_board_journal_1',
    ]
    for ref in menu_refs:
        try:
            env.ref(ref).parent_id = invoicing_menu
        except ValueError as exc:
            _logger.warning('Could not restore menu %s: %s', ref, exc)
