"""services/audit_log_service.py

Audit trail for state-CHANGING actions the assistant executes on a user's
instruction — today only FR-07.4's manager leave approval.

Section 10's Audit Logging NFR, verbatim: "Every AI decision or action —
auto-approval, auto-rejection, cancellation, escalation — shall be logged
with timestamp, decision basis, and rule version, tagged with
source = 'AI Assistant.'"

Those four fields are the contract this module exists to guarantee, so all
four are set here rather than by the caller: SOURCE and the rule version are
constants, the timestamp is the row's own created_at, and decision_basis is
assembled from what the caller passes about the confirmation it obtained.
A caller cannot forget one, and cannot log an approval under a different
source.

Best-effort, exactly like erp_client's call log: its own short-lived session
(never the request's db handle, which may already be mid-transaction), run
off the event loop, and it never raises. An audit write that fails must not
turn an approval the manager already confirmed — and erp-api already
executed — into an error message.

That trade-off has one consequence worth stating plainly: the log is
best-effort, so a database outage can lose a row. What it CANNOT do is
silently disagree with reality, because the row is written after erp-api's
own answer and records that answer verbatim.
"""

import logging
import os
from datetime import datetime

from fastapi.concurrency import run_in_threadpool

from database import SessionLocal
from models.ai_action_audit_log import AiActionAuditLog

logger = logging.getLogger(__name__)

# The NFR's required tag. Not a parameter: every row this module writes is by
# definition an action taken through the assistant.
SOURCE = "AI Assistant"

# The version of the decision rules in force when the action was taken, so a
# row stays interpretable after those rules change. Env-overridable because
# it tracks the deployed rule set, not this file — bump it when the approval
# flow's rules change, not when its code does.
RULE_VERSION = os.getenv("AI_DECISION_RULE_VERSION", "FR-07.4/1.0")


def _decision_basis(action: str, confirmation_query: str, requested_query: str | None) -> str:
    """The WHY behind the action, in the terms FR-08.3 defines it: this
    assistant never decides an approval on its own, so the basis is always
    the manager's own explicit confirmation of a specific request — and the
    two messages that produced it are quoted so an auditor can see exactly
    what was asked and what was confirmed."""
    parts = [
        f"Manager-initiated {action} executed after explicit in-chat confirmation (FR-08.3).",
    ]
    if requested_query:
        parts.append(f'Request message: "{requested_query.strip()[:500]}"')
    if confirmation_query:
        parts.append(f'Confirmation message: "{confirmation_query.strip()[:500]}"')
    return " ".join(parts)


async def _persist(**fields) -> None:
    """The threadpool hop, named so the one place that has to be
    exception-proof (log_leave_approval) reads as a single call."""
    await run_in_threadpool(_write, **fields)


def _write(**fields) -> None:
    """Never raises. SessionLocal() is INSIDE the try because it is itself a
    thing that fails when the database is down - leaving it outside was the
    one line that could have turned a logging outage into a failed reply for
    an approval erp-api had already executed."""
    db = None
    try:
        db = SessionLocal()
        db.add(AiActionAuditLog(**fields))
        db.commit()
    except Exception as e:
        logger.error("Failed to write AI action audit log: %s", e)
        if db is not None:
            try:
                db.rollback()
            except Exception:
                pass
    finally:
        if db is not None:
            try:
                db.close()
            except Exception:
                pass


async def log_leave_approval(
    *,
    action: str,
    leave_request_id,
    executed: bool,
    confirmation_query: str,
    requested_query: str | None = None,
    employee_id=None,
    employee_name: str | None = None,
    approver_id=None,
    approver_name: str | None = None,
    erp_status: int | None = None,
    erp_message: str | None = None,
    company_id=None,
    conversation_id: str | None = None,
) -> None:
    """Records one approval attempt — successful or not.

    executed=False rows are the point of logging attempts rather than
    outcomes: "the manager confirmed an approval and erp-api refused it" is
    an auditable event, and its absence is indistinguishable from the
    logging having failed.
    """
    logger.info(
        "[Audit] %s leave_request_id=%s executed=%s source=%s rule_version=%s",
        action, leave_request_id, executed, SOURCE, RULE_VERSION,
    )
    try:
        await _persist(
            action=action,
            resource_type="leave_request",
            resource_id=int(leave_request_id) if leave_request_id is not None else None,
            employee_id=int(employee_id) if employee_id is not None else None,
            employee_name=employee_name,
            approver_id=int(approver_id) if approver_id is not None else None,
            approver_name=approver_name,
            decision_basis=_decision_basis(action, confirmation_query, requested_query),
            rule_version=RULE_VERSION,
            source=SOURCE,
            executed=bool(executed),
            erp_status=erp_status,
            erp_message=erp_message,
            company_id=int(company_id) if company_id is not None else None,
            conversation_id=conversation_id,
            created_at=datetime.utcnow(),
        )
    except Exception as e:
        # The outer belt to _write's braces: this is called immediately after
        # an approval erp-api has already applied, and there is no version of
        # "the audit write blew up" that should turn into an error message
        # about the approval itself.
        logger.error("Audit logging failed for %s leave_request_id=%s: %s",
                     action, leave_request_id, e)


async def log_regularization_approval(
    *,
    action: str,
    regularization_id,
    executed: bool,
    confirmation_query: str,
    requested_query: str | None = None,
    employee_id=None,
    employee_name: str | None = None,
    approver_id=None,
    approver_name: str | None = None,
    erp_status: int | None = None,
    erp_message: str | None = None,
    company_id=None,
    conversation_id: str | None = None,
) -> None:
    """The attendance-regularization sibling of log_leave_approval.

    Separate function rather than a resource_type argument on that one: the
    NFR's four fields are guaranteed HERE, not by the caller, and the way
    that guarantee holds is that a caller cannot choose what kind of row it
    writes. Both approval flows get a function that can only write their own
    resource_type, so a regularization can never be logged as a leave.

    Same best-effort contract, for the same reason: this runs after erp-api
    has already applied the approval, so it must never raise.
    """
    logger.info(
        "[Audit] %s regularization_id=%s executed=%s source=%s rule_version=%s",
        action, regularization_id, executed, SOURCE, RULE_VERSION,
    )
    try:
        await _persist(
            action=action,
            resource_type="regularization_request",
            resource_id=int(regularization_id) if regularization_id is not None else None,
            employee_id=int(employee_id) if employee_id is not None else None,
            employee_name=employee_name,
            approver_id=int(approver_id) if approver_id is not None else None,
            approver_name=approver_name,
            decision_basis=_decision_basis(action, confirmation_query, requested_query),
            rule_version=RULE_VERSION,
            source=SOURCE,
            executed=bool(executed),
            erp_status=erp_status,
            erp_message=erp_message,
            company_id=int(company_id) if company_id is not None else None,
            conversation_id=conversation_id,
            created_at=datetime.utcnow(),
        )
    except Exception as e:
        logger.error("Audit logging failed for %s regularization_id=%s: %s",
                     action, regularization_id, e)
