# -*- coding: utf-8 -*-
"""STEP 9 — Child-support modification workflow (end to end).

Wires Steps 1-8 for a support modification. Per the locked decision, a modification
does NOT mutate the original action — it opens a NEW `familylaw.proceeding` under the
same case, and deadlines/documents attach to that proceeding.

Captures the deterministic, NON-judgment facts:
  * the 15%/$50 substantial-change threshold (presumption of substantial change) —
    computed, never an opinion on whether the court will grant it;
  * the 20-day answer clock on the supplemental petition;
  * the DOR / Title IV-D flag (routes differently);
  * retroactivity to the filing date.

Prior-judgment handling is EXTRACTION + PLAIN SUMMARY + FLAGGED interpretation
QUESTIONS — never a conclusion or ruling (locked decision). The AI call is mocked
in tests. Nothing here decides the modification; the attorney does.

VERIFY current rule — the 15%/$50 presumption (§61.30(1)(b)) and the 20-day answer
window are volatile; confirm before relying in production.
"""

from odoo import api, fields, models, _

THRESHOLD_PCT = 0.15      # 15% — VERIFY
THRESHOLD_MIN = 50.0      # or $50, whichever is greater — VERIFY
ANSWER_DAYS = 20          # answer to supplemental petition — VERIFY


class FamilyLawSupportModification(models.Model):
    _name = "familylaw.support.modification"
    _description = "Child-Support Modification"
    _inherit = ["mail.thread", "mail.activity.mixin"]
    _order = "create_date desc"

    name = fields.Char(default="Support Modification", 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,
    )

    current_support_amount = fields.Float(string="Current Monthly Support", tracking=True)
    proposed_support_amount = fields.Float(string="Proposed Monthly Support", tracking=True)
    change_amount = fields.Float(compute="_compute_threshold", store=True)
    change_pct = fields.Float(compute="_compute_threshold", store=True,
                              string="Change %")
    threshold_amount = fields.Float(compute="_compute_threshold", store=True,
                                    string="Required Min Change")
    meets_threshold = fields.Boolean(
        compute="_compute_threshold", store=True,
        string="Meets 15%/$50 Presumption",
        help="Deterministic threshold check ONLY. Whether the court grants the "
             "modification is the attorney's/judge's call — not stated here.",
    )

    is_dor_case = fields.Boolean(
        string="DOR / Title IV-D Case",
        tracking=True,
        help="Department of Revenue Title IV-D case — routes differently.",
    )
    filing_date = fields.Date(string="Petition Filing Date",
                              default=fields.Date.context_today, tracking=True)
    retroactivity_date = fields.Date(
        string="Retroactive To",
        help="Modification is generally retroactive to the date the supplemental "
             "petition was filed. Verify the current rule for the matter.",
    )
    retroactivity_note = fields.Text(
        default=lambda self: _(
            "A granted modification is generally retroactive to the petition filing "
            "date. The attorney determines the applicable retroactivity."
        ),
    )

    # Prior judgment — extraction + summary + FLAGGED questions (no conclusions)
    prior_order_text = fields.Text(string="Prior Order Text")
    extracted_summary = fields.Text(string="Plain-Language Summary", readonly=True)
    interpretation_flags = fields.Text(
        string="Interpretation Questions (for attorney)", readonly=True,
        help="Questions surfaced for the attorney — never answered or concluded here.",
    )
    extraction_task_id = fields.Many2one("familylaw.ai.task", readonly=True)

    @api.depends("current_support_amount", "proposed_support_amount")
    def _compute_threshold(self):
        for rec in self:
            change = abs((rec.proposed_support_amount or 0.0)
                         - (rec.current_support_amount or 0.0))
            rec.change_amount = change
            base = rec.current_support_amount or 0.0
            rec.change_pct = (change / base * 100.0) if base else 0.0
            rec.threshold_amount = max(THRESHOLD_MIN, THRESHOLD_PCT * base)
            rec.meets_threshold = change >= rec.threshold_amount and change > 0

    # --- creation wiring ----------------------------------------------------
    @api.model
    def open_for_case(self, case, current_amount, proposed_amount, *,
                      is_dor=False, filing_date=None, prior_order_text=None):
        """Open a NEW modification proceeding under the case and wire its 20-day
        answer deadline. Returns the modification record."""
        case = case if hasattr(case, "id") else self.env["familylaw.case"].browse(case)
        filing_date = filing_date or fields.Date.context_today(self)

        proc = self.env["familylaw.proceeding"].create({
            "case_id": case.id,
            "name": _("Support Modification (%s)") % filing_date,
            "proceeding_type": "modification",
        })
        rec = self.create({
            "proceeding_id": proc.id,
            "current_support_amount": current_amount,
            "proposed_support_amount": proposed_amount,
            "is_dor_case": is_dor,
            "filing_date": filing_date,
            "retroactivity_date": filing_date,
            "prior_order_text": prior_order_text or False,
        })
        # 20-day answer clock on the supplemental petition.
        self.env["familylaw.deadline"].create({
            "proceeding_id": proc.id,
            "name": _("Answer to Supplemental Petition due"),
            "deadline_type": "answer",
            "trigger_date": filing_date,
            "days": ANSWER_DAYS,
        })
        case.message_post(body=_(
            "New support-modification proceeding opened (filing %s). 20-day answer "
            "clock set. This is a new proceeding under the same matter.") % filing_date)
        return rec

    # --- prior-judgment extraction (flagged, not concluded) -----------------
    def action_extract_prior_judgment(self):
        """AI extraction + plain summary + FLAGGED interpretation questions.
        Never states a legal conclusion. Mocked in tests."""
        Client = self.env["familylaw.ai.client"]
        for rec in self:
            instruction = _(
                "Extract the key support terms from this order and write a plain-"
                "language summary. Then LIST interpretation QUESTIONS the attorney "
                "should resolve. Do NOT answer them or state any legal conclusion.\n\n"
                "%s"
            ) % (rec.prior_order_text or "")
            result, task = Client.generate(
                "extract_judgment", [{"role": "user", "content": instruction}],
                case=rec.case_id, proceeding=rec.proceeding_id,
                name=_("Prior-judgment extraction"),
            )
            text = result.get("text") or ""
            rec.extracted_summary = text
            rec.interpretation_flags = _(
                "FLAGGED FOR ATTORNEY — these are questions, NOT conclusions or "
                "rulings. The software does not interpret the order:\n%s"
            ) % text
            rec.extraction_task_id = task.id
            rec.message_post(body=_(
                "Prior judgment extracted and summarized. Interpretation questions "
                "flagged for the attorney — no conclusion drawn by the software."))
        return True
