# -*- coding: utf-8 -*-
"""STEP 1 — Case spine (updated in Step 2: case_number, county, emergency flag,
related records, initial-proceeding creation, conflict screening).
"""

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

ATTORNEY_GROUP = "activeblue_familylaw_v2.group_familylaw_attorney"

STATE_SEQUENCE = [
    "intake",
    "engaged",
    "disclosure",
    "discovery",
    "mediation",
    "hearing",
    "closed",
]

_MODIFICATION_TYPES = {
    "support_modification",
    "parenting_modification",
    "alimony_modification",
}


class FamilyLawCase(models.Model):
    _name = "familylaw.case"
    _description = "Family Law Case"
    _inherit = ["mail.thread", "mail.activity.mixin"]
    _order = "create_date desc"

    # --- Identity -----------------------------------------------------------
    name = fields.Char(
        string="Matter",
        required=True,
        tracking=True,
        help="Short matter title, e.g. 'In re the Marriage of Client A'.",
    )
    client_id = fields.Many2one(
        "res.partner",
        string="Client",
        required=True,
        tracking=True,
    )
    case_number = fields.Char(
        string="Court Case Number",
        index=True,
        tracking=True,
        help="Court-assigned case number (e.g. 2024-DR-001234). "
             "Leave blank until the court assigns one.",
    )
    county = fields.Selection(
        selection=[
            ("miami_dade", "Miami-Dade (11th Circuit)"),
            ("broward", "Broward (17th Circuit)"),
            ("palm_beach", "Palm Beach (15th Circuit)"),
            ("other_fl", "Other Florida County"),
        ],
        string="County / Court",
        default="miami_dade",
        tracking=True,
    )
    case_type = fields.Selection(
        selection=[
            ("dissolution_no_children", "Dissolution — no children"),
            ("dissolution_children", "Dissolution — with children"),
            ("paternity", "Paternity"),
            ("support_modification", "Child Support Modification"),
            ("parenting_modification", "Parenting / Time-Sharing Modification"),
            ("alimony_modification", "Alimony Modification"),
            ("enforcement", "Enforcement / Contempt"),
            ("dv_injunction", "Domestic Violence Injunction"),
            ("other", "Other"),
        ],
        string="Case Type",
        required=True,
        default="dissolution_children",
        tracking=True,
    )

    # --- People -------------------------------------------------------------
    attorney_id = fields.Many2one(
        "res.users",
        string="Responsible Attorney",
        tracking=True,
    )
    paralegal_id = fields.Many2one(
        "res.users",
        string="Paralegal",
        tracking=True,
    )

    # --- Representation (drives the Step 8 subpoena branch) -----------------
    representation = fields.Selection(
        selection=[
            ("attorney", "Attorney of Record"),
            ("pro_se", "Pro Se (self-represented)"),
        ],
        string="Representation",
        default="attorney",
        required=True,
        tracking=True,
        help="Pro-se matters route subpoena issuance through the clerk of court; "
             "attorney-of-record matters issue directly. See Forms & Playbook, Part C.",
    )

    # --- Emergency flags (Step 2 intake fast-path) --------------------------
    is_emergency = fields.Boolean(
        string="Emergency Matter",
        default=False,
        tracking=True,
        help="Set when the intake urgency screen trips. Matter opened on minimum "
             "facts; staff must complete the record immediately.",
    )
    urgency_notes = fields.Text(
        string="Urgency Notes",
        help="Emergency description captured at intake.",
    )

    # --- Gates / status -----------------------------------------------------
    conflict_check_cleared = fields.Boolean(
        string="Conflict Check Cleared",
        readonly=True,
        copy=False,
        tracking=True,
        help="Set by an attorney once the conflict check is documented and clear. "
             "Required before the matter can be engaged.",
    )
    state = fields.Selection(
        selection=[
            ("intake", "Intake"),
            ("engaged", "Engaged"),
            ("disclosure", "Mandatory Disclosure"),
            ("discovery", "Discovery"),
            ("mediation", "Mediation"),
            ("hearing", "Hearing / Trial"),
            ("closed", "Closed"),
        ],
        string="Stage",
        default="intake",
        required=True,
        copy=False,
        tracking=True,
    )
    date_opened = fields.Date(
        string="Date Opened",
        default=fields.Date.context_today,
    )
    active = fields.Boolean(default=True)

    # --- Related records (Step 2) -------------------------------------------
    party_ids = fields.One2many(
        "familylaw.party", "case_id",
        string="Parties",
    )
    child_ids = fields.One2many(
        "familylaw.child", "case_id",
        string="Children",
    )
    issue_ids = fields.One2many(
        "familylaw.issue", "case_id",
        string="Issues",
    )
    proceeding_ids = fields.One2many(
        "familylaw.proceeding", "case_id",
        string="Proceedings",
    )
    conflict_hit_ids = fields.One2many(
        "familylaw.conflict.hit", "case_id",
        string="Conflict Screening Hits",
    )
    conflict_hit_count = fields.Integer(
        compute="_compute_conflict_hit_count",
        string="Conflict Hits",
    )

    _sql_constraints = [
        (
            "case_number_unique",
            "UNIQUE(case_number)",
            "Court case number must be unique. Check the existing cases.",
        ),
    ]

    @api.depends("conflict_hit_ids")
    def _compute_conflict_hit_count(self):
        for case in self:
            case.conflict_hit_count = len(case.conflict_hit_ids)

    # --- Case creation: auto-open an initial proceeding --------------------
    @api.model_create_multi
    def create(self, vals_list):
        cases = super().create(vals_list)
        type_labels = dict(self._fields["case_type"].selection)
        for case in cases:
            if case.case_type in _MODIFICATION_TYPES:
                proc_type = "modification"
            elif case.case_type == "enforcement":
                proc_type = "enforcement"
            else:
                proc_type = "original"
            self.env["familylaw.proceeding"].create({
                "case_id": case.id,
                "name": _("Initial Proceeding — %s")
                        % type_labels.get(case.case_type, case.case_type),
                "proceeding_type": proc_type,
            })
        return cases

    # --- Conflict screening -------------------------------------------------
    def action_run_conflict_screening(self):
        """Search all party records across all matters for potential conflicts.

        Checks opposing parties on this case against:
          1. Any party role on any other matter (name match).
          2. Any client name on any other matter.

        Creates familylaw.conflict.hit records for attorney review.
        Never auto-clears conflict_check_cleared; that gate stays with the attorney.
        """
        for case in self:
            case.conflict_hit_ids.unlink()
            opposing = case.party_ids.filtered(
                lambda p: p.role == "opposing_party"
            )
            if not opposing:
                case.message_post(
                    body=_(
                        "Conflict screening: no opposing party on record. "
                        "Add an opposing party and re-run."
                    )
                )
                continue

            role_labels = dict(self.env["familylaw.party"]._fields["role"].selection)
            hit_count = 0

            for party in opposing:
                name = (party.name or "").strip()
                if not name:
                    continue

                # 1. Name appears as any party role on another matter
                for hit in self.env["familylaw.party"].search([
                    ("name", "ilike", name),
                    ("case_id", "!=", case.id),
                ]):
                    self.env["familylaw.conflict.hit"].create({
                        "case_id": case.id,
                        "party_name": name,
                        "hit_case_id": hit.case_id.id,
                        "hit_role": role_labels.get(hit.role, hit.role),
                        "reason": _(
                            "'%(n)s' appears as '%(r)s' in matter '%(m)s'",
                            n=name,
                            r=role_labels.get(hit.role, hit.role),
                            m=hit.case_id.name,
                        ),
                    })
                    hit_count += 1

                # 2. Name matches a client on another matter
                for cc in self.env["familylaw.case"].search([
                    ("client_id.name", "ilike", name),
                    ("id", "!=", case.id),
                ]):
                    self.env["familylaw.conflict.hit"].create({
                        "case_id": case.id,
                        "party_name": name,
                        "hit_case_id": cc.id,
                        "hit_role": _("Client"),
                        "reason": _(
                            "'%(n)s' matches client '%(c)s' in matter '%(m)s'",
                            n=name,
                            c=cc.client_id.name,
                            m=cc.name,
                        ),
                    })
                    hit_count += 1

            if hit_count:
                case.message_post(
                    body=_(
                        "⚠️ Conflict screening found %(n)d potential conflict(s). "
                        "Review the Conflict Hits tab — attorney must clear before engaging.",
                        n=hit_count,
                    )
                )
            else:
                case.message_post(
                    body=_("Conflict screening complete — no potential conflicts detected.")
                )
        return True

    # --- Internal helpers ---------------------------------------------------
    def _ensure_attorney(self):
        if not self.env.user.has_group(ATTORNEY_GROUP):
            raise UserError(
                _("Only a licensed attorney (Family Law / Attorney group) may "
                  "perform this action.")
            )

    def _require_state(self, allowed):
        bad = self.filtered(lambda c: c.state not in allowed)
        if bad:
            raise UserError(
                _("This action is not allowed from the current stage (%(states)s). "
                  "Allowed from: %(allowed)s.",
                  states=", ".join(sorted(set(bad.mapped("state")))),
                  allowed=", ".join(allowed))
            )

    def _advance_to(self, target):
        for case in self:
            case.state = target
            case.message_post(
                body=_("Stage changed to: %s")
                     % dict(self._fields["state"].selection).get(target, target)
            )

    # --- Gated transitions --------------------------------------------------
    def action_mark_conflict_cleared(self):
        self._ensure_attorney()
        for case in self:
            if case.conflict_check_cleared:
                continue
            case.conflict_check_cleared = True
            case.message_post(
                body=_("Conflict check cleared by %s.") % self.env.user.name
            )
        return True

    def action_engage(self):
        self._require_state(["intake"])
        not_cleared = self.filtered(lambda c: not c.conflict_check_cleared)
        if not_cleared:
            raise UserError(
                _("Cannot engage a matter before the conflict check is cleared. "
                  "An attorney must clear it first.")
            )
        self._advance_to("engaged")
        return True

    def action_start_disclosure(self):
        self._require_state(["engaged"])
        self._advance_to("disclosure")
        return True

    def action_start_discovery(self):
        self._require_state(["disclosure"])
        self._advance_to("discovery")
        return True

    def action_start_mediation(self):
        self._require_state(["discovery"])
        self._advance_to("mediation")
        return True

    def action_set_hearing(self):
        self._require_state(["mediation"])
        self._advance_to("hearing")
        return True

    def action_close(self):
        self._ensure_attorney()
        self._require_state([s for s in STATE_SEQUENCE if s != "closed"])
        self._advance_to("closed")
        return True

    def action_reopen(self):
        self._ensure_attorney()
        self._require_state(["closed"])
        self._advance_to("engaged")
        return True
