# Copyright 2026 Criptomart
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo import api, models


class ProjectTask(models.Model):
    _inherit = "project.task"

    @api.depends("project_id.analytic_account_id")
    def _compute_analytic_account_id(self):
        super()._compute_analytic_account_id()
        for task in self:
            expected = (
                task.project_id.analytic_account_id if task.project_id else False
            )
            if task.analytic_account_id != expected:
                task.analytic_account_id = expected

    def write(self, vals):
        if "project_id" in vals and "analytic_account_id" not in vals:
            # Project changed: force the correct account from the new project
            new_project = self.env["project.project"].browse(vals["project_id"])
            vals["analytic_account_id"] = (
                new_project.analytic_account_id.id if new_project else False
            )
        elif "analytic_account_id" in vals and "project_id" not in vals:
            # Validate provided account against the current project
            for task in self:
                expected = (
                    task.project_id.analytic_account_id.id if task.project_id else False
                )
                if vals["analytic_account_id"] != expected:
                    vals["analytic_account_id"] = expected
                    break
        elif "project_id" in vals and "analytic_account_id" in vals:
            # Both changed: force account from the new project
            new_project = self.env["project.project"].browse(vals["project_id"])
            vals["analytic_account_id"] = (
                new_project.analytic_account_id.id if new_project else False
            )
        return super().write(vals)
