# -*- coding: utf-8 -*-
"""STEP 13 — Miami-Dade auto-seed (11th Circuit Administrative Order 14-13).

When a Miami-Dade family matter is opened, certain obligations attach automatically:
  * a Status Quo Order (dissolution matters);
  * a mandatory Parenting Course (matters involving minor children);
  * mandatory Mediation before the final hearing.

And a COURSE-BEFORE-JUDGMENT GUARD: a matter with minor children cannot be set for
the final hearing (toward judgment) while the mandatory parenting course is still
pending.

VERIFY current rule — local administrative orders change; confirm AO 14-13's current
requirements and which case types they attach to before relying in production.
"""

from odoo import api, fields, models, _
from odoo.exceptions import UserError

_DISSOLUTION_TYPES = {"dissolution_no_children", "dissolution_children"}
_CHILDREN_TYPES = {"dissolution_children", "paternity", "parenting_modification"}


class FamilyLawObligation(models.Model):
    _name = "familylaw.obligation"
    _description = "Court-Imposed Obligation (AO 14-13)"
    _inherit = ["mail.thread", "mail.activity.mixin"]
    _order = "id"

    case_id = fields.Many2one(
        "familylaw.case", required=True, ondelete="cascade", index=True, tracking=True,
    )
    name = fields.Char(required=True)
    obligation_type = fields.Selection(
        selection=[
            ("status_quo_order", "Status Quo Order"),
            ("parenting_course", "Parenting Course"),
            ("mediation", "Mediation"),
            ("other", "Other"),
        ],
        required=True,
        tracking=True,
    )
    required = fields.Boolean(default=True)
    state = fields.Selection(
        selection=[
            ("pending", "Pending"),
            ("completed", "Completed"),
            ("waived", "Waived"),
        ],
        default="pending",
        required=True,
        tracking=True,
    )
    completed_date = fields.Date(readonly=True, copy=False)
    notes = fields.Text()

    def action_complete(self):
        for ob in self:
            ob.state = "completed"
            ob.completed_date = fields.Date.context_today(ob)
            ob.message_post(body=_("Obligation completed."))
        return True

    def action_waive(self):
        for ob in self:
            ob.state = "waived"
            ob.message_post(body=_("Obligation waived (by the court / attorney)."))
        return True


class FamilyLawCaseObligations(models.Model):
    _inherit = "familylaw.case"

    obligation_ids = fields.One2many(
        "familylaw.obligation", "case_id", string="Obligations",
    )

    @api.model_create_multi
    def create(self, vals_list):
        cases = super().create(vals_list)
        cases._seed_miamidade_obligations()
        return cases

    def _seed_miamidade_obligations(self):
        """Idempotently seed AO 14-13 obligations for Miami-Dade matters."""
        Ob = self.env["familylaw.obligation"]
        for case in self:
            if case.county != "miami_dade":
                continue
            existing = set(case.obligation_ids.mapped("obligation_type"))
            to_add = []
            if case.case_type in _DISSOLUTION_TYPES:
                to_add.append(("status_quo_order",
                               _("Status Quo Order (AO 14-13)")))
            if case.case_type in _CHILDREN_TYPES:
                to_add.append(("parenting_course",
                               _("Parenting Course (mandatory, AO 14-13)")))
            to_add.append(("mediation", _("Mediation before final hearing")))
            for otype, label in to_add:
                if otype in existing:
                    continue
                Ob.create({
                    "case_id": case.id,
                    "obligation_type": otype,
                    "name": label,
                    "required": True,
                })
        return True

    def action_seed_obligations(self):
        self._seed_miamidade_obligations()
        return True

    def _check_parenting_course_before_judgment(self):
        for case in self:
            pending = case.obligation_ids.filtered(
                lambda o: o.obligation_type == "parenting_course"
                and o.required and o.state == "pending")
            if pending:
                raise UserError(_(
                    "The mandatory parenting course must be completed before this "
                    "matter can be set for the final hearing / judgment (AO 14-13)."))

    def action_set_hearing(self):
        # Course-before-judgment guard layered on the Step 1 transition.
        self._check_parenting_course_before_judgment()
        return super().action_set_hearing()
