# -*- coding: utf-8 -*-
"""STEP 6 — Citation ledger (born unverified). Step 7 adds verification + Gate 2.

Every case-law citation is born `unverified` and is mechanically blocked from any
filing until it passes verification against a real reporter (CourtListener) — the
citation gate (Gate 2), built in Step 7. This model holds the citation and its
status; the verification workflow and the filing gate are layered on in Step 7.

This is TIER 3: the existence/holdings/good-law judgments are NOT authoritative
until verified and attorney-approved. Lawyers have been sanctioned for AI-
hallucinated cites — this ledger is what makes that mechanically impossible.
"""

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

ATTORNEY_GROUP = "activeblue_familylaw_v2.group_familylaw_attorney"


class FamilyLawCitation(models.Model):
    _name = "familylaw.citation"
    _description = "Case-Law Citation (gated)"
    _inherit = ["mail.thread", "mail.activity.mixin"]
    _order = "create_date desc"

    document_id = fields.Many2one(
        "familylaw.document", string="Document", ondelete="cascade", index=True,
    )
    proceeding_id = fields.Many2one(
        "familylaw.proceeding",
        related="document_id.proceeding_id", store=True, index=True,
    )
    case_id = fields.Many2one(
        "familylaw.case", related="document_id.case_id", store=True, index=True,
    )
    citation_text = fields.Char(
        string="Citation", required=True, tracking=True,
        help="e.g. Smith v. Jones, 123 So. 3d 456 (Fla. 3d DCA 2015).",
    )
    case_name = fields.Char()
    reporter = fields.Char()
    court = fields.Char()
    year = fields.Char()
    proposition = fields.Text(
        string="Cited For",
        help="The proposition the citation supports in the draft.",
    )
    status = fields.Selection(
        selection=[
            ("unverified", "Unverified"),
            ("verified", "Verified"),
            ("not_found", "Not Found"),
            ("rejected", "Rejected / Bad Law"),
        ],
        default="unverified",
        required=True,
        copy=False,
        tracking=True,
        help="Born unverified. Must be 'verified' before it can enter a filing "
             "(Gate 2, enforced in Step 7).",
    )
    is_verified = fields.Boolean(
        compute="_compute_is_verified", store=True, string="Verified?",
    )
    source_ai_task_id = fields.Many2one("familylaw.ai.task", string="Proposed By (AI Task)")

    verification_source = fields.Char(string="Verified Via", readonly=True)
    verification_date = fields.Datetime(string="Verified On", readonly=True)
    verification_note = fields.Text(string="Verification Note", readonly=True)

    @api.depends("status")
    def _compute_is_verified(self):
        for cite in self:
            cite.is_verified = cite.status == "verified"

    # --- verification (Gate 2 engine) ---------------------------------------
    def action_verify(self):
        """Run the fail-closed verifier against each citation."""
        verifier = self.env["familylaw.citation.verifier"]
        for cite in self:
            verifier.verify_citation(cite)
        return True

    def action_attorney_verify(self):
        """Attorney override: the licensed attorney attests the cite is good law.
        Still a deliberate, audited human act — not an automatic pass."""
        if not self.env.user.has_group(ATTORNEY_GROUP):
            raise UserError(
                _("Only a licensed attorney may manually attest a citation.")
            )
        for cite in self:
            cite.write({
                "status": "verified",
                "verification_source": "attorney",
                "verification_date": fields.Datetime.now(),
                "verification_note": _("Manually attested by %s.") % self.env.user.name,
            })
            cite.message_post(body=_("Citation attested by attorney %s.")
                              % self.env.user.name)
        return True

    def action_reject(self):
        for cite in self:
            cite.status = "rejected"
            cite.message_post(body=_("Citation rejected."))
        return True
