# -*- coding: utf-8 -*-
"""STEP 10 — Emergency workflow (Rule 12.941 pick-up / removal).

An emergency motion hangs off a PROCEEDING (typically the fast-path matter opened by
the intake urgency screen in Step 2). The two structural safety features:

  * the HAVE-ORDER-vs-NOT fork — the required attachments differ depending on whether
    there is already an order to enforce (certified copy) or the movant must establish
    the emergency from scratch (verified motion / sworn affidavit);
  * a MISSING-ATTACHMENT BLOCK — the motion cannot be marked ready/filed until every
    required attachment for its fork is present.

VERIFY current rule — pick-up / emergency-relief mechanics and required attachments
are volatile; confirm before relying in production. Nothing here decides the motion;
the attorney signs and the court rules.
"""

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


class FamilyLawEmergencyMotion(models.Model):
    _name = "familylaw.emergency.motion"
    _description = "Emergency Motion (12.941)"
    _inherit = ["mail.thread", "mail.activity.mixin"]
    _order = "create_date desc"

    name = fields.Char(required=True, default="Emergency Motion", tracking=True)
    proceeding_id = fields.Many2one(
        "familylaw.proceeding", required=True, ondelete="cascade", index=True,
        tracking=True,
    )
    case_id = fields.Many2one(
        "familylaw.case", related="proceeding_id.case_id", store=True, index=True,
    )
    child_id = fields.Many2one("familylaw.child", string="Child")
    motion_type = fields.Selection(
        selection=[
            ("pickup_order", "Pick-Up Order"),
            ("temporary_custody", "Emergency Temporary Custody"),
            ("prevent_removal", "Prevent Removal from Jurisdiction"),
            ("other", "Other Emergency Relief"),
        ],
        string="Motion Type",
        required=True,
        default="pickup_order",
        tracking=True,
    )
    have_existing_order = fields.Boolean(
        string="Existing Order to Enforce?",
        tracking=True,
        help="The fork: enforce an existing order (certified copy) vs. establish the "
             "emergency from scratch (verified motion / sworn affidavit).",
    )
    existing_order_reference = fields.Char(string="Existing Order Reference")
    basis = fields.Text(string="Sworn Basis (no existing order)")

    attachment_ids = fields.One2many(
        "familylaw.emergency.attachment", "motion_id", string="Required Attachments",
    )
    missing_required_count = fields.Integer(
        compute="_compute_missing", string="Missing Required",
    )
    state = fields.Selection(
        selection=[
            ("draft", "Draft"),
            ("ready", "Ready to File"),
            ("filed", "Filed"),
        ],
        default="draft",
        required=True,
        tracking=True,
    )

    @api.depends("attachment_ids.is_required", "attachment_ids.provided")
    def _compute_missing(self):
        for m in self:
            m.missing_required_count = len(
                m.attachment_ids.filtered(lambda a: a.is_required and not a.provided)
            )

    # --- requirement seeding (the fork) -------------------------------------
    def _required_for_fork(self):
        self.ensure_one()
        if self.have_existing_order:
            return [
                _("Certified copy of the existing order"),
                _("Proposed pick-up / enforcement order"),
            ]
        return [
            _("Verified motion / sworn affidavit establishing the emergency"),
            _("Proposed pick-up order"),
        ]

    def action_seed_requirements(self):
        Att = self.env["familylaw.emergency.attachment"]
        for m in self:
            m.attachment_ids.unlink()
            for label in m._required_for_fork():
                Att.create({"motion_id": m.id, "name": label, "is_required": True})
            m.message_post(body=_("Required attachments seeded for the %s path.")
                           % ("existing-order" if m.have_existing_order else "no-order"))
        return True

    # --- gates --------------------------------------------------------------
    def _ensure_complete(self):
        for m in self:
            missing = m.attachment_ids.filtered(
                lambda a: a.is_required and not a.provided)
            if not m.attachment_ids:
                raise UserError(
                    _("No attachment checklist yet. Seed the requirements first.")
                )
            if missing:
                raise UserError(
                    _("Emergency motion '%(name)s' is missing required attachment(s): "
                      "%(list)s. It cannot be filed until complete.",
                      name=m.name, list="; ".join(missing.mapped("name")))
                )

    def action_mark_ready(self):
        self._ensure_complete()
        for m in self:
            m.state = "ready"
            m.message_post(body=_("All required attachments present — ready to file."))
        return True

    def action_file(self):
        for m in self:
            if m.state != "ready":
                raise UserError(
                    _("Mark the motion ready (all attachments present) before filing.")
                )
            m.state = "filed"
            m.message_post(body=_("Emergency motion filed."))
        return True

    # --- creation helper (fast-path) ----------------------------------------
    @api.model
    def open_for_case(self, case, motion_type, have_existing_order, *,
                      child=None, basis=None, existing_order_reference=None):
        case = case if hasattr(case, "id") else self.env["familylaw.case"].browse(case)
        proc = case.proceeding_ids.filtered(lambda p: p.state == "open")[:1]
        if not proc:
            proc = self.env["familylaw.proceeding"].create({
                "case_id": case.id,
                "name": _("Emergency Proceeding"),
                "proceeding_type": "other",
            })
        motion = self.create({
            "proceeding_id": proc.id,
            "motion_type": motion_type,
            "have_existing_order": have_existing_order,
            "child_id": child.id if child else False,
            "basis": basis or False,
            "existing_order_reference": existing_order_reference or False,
        })
        motion.action_seed_requirements()
        return motion


class FamilyLawEmergencyAttachment(models.Model):
    _name = "familylaw.emergency.attachment"
    _description = "Emergency Motion Attachment Requirement"
    _order = "id"

    motion_id = fields.Many2one(
        "familylaw.emergency.motion", required=True, ondelete="cascade", index=True,
    )
    name = fields.Char(required=True)
    is_required = fields.Boolean(default=True)
    provided = fields.Boolean(default=False)
