# -*- coding: utf-8 -*-
"""STEP 7 — Research loop (search -> propose citations -> verify each -> synthesize).

The design allows the agentic research chain to run either in an external FastAPI
orchestrator OR as sequenced steps inside Odoo (an explicitly acceptable
alternative). This implements the in-Odoo path so the platform is self-contained;
the FastAPI orchestrator can replace run() later without changing callers.

TIER 3: every citation is born unverified and verified FAIL-CLOSED before the
synthesized memo can be filed; the memo itself is born ai_draft for attorney review.
Nothing here is authoritative.
"""

from odoo import api, fields, models, _


class FamilyLawResearchAgent(models.AbstractModel):
    _name = "familylaw.research.agent"
    _description = "Case-law research loop"

    @api.model
    def run(self, proceeding, question):
        """Run the loop and return the synthesized DRAFT document.

        1. PROPOSE — ask the model for candidate authority (citations born unverified)
        2. VERIFY  — run each through the fail-closed verifier
        3. SYNTHESIZE — draft a memo; the draft is born ai_draft (attorney review)

        Both model calls go through familylaw.ai.client (mocked in tests); the
        verifier's network calls are mocked too.
        """
        proceeding = proceeding if hasattr(proceeding, "id") else \
            self.env["familylaw.proceeding"].browse(proceeding)
        Client = self.env["familylaw.ai.client"]
        Doc = self.env["familylaw.document"]
        Cit = self.env["familylaw.citation"]
        verifier = self.env["familylaw.citation.verifier"]

        # 1. PROPOSE authority
        propose_msg = [{
            "role": "user",
            "content": _("Propose candidate Florida authority for: %s. Return "
                         "citations for the attorney to verify — do not assert good "
                         "law yourself.") % question,
        }]
        proposal, propose_task = Client.generate(
            "research_propose", propose_msg,
            case=proceeding.case_id, proceeding=proceeding,
            name=_("Research: propose authority"),
        )

        # Synthesis document is born ai_draft; citations attach to it.
        doc = Doc.create({
            "name": _("Research Memo — %s") % (question[:60] or "untitled"),
            "proceeding_id": proceeding.id,
            "document_type": "other",
            "source": "ai",
            "state": "ai_draft",
        })
        propose_task.document_id = doc.id

        citations = self.env["familylaw.citation"]
        for c in (proposal.get("citations") or []):
            cite = Cit.create({
                "document_id": doc.id,
                "citation_text": c.get("citation_text") or c.get("text") or _("(unparsed)"),
                "case_name": c.get("case_name"),
                "proposition": c.get("proposition"),
                "status": "unverified",
                "source_ai_task_id": propose_task.id,
            })
            citations |= cite

        # 2. VERIFY each (fail-closed)
        for cite in citations:
            verifier.verify_citation(cite)

        # 3. SYNTHESIZE using ONLY verified authority
        verified = citations.filtered(lambda c: c.status == "verified")
        verified_text = "\n".join(verified.mapped("citation_text")) or _("(none verified)")
        synth_msg = [{
            "role": "user",
            "content": _("Draft a research memo answering: %(q)s. Use ONLY these "
                         "verified citations:\n%(c)s", q=question, c=verified_text),
        }]
        synthesis, synth_task = Client.generate(
            "research_synthesize", synth_msg,
            case=proceeding.case_id, proceeding=proceeding,
            name=_("Research: synthesize memo"),
        )
        synth_task.document_id = doc.id
        doc.body = synthesis.get("text") or ""
        doc.message_post(body=_(
            "Research loop complete: %(p)d proposed, %(v)d verified. Memo is a DRAFT "
            "for attorney review; unverified citations block filing.",
            p=len(citations), v=len(verified),
        ))
        return doc
