# -*- coding: utf-8 -*-
"""STEP 14 — Comms drafting + AI-assisted billing flag + matter-scoped access.

Three concerns:
  * COMMS — plain-language client updates drafted (optionally AI-assisted) for
    attorney review. They are born draft and NEVER auto-send: there is no code path
    that transmits a communication without an explicit, post-approval human action.
  * BILLING FLAG — time entries carry an ai_assisted flag so the AI-assisted share of
    work is reportable (transparency, fee reasonableness).
  * MATTER-SCOPED ACCESS — record rules confine staff (non-lawyers) to the matters
    they are assigned to (Bar Rule 4-5.3 supervision + confidentiality). Attorneys see
    all. The record rules live in security/familylaw_security.xml.

Hardening note (infra, not code): encryption-at-rest for case data and backups of the
audit trail / DocuSeal host are operational requirements (Requirements for Success
#5) — out of scope for the module but called out here.
"""

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

ATTORNEY_GROUP = "activeblue_familylaw_v2.group_familylaw_attorney"


class FamilyLawComms(models.Model):
    _name = "familylaw.comms"
    _description = "Client Communication (review-gated, never auto-send)"
    _inherit = ["mail.thread", "mail.activity.mixin"]
    _order = "create_date desc"

    name = fields.Char(string="Subject", required=True, tracking=True)
    case_id = fields.Many2one(
        "familylaw.case", required=True, ondelete="cascade", index=True, tracking=True,
    )
    comm_type = fields.Selection(
        selection=[
            ("update", "Status Update"),
            ("email", "Email"),
            ("letter", "Letter"),
        ],
        default="update",
        required=True,
    )
    body = fields.Html(sanitize=True)
    source = fields.Selection(
        selection=[("ai", "AI-Assisted"), ("manual", "Manual")],
        default="manual",
    )
    state = fields.Selection(
        selection=[
            ("draft", "Draft"),
            ("approved", "Approved"),
            ("sent", "Sent"),
        ],
        default="draft",
        required=True,
        copy=False,
        tracking=True,
    )
    approved_by_id = fields.Many2one("res.users", readonly=True, copy=False)
    sent_date = fields.Datetime(readonly=True, copy=False)

    def _ensure_attorney(self):
        if not self.env.user.has_group(ATTORNEY_GROUP):
            raise UserError(_("Only an attorney may approve a client communication. "
                              "Staff draft and assemble; they do not communicate legal "
                              "positions to clients."))

    def action_approve(self):
        self._ensure_attorney()
        for c in self:
            if c.state != "draft":
                raise UserError(_("Only a draft communication can be approved."))
            c.write({"state": "approved", "approved_by_id": self.env.user.id})
            c.message_post(body=_("Communication approved by %s.") % self.env.user.name)
        return True

    def action_send(self):
        """Explicit, human-initiated send. NEVER auto — requires prior approval."""
        for c in self:
            if c.state != "approved":
                raise UserError(_(
                    "A communication must be attorney-approved before it can be sent. "
                    "Communications never auto-send."))
            c.write({"state": "sent", "sent_date": fields.Datetime.now()})
            c.message_post(body=_("Communication sent by %s.") % self.env.user.name)
        return True


class FamilyLawTimeEntry(models.Model):
    _name = "familylaw.time.entry"
    _description = "Time Entry (with AI-assist flag)"
    _order = "date desc, id desc"

    case_id = fields.Many2one(
        "familylaw.case", required=True, ondelete="cascade", index=True,
    )
    user_id = fields.Many2one(
        "res.users", default=lambda self: self.env.user, required=True,
    )
    date = fields.Date(default=fields.Date.context_today, required=True)
    description = fields.Char(required=True)
    hours = fields.Float(required=True)
    ai_assisted = fields.Boolean(
        string="AI-Assisted",
        help="Set when this work was materially assisted by AI — keeps the AI-assisted "
             "share reportable for fee transparency.",
    )


class FamilyLawCaseComms(models.Model):
    _inherit = "familylaw.case"

    comms_ids = fields.One2many("familylaw.comms", "case_id", string="Communications")
    time_entry_ids = fields.One2many(
        "familylaw.time.entry", "case_id", string="Time Entries")
    total_hours = fields.Float(compute="_compute_time", store=True)
    ai_assisted_hours = fields.Float(compute="_compute_time", store=True)
    ai_assisted_ratio = fields.Float(
        compute="_compute_time", store=True, string="AI-Assisted %",
    )

    @api.depends("time_entry_ids.hours", "time_entry_ids.ai_assisted")
    def _compute_time(self):
        for case in self:
            total = sum(case.time_entry_ids.mapped("hours"))
            ai = sum(case.time_entry_ids.filtered("ai_assisted").mapped("hours"))
            case.total_hours = total
            case.ai_assisted_hours = ai
            case.ai_assisted_ratio = (ai / total * 100.0) if total else 0.0
