# -*- coding: utf-8 -*-
"""STEP 2 — Intake questionnaire wizard.

Multi-step TransientModel that:
  * runs triage FIRST (caller info, opposing party, urgency screen),
  * branches on urgency: emergency → fast-path on minimum facts;
    standard → strict (name + client + case_type + county required),
  * branches into the child-support modification question set,
  * creates a draft familylaw.case in 'intake' state (and its initial proceeding,
    via the case model's create() override),
  * runs conflict screening on the opposing party,
  * and captures the caller's concern as an attorney question — never answers it.

No external/network calls. Pure local DB.
"""

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

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

_CASE_TYPE_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"),
]


class FamilyLawIntakeWizard(models.TransientModel):
    _name = "familylaw.intake.wizard"
    _description = "Family Law Intake Questionnaire"

    step = fields.Selection(
        selection=[
            ("triage", "1 — Triage"),
            ("details", "2 — Case Details"),
            ("modification", "3 — Modification Details"),
            ("confirm", "4 — Complete"),
        ],
        default="triage",
        required=True,
    )

    # === TRIAGE (step 1) ====================================================
    caller_name = fields.Char(string="Caller / Client Name")
    caller_phone = fields.Char(string="Phone")
    caller_email = fields.Char(string="Email")
    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",
    )
    case_type = fields.Selection(
        selection=_CASE_TYPE_SELECTION,
        string="Case Type",
    )
    opposing_party_name = fields.Char(string="Opposing Party Name")
    has_children = fields.Boolean(string="Minor children involved?")
    has_existing_order = fields.Boolean(string="Existing court order?")

    # Urgency screen — runs first; triggers the emergency fast-path
    urgency_child_withheld = fields.Boolean(
        string="Child being withheld / refused access?"
    )
    urgency_removal_threat = fields.Boolean(
        string="Threat of removal from Florida?"
    )
    urgency_violence = fields.Boolean(
        string="Domestic violence / immediate safety concern?"
    )
    urgency_description = fields.Text(
        string="Describe the Emergency",
        help="Captured verbatim for the attorney. Do not interpret or advise.",
    )
    is_emergency = fields.Boolean(
        compute="_compute_is_emergency",
        store=True,
        string="Emergency",
    )

    # === STANDARD DETAILS (step 2 — strict path) ============================
    matter_name = fields.Char(string="Matter Name")
    client_partner_id = fields.Many2one(
        "res.partner",
        string="Client (existing contact)",
        help="Pick an existing contact or leave blank to create from caller name.",
    )
    attorney_id = fields.Many2one("res.users", string="Responsible Attorney")
    paralegal_id = fields.Many2one("res.users", string="Paralegal")

    # === MODIFICATION DETAILS (step 3 — modification types only) ============
    existing_order_summary = fields.Text(
        string="Summary of Existing Order",
        help="Captured facts from the prior judgment. Not interpreted here — "
             "prior-judgment interpretation is Step 6+ (attorney-reviewed).",
    )
    reason_for_modification = fields.Text(string="Reason for Modification")
    income_change_details = fields.Text(
        string="Income / Financial Change Details",
        help="E.g. 'income dropped from $X to $Y in month/year'. Facts only.",
    )

    # Caller concern — CAPTURED AS ATTORNEY QUESTION, never answered here
    caller_concern = fields.Text(
        string="Caller's Question / Concern for the Attorney",
        help="Record the caller's own words. This is logged on the case as a "
             "question for the attorney. This software does not answer "
             "'do I have a good case?' — that determination belongs to the attorney.",
    )

    # === RESULT (step 4) ====================================================
    created_case_id = fields.Many2one(
        "familylaw.case",
        string="Created Matter",
        readonly=True,
    )
    conflict_summary = fields.Text(
        string="Conflict Screening Results",
        readonly=True,
    )

    # -----------------------------------------------------------------------

    @api.depends("urgency_child_withheld", "urgency_removal_threat", "urgency_violence")
    def _compute_is_emergency(self):
        for w in self:
            w.is_emergency = bool(
                w.urgency_child_withheld
                or w.urgency_removal_threat
                or w.urgency_violence
            )

    # --- Navigation ---------------------------------------------------------

    def action_next(self):
        self.ensure_one()
        if self.step == "triage":
            if self.is_emergency:
                self._create_emergency_case()
                self.step = "confirm"
            else:
                self.step = "details"

        elif self.step == "details":
            self._validate_standard_details()
            if self.case_type in _MODIFICATION_TYPES:
                self.step = "modification"
            else:
                self._create_standard_case()
                self.step = "confirm"

        elif self.step == "modification":
            self._create_standard_case()
            self.step = "confirm"

        return self._reopen()

    def action_back(self):
        self.ensure_one()
        if self.step == "details":
            self.step = "triage"
        elif self.step == "modification":
            self.step = "details"
        return self._reopen()

    def action_open_case(self):
        self.ensure_one()
        return {
            "type": "ir.actions.act_window",
            "res_model": "familylaw.case",
            "res_id": self.created_case_id.id,
            "view_mode": "form",
            "target": "current",
        }

    def _reopen(self):
        return {
            "type": "ir.actions.act_window",
            "res_model": "familylaw.intake.wizard",
            "res_id": self.id,
            "view_mode": "form",
            "target": "new",
        }

    # --- Validation ---------------------------------------------------------

    def _validate_standard_details(self):
        errors = []
        if not self.matter_name:
            errors.append(_("Matter Name is required."))
        if not self.client_partner_id and not self.caller_name:
            errors.append(_("A client contact or caller name is required."))
        if not self.case_type:
            errors.append(_("Case Type is required."))
        if not self.county:
            errors.append(_("County / Court is required."))
        if errors:
            raise UserError("\n".join(errors))

    # --- Case creation ------------------------------------------------------

    def _resolve_or_create_partner(self):
        if self.client_partner_id:
            return self.client_partner_id
        return self.env["res.partner"].create({
            "name": self.caller_name or _("Unknown — Emergency Intake"),
            "phone": self.caller_phone or False,
            "email": self.caller_email or False,
        })

    def _create_emergency_case(self):
        """Fast-path: open on minimum facts — who, which child, what's happening."""
        partner = self._resolve_or_create_partner()

        flags = []
        if self.urgency_child_withheld:
            flags.append(_("Child withheld / refused access"))
        if self.urgency_removal_threat:
            flags.append(_("Threat of removal from Florida"))
        if self.urgency_violence:
            flags.append(_("Domestic violence / safety concern"))
        urgency_text = "; ".join(flags)
        if self.urgency_description:
            urgency_text += "\n" + self.urgency_description

        case = self.env["familylaw.case"].create({
            "name": self.matter_name or _("EMERGENCY — %s") % partner.name,
            "client_id": partner.id,
            "case_type": self.case_type or "other",
            "county": self.county or "miami_dade",
            "is_emergency": True,
            "urgency_notes": urgency_text,
        })

        if self.opposing_party_name:
            self.env["familylaw.party"].create({
                "case_id": case.id,
                "name": self.opposing_party_name,
                "role": "opposing_party",
            })

        self._post_caller_concern(case)
        self._run_screening_and_summarise(case)
        self.created_case_id = case

    def _create_standard_case(self):
        """Strict path: all required fields validated before reaching here."""
        partner = self._resolve_or_create_partner()

        case = self.env["familylaw.case"].create({
            "name": self.matter_name,
            "client_id": partner.id,
            "case_type": self.case_type,
            "county": self.county or "miami_dade",
            "attorney_id": self.attorney_id.id if self.attorney_id else False,
            "paralegal_id": self.paralegal_id.id if self.paralegal_id else False,
            "is_emergency": False,
        })

        if self.opposing_party_name:
            self.env["familylaw.party"].create({
                "case_id": case.id,
                "name": self.opposing_party_name,
                "role": "opposing_party",
            })

        if self.reason_for_modification:
            case.message_post(
                body=_("Modification reason (captured at intake): %s")
                     % self.reason_for_modification
            )
        if self.existing_order_summary:
            case.message_post(
                body=_("Existing order summary (captured at intake; not legally "
                       "interpreted here — see Step 6+ for prior-judgment extraction): %s")
                     % self.existing_order_summary
            )

        self._post_caller_concern(case)
        self._run_screening_and_summarise(case)
        self.created_case_id = case

    def _post_caller_concern(self, case):
        if self.caller_concern:
            case.message_post(
                body=_(
                    "ATTORNEY QUESTION (captured at intake — this software does "
                    "not answer this; for attorney review only): %s"
                ) % self.caller_concern
            )

    def _run_screening_and_summarise(self, case):
        case.action_run_conflict_screening()
        hits = case.conflict_hit_ids
        if hits:
            lines = [
                _("⚠️ %(n)d potential conflict(s) found — attorney review required "
                  "before engaging:", n=len(hits))
            ]
            for h in hits:
                lines.append("  • " + (h.reason or h.party_name))
            self.conflict_summary = "\n".join(lines)
        else:
            self.conflict_summary = _("No potential conflicts detected.")
