from odoo import api, fields, models


class DirectiveOrigin(models.Model):
    _name = "directive.origin"
    _description = "Directive Origin"
    _rec_name = "display_name"
    _order = "id desc"

    res_model = fields.Char(string="Техническое имя модели", required=True, index=True)
    res_id = fields.Integer(string="ID записи", required=True, index=True)

    res_ref = fields.Reference(
        selection="_get_reference_models",
        string="Ссылка на запись",
        compute="_compute_res_ref",
        inverse="_inverse_res_ref",
        store=True,
        readonly=False,
    )

    directive_ids = fields.One2many(
        "directive.directive",
        "origin_id",
        string="Директивы",
        readonly=True,
    )

    display_name = fields.Char(
        string="Источник (display_name)",
        compute="_compute_display_name",
        store=True,
    )

    _sql_constraints = [
        ("directive_origin_uniq", "unique(res_model, res_id)", "Origin must be unique per (model, id)."),
    ]

    @api.model
    def _get_reference_models(self):
        models = self.env["ir.model"].sudo().search([])
        return [(m.model, m.name) for m in models if m.model]

    @api.depends("res_model", "res_id")
    def _compute_res_ref(self):
        for rec in self:
            if rec.res_model and rec.res_id:
                rec.res_ref = f"{rec.res_model},{rec.res_id}"
            else:
                rec.res_ref = False

    def _inverse_res_ref(self):
        for rec in self:
            if not rec.res_ref:
                rec.res_model = False
                rec.res_id = 0
                continue
            try:
                model, rid = rec.res_ref.split(",")
                rec.res_model = model
                rec.res_id = int(rid)
            except Exception:
                rec.res_model = False
                rec.res_id = 0

    @api.depends("res_ref")
    def _compute_display_name(self):
        for rec in self:
            if rec.res_ref:
                try:
                    rec.display_name = f"{rec.res_model},{rec.res_id}"
                except Exception:
                    rec.display_name = f"{rec.res_model},{rec.res_id}"
            else:
                rec.display_name = f"{rec.res_model},{rec.res_id}"
