import os
import time
import asyncio
import json
import logging
import httpx
from fastapi.concurrency import run_in_threadpool

from database import SessionLocal
from models.erp_api_call_log import ErpApiCallLog

logger = logging.getLogger(__name__)

ERP_API_URL = os.getenv("ERP_API_URL", "")

logger.info("ERP_API_URL: %s", ERP_API_URL)
# FR-07.3 is now LIVE on both halves: get_team_pending_leaves for the leave
# lookup, and get_attendance_punch_details (GET /ai/attendance/punch-details)
# for the attendance one. The fixtures that stood in for the second are gone
# along with their flag - a dummy still wired up would now return a shape the
# renderer no longer understands, and its roster (John Doe, Priya Sharma...)
# silently denied every REAL employee name.
#
# ATTENDANCE_EXPLANATION_USE_DUMMY / INDIVIDUAL_REPORT_USE_DUMMY in an
# existing .env are simply ignored now; they gate nothing.
if os.getenv("ATTENDANCE_EXPLANATION_USE_DUMMY") or os.getenv("INDIVIDUAL_REPORT_USE_DUMMY"):
    logger.warning(
        "ATTENDANCE_EXPLANATION_USE_DUMMY/INDIVIDUAL_REPORT_USE_DUMMY is set but no "
        "longer does anything - attendance is served live from erp-api's "
        "/api/v1/ai/attendance/punch-details. The .env entry can be removed."
    )
# Tighter budget than ai_service.py's _http — this is a synchronous health
# probe, not an LLM generation call.
_http = httpx.AsyncClient(
    timeout=httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=5.0),
    limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
)


def extract_erp_message(body) -> str | None:
    """Pull erp-api's own user-facing message out of a response body.

    Shared by ErpApiUnavailable.erp_message and by the nodes that read a
    business-error body directly, so both read the same keys in the same order
    and a route that moves its message cannot quietly stop being surfaced.

    Returns None rather than a placeholder: the caller's own wording is the
    right fallback, and an empty bubble is worse than a generic sentence.
    """
    if not isinstance(body, dict):
        return None
    for key in ("message", "error", "detail"):
        value = body.get(key)
        if isinstance(value, str) and value.strip():
            return value.strip()
    data = body.get("data")
    if isinstance(data, dict):
        for key in ("message", "error", "detail"):
            value = data.get(key)
            if isinstance(value, str) and value.strip():
                return value.strip()
    return None


# The sentence every node falls back to when erp-api genuinely could not be
# reached. Kept here so the wording has one home and callers can compare
# against it, rather than 35 copies of the same string literal.
UNAVAILABLE_FALLBACK = "I'm unable to reach the HR system right now — please try again shortly."


def unavailable_message(exc: Exception, fallback: str = UNAVAILABLE_FALLBACK) -> str:
    """The right thing to say to the user about a failed erp-api call.

    Prefers erp-api's own message whenever it sent one — a 403's "You can only
    view your own team", a 400's "Invalid date" — and falls back to the
    infrastructure sentence only when there was genuinely no reply (connection
    error, timeout, HTML error page from a proxy).

    This is the difference between telling a manager the HR system is down
    (inviting a pointless retry) and telling them the actual rule they hit.
    """
    message = getattr(exc, "erp_message", None)
    return message or fallback


class ErpApiTimeout(Exception):
    pass


class ErpApiUnavailable(Exception):
    """erp-api could not answer this call.

    Carries the status code and erp-api's own response body when there was
    one. Before this, the exception carried the status in a string and the
    body was written to the call log and nowhere else — so every caller could
    only say "I'm unable to reach the HR system right now", even when erp-api
    had replied with a precise, actionable business reason ("Attendance is
    locked for this date. Contact HR."). That message is wrong twice over: it
    blames infrastructure for a business rule, and it invites a retry of
    something that will never succeed.

    `status_code` is None for the cases where there genuinely was no reply —
    a connection error, or ERP_API_URL not configured.
    """

    def __init__(self, message: str, *, status_code: int | None = None, body=None):
        super().__init__(message)
        self.status_code = status_code
        self.body = body

    @property
    def erp_message(self) -> str | None:
        """erp-api's own user-facing text, when it sent one.

        erp-api answers through sendInfo(), which puts the human-readable
        reason at the top level as `message`; a few routes nest it under
        `data`. Anything else (an HTML error page from a proxy, an empty
        body) yields None and the caller keeps its own wording.
        """
        return extract_erp_message(self.body)


class ErpApiUnauthorized(ErpApiUnavailable):
    """erp-api rejected the forwarded caller token (401). Distinguished from a
    plain ErpApiUnavailable because the two need different user-facing
    messages: a 401 means "log in again", a 5xx/404 means "the HR system is
    down".

    Deliberately a SUBCLASS rather than a sibling. A rejected token does leave
    erp-api unusable for this call, so every existing `except ErpApiUnavailable`
    keeps working and no caller can be surprised by an uncaught 401 — while a
    caller that wants the sharper message just catches ErpApiUnauthorized
    first. Ordering matters: the specific except must come before the general
    one, or the "log in again" message is never reached."""
    pass


# Whether each erp_api_call_logs row also records the exchange's payloads —
# the querystring/body SENT to erp-api and the body RECEIVED back. Those
# carry employee PII (names, attendance status, leave reasons), so the
# capture is a single switch that can be turned off without a code change.
# On by default: the whole point of the column is that the payload is there
# when a wrong-looking card needs explaining, and a flag defaulted off is a
# flag nobody remembers to set until after the incident.
ERP_LOG_PAYLOADS = os.getenv("ERP_LOG_PAYLOADS", "true").strip().lower() not in ("0", "false", "no", "off")

# A ceiling on one stored payload, in serialized characters. A team roster
# response can be large, and an unbounded JSON column turns a log table into
# the reason the disk filled up. Over the ceiling the payload is stored as a
# marked preview rather than dropped: a truncated body still tells you which
# shape came back.
_MAX_LOGGED_PAYLOAD_CHARS = int(os.getenv("ERP_LOG_PAYLOAD_MAX_CHARS", "32000"))

# Credential-shaped keys, blanked wherever they appear in a captured
# payload. The forwarded caller JWT travels in the Authorization header,
# which is never captured at all — this is the second line of defence, for
# the day some endpoint starts taking a token in its body.
_REDACTED_KEYS = {"authorization", "token", "bearer_token", "access_token",
                   "refresh_token", "password", "secret", "api_key", "apikey"}


def _redact(value):
    """A copy of `value` with every credential-shaped key blanked, at any
    depth. Non-container values are returned unchanged."""
    if isinstance(value, dict):
        return {k: ("[redacted]" if str(k).lower() in _REDACTED_KEYS else _redact(v))
                for k, v in value.items()}
    if isinstance(value, list):
        return [_redact(v) for v in value]
    return value


def _capture_payload(value):
    """One payload, ready for a JSON column: redacted, size-capped, and
    round-tripped through json so a stray date/Decimal can't fail the INSERT
    later (when the failure would be attributed to the wrong call). Returns
    None when capture is off or nothing was sent, and a marked stand-in
    rather than raising when the payload can't be serialized at all."""
    if not ERP_LOG_PAYLOADS or value is None:
        return None
    try:
        encoded = json.dumps(_redact(value), default=str)
    except Exception as e:
        # Deliberately broad. default=str already absorbs dates/Decimals, so
        # what is left is the pathological case (a self-referential payload
        # recursing through _redact, a __str__ that raises) — and a logging
        # helper that lets THAT escape would take down the erp-api call it
        # was only supposed to observe.
        return {"_unserializable": f"{type(e).__name__}: {e}"}
    if len(encoded) > _MAX_LOGGED_PAYLOAD_CHARS:
        return {"_truncated": True, "_chars": len(encoded),
                "preview": encoded[:_MAX_LOGGED_PAYLOAD_CHARS]}
    return json.loads(encoded)


def _capture_text(text):
    """The same, for a response that wasn't JSON at all (an HTML error page
    from a proxy in front of erp-api, an empty body). Wrapped in an object
    so the column always holds JSON."""
    if not ERP_LOG_PAYLOADS or not text:
        return None
    raw = str(text)
    if len(raw) > _MAX_LOGGED_PAYLOAD_CHARS:
        return {"_truncated": True, "_chars": len(raw), "raw": raw[:_MAX_LOGGED_PAYLOAD_CHARS]}
    return {"raw": raw}


def _response_payload(resp):
    """erp-api's response body for the log row — parsed JSON where it is
    JSON, the raw text where it isn't. Best-effort by construction: this
    runs on the error paths too, where the body is exactly what you want to
    read afterwards and exactly what nothing else keeps."""
    if not ERP_LOG_PAYLOADS:
        return None
    try:
        return _capture_payload(resp.json())
    except Exception:
        try:
            return _capture_text(resp.text)
        except Exception:
            return None


def _log_call_to_db(method, endpoint, http_status, latency_ms, success, error_code,
                     company_id, conversation_id,
                     request_params=None, request_body=None, response_body=None):
    """Best-effort DB record of one outbound erp-api call — a self-contained
    session (mirrors main.py's _store_server_ip pattern) rather than
    threading a shared db session through hr_graph/leave_action_node. Never
    raises: a logging failure must not break the actual erp-api call.

    The payload arguments default to None so a caller that has nothing to
    record (or runs with ERP_LOG_PAYLOADS off) still writes the same row it
    always did."""
    db = SessionLocal()
    try:
        db.add(ErpApiCallLog(
            method=method,
            endpoint=endpoint,
            http_status=http_status,
            latency_ms=latency_ms,
            success=success,
            error_code=error_code,
            request_params=request_params,
            request_body=request_body,
            response_body=response_body,
            company_id=company_id,
            conversation_id=conversation_id,
        ))
        db.commit()
    except Exception as e:
        db.rollback()
        logger.warning(f"Failed to store erp-api call log: {e}")
    finally:
        db.close()


async def _persist_call_log(**kwargs) -> None:
    try:
        await run_in_threadpool(_log_call_to_db, **kwargs)
    except Exception as e:
        logger.warning(f"erp-api call log threadpool dispatch failed: {e}")


# Fire-and-forget dispatch — logging must never add latency to the erp-api
# call it's recording. A bare asyncio.create_task() with no reference is
# eligible for garbage collection before it runs, so tasks are held here
# just long enough to complete.
_background_log_tasks: set[asyncio.Task] = set()


def _log_call_background(**kwargs) -> None:
    task = asyncio.create_task(_persist_call_log(**kwargs))
    _background_log_tasks.add(task)
    task.add_done_callback(_background_log_tasks.discard)
async def ping(bearer_token: str, company_id=None, conversation_id: str | None = None) -> dict:
    """Forwards the CALLER's own JWT to erp-api — never a stored/minted
    service credential. Never logs the raw token."""
    if not ERP_API_URL:
        raise ErpApiUnavailable("ERP_API_URL not configured")

    url = f"{ERP_API_URL}/api/v1/ai/ping"
    endpoint = "/api/v1/ai/ping"
    logger.info("erp-api call -> GET %s", url)
    start = time.monotonic()
    try:
        resp = await _http.get(url, headers={"Authorization": f"Bearer {bearer_token}"})
    except httpx.TimeoutException as e:
        logger.error("erp-api ping timeout: %s", e)
        await _persist_call_log(method="GET", endpoint=endpoint, http_status=None,
                                 latency_ms=round((time.monotonic() - start) * 1000, 1), success=False,
                                 error_code="TIMEOUT", company_id=company_id, conversation_id=conversation_id)
        raise ErpApiTimeout(str(e)) from e
    except httpx.HTTPError as e:
        logger.error("erp-api ping unreachable: %s", e)
        await _persist_call_log(method="GET", endpoint=endpoint, http_status=None,
                                 latency_ms=round((time.monotonic() - start) * 1000, 1), success=False,
                                 error_code="UNAVAILABLE", company_id=company_id, conversation_id=conversation_id)
        raise ErpApiUnavailable(str(e)) from e

    latency_ms = round((time.monotonic() - start) * 1000, 1)

    if resp.status_code >= 500 or resp.status_code == 401:
        logger.error("erp-api ping returned %s", resp.status_code)
        await _persist_call_log(method="GET", endpoint=endpoint, http_status=resp.status_code,
                                 latency_ms=latency_ms, success=False, error_code="UNAVAILABLE",
                                 company_id=company_id, conversation_id=conversation_id,
                                 response_body=_response_payload(resp))
        raise ErpApiUnavailable(f"erp-api returned {resp.status_code}")

    resp.raise_for_status()

    logger.info("erp-api call <- GET %s | %s | %sms", url, resp.status_code, latency_ms)

    try:
        body = resp.json()
    except ValueError as e:
        logger.error("erp-api ping returned non-JSON body (status=%s): %s", resp.status_code, e)
        await _persist_call_log(method="GET", endpoint=endpoint, http_status=resp.status_code,
                                 latency_ms=latency_ms, success=False, error_code="UNAVAILABLE",
                                 company_id=company_id, conversation_id=conversation_id,
                                 response_body=_capture_text(resp.text))
        raise ErpApiUnavailable(f"erp-api ping returned non-JSON body (status={resp.status_code})") from e

    await _persist_call_log(method="GET", endpoint=endpoint, http_status=resp.status_code,
                             latency_ms=latency_ms, success=True, error_code=None,
                             company_id=company_id, conversation_id=conversation_id,
                             response_body=_capture_payload(body))

    return {
        "latency_ms": latency_ms,
        "http_status": resp.status_code,
        "body": body,
    }

# Connection-level failures worth ONE silent retry. Reported live: an apply-
# flow turn ("full") answered "I'm unable to reach the HR system right now",
# and the identical message sent again a moment later worked. That is the
# signature of a pooled keep-alive connection the server side had already
# closed: the first request on it dies ("Server disconnected without sending
# a response"), the pool opens a fresh one, and the next call is fine - so
# the user was being made to do the retry by hand.
#
# Deliberately narrow:
#   * reads (GET) retry on any of these - repeating a read is harmless;
#   * writes (POST/PUT/PATCH/DELETE - apply, cancel, approve) retry ONLY on
#     ConnectError, where the connection never opened and the request was
#     provably never sent. A dropped connection AFTER sending could mean
#     erp-api already acted, and a second submission would duplicate a leave;
#   * timeouts and HTTP error statuses are never retried: a slow or erroring
#     erp-api must not be hit twice, and callers keep their own messages.
_RETRYABLE_READ_ERRORS = (httpx.ConnectError, httpx.RemoteProtocolError,
                          httpx.ReadError, httpx.WriteError)
_RETRYABLE_WRITE_ERRORS = (httpx.ConnectError,)


async def _send_with_one_retry(method: str, url: str, path: str, request_kwargs: dict):
    retryable = _RETRYABLE_READ_ERRORS if method.upper() == "GET" else _RETRYABLE_WRITE_ERRORS
    try:
        return await _http.request(method, url, **request_kwargs)
    except httpx.TimeoutException:
        raise
    except retryable as e:
        logger.warning("erp-api %s %s connection failed (%s: %s) - retrying once",
                       method, path, type(e).__name__, e)
        return await _http.request(method, url, **request_kwargs)


async def _request(method: str, path: str, bearer_token: str, json_body: dict | None = None,
                    params: dict | None = None, company_id=None, conversation_id: str | None = None,
                    allow_business_error_body: bool = False,
                    allow_404_body: bool = False,
                    allow_403_body: bool = False,
                    allow_422_body: bool = False,
                    timeout_seconds: float | None = None) -> dict:
    """Shared request path for every erp-api call (ping + leave/attendance endpoints) —
    forwards the CALLER's own JWT to erp-api, never a stored/minted service
    credential, and never logs the raw token.

    `params` (querystring) is separate from `json_body` (request body) —
    passed to httpx separately rather than concatenated into `path` — so
    the logged/known route stays a fixed string (e.g.
    "/api/v1/ai/attendance/punch-details") regardless of which date was
    requested, and GET endpoints like /attendance/query?from=...&to=...
    don't need to fake a body.

    allow_business_error_body: when True, a 400 response is returned as data
    instead of raising — erp-api's sendInfo() uses 400 for both validation
    errors and business rules (e.g. "insufficient balance"), and callers
    that opt in surface erp-api's own message instead of a generic failure.
    Any other unexpected status (401/403/404/422/5xx/...) always raises
    ErpApiUnavailable — never silently passed through as a false success,
    unless the caller opts that status in (see allow_422_body below).

    allow_404_body: when True, a 404 is likewise returned as data. Only for
    routes that take a RESOURCE ID in the path: there, a 404 is erp-api
    answering about that one id ("no such pending request", "not yours"),
    which the caller must surface, not the route being unreachable. The fixed,
    no-ID AI routes must NOT opt in — a 404 on those really does mean the
    route isn't deployed, and swallowing it would report a deploy gap as a
    business answer.

    allow_403_body: when True, a 403 is returned as data too. Only for routes
    that take ANOTHER EMPLOYEE as a parameter, where erp-api uses 403 to say
    "you may not look at that person" — a decision it made about the request,
    not a sign it is unwell. Its own wording is the honest answer and the
    caller surfaces it; reporting it as an outage tells the user to retry
    something that will never succeed. Kept separate from
    allow_business_error_body rather than folded into it: the routes already
    using that flag expect 400 to mean a validation/business rule and 403 to
    keep raising, and widening it under them would change what they do.

    allow_422_body: when True, a 422 is returned as data as well. The AI
    MANAGER routes (leave approve, regularization approve) answer a business
    refusal with 422 where the older employee routes use 400 — erp-api's own
    sendInfo() with the rule it enforced, e.g. "Cannot approve this as leave
    count exceed remaining leave for this user" or "Attendance is locked for
    this date. Contact HR." That is erp-api ANSWERING, not erp-api failing.
    Without this flag those refusals raised ErpApiUnavailable and reached the
    manager as "I'm unable to reach the HR system right now", which is both
    wrong and actively misleading: it invites a retry of something that will
    never succeed, and hides the quota rule the manager actually has to act
    on. Kept separate from allow_business_error_body for the same reason
    allow_403_body is: the routes already on that flag expect 422 to keep
    raising, and widening it under them would change what they do.

    timeout_seconds: per-call override of the shared client's default
    (connect=5.0, read=10.0). Some callers have a tighter SLA than that
    default (leave_eligibility_node's 3-second target, for one). Left as None
    for every call that doesn't ask for one, which preserves the client default.
    """

    if not ERP_API_URL:
        raise ErpApiUnavailable("ERP_API_URL not configured")

    url = f"{ERP_API_URL}{path}"
    headers = {"Authorization": f"Bearer {bearer_token}"}
    request_kwargs = {"headers": headers, "json": json_body, "params": params}
    if timeout_seconds is not None:
        request_kwargs["timeout"] = timeout_seconds
    # Captured here, once, so the SENT half of the exchange is on the log row
    # of every outcome below — including the timeout and unreachable paths,
    # where there is no response to pair it with and "what did we ask for"
    # is the only question the row can still answer. `headers` is
    # deliberately not among them: it holds the forwarded caller JWT.
    logged_params = _capture_payload(params)
    logged_body = _capture_payload(json_body)
    logger.info("erp-api call -> %s %s", method, url)
    start = time.monotonic()
    try:
        # **request_kwargs, not the three arguments spelled out again - that
        # is what carries the timeout_seconds override. Spelled out, the
        # kwargs dict was built just above and then dropped on the floor,
        # so every caller asking for a tighter SLA silently got the shared
        # client default instead.
        resp = await _send_with_one_retry(method, url, path, request_kwargs)
    except httpx.TimeoutException as e:
        logger.error("erp-api %s timeout: %s", path, e)
        _log_call_background(method=method, endpoint=path, http_status=None,
                              latency_ms=round((time.monotonic() - start) * 1000, 1), success=False,
                              error_code="TIMEOUT", company_id=company_id, conversation_id=conversation_id,
                              request_params=logged_params, request_body=logged_body)
        raise ErpApiTimeout(str(e)) from e
    except httpx.HTTPError as e:
        logger.error("erp-api %s unreachable: %s", path, e)
        _log_call_background(method=method, endpoint=path, http_status=None,
                              latency_ms=round((time.monotonic() - start) * 1000, 1), success=False,
                              error_code="UNAVAILABLE", company_id=company_id, conversation_id=conversation_id,
                              request_params=logged_params, request_body=logged_body)
        raise ErpApiUnavailable(str(e)) from e

    latency_ms = round((time.monotonic() - start) * 1000, 1)

    # 401 means the caller's own forwarded token was rejected — expired or
    # revoked. Distinct from "erp-api is down": the user can fix it by logging
    # in again, so it keeps its own exception and its own message. Checked
    # ahead of the general non-2xx rule below, which would otherwise fold it
    # into ErpApiUnavailable and tell the employee the HR system is down when
    # all they need to do is sign in again (leave_eligibility_node and the
    # leave action flows both catch this specifically).
    if resp.status_code == 401:
        logger.error("erp-api %s returned 401 (token rejected)", path)
        _log_call_background(method=method, endpoint=path, http_status=resp.status_code,
                              latency_ms=latency_ms, success=False, error_code="UNAUTHORIZED",
                              company_id=company_id, conversation_id=conversation_id,
                              request_params=logged_params, request_body=logged_body,
                              response_body=_response_payload(resp))
        raise ErpApiUnauthorized("erp-api returned 401")

    # Everything else that isn't a 2xx — or an opted-in 400 business error —
    # is treated as erp-api being effectively unavailable for this call. That
    # covers 404 by default: the fixed, no-ID AI-leave routes can only 404 when
    # the route itself isn't reachable (not deployed, wrong ERP_API_URL, proxy
    # misroute), never as a per-resource "not found". Routes that DO carry an
    # id opt out with allow_404_body.
    is_business_error = allow_business_error_body and resp.status_code == 400
    is_resource_404 = allow_404_body and resp.status_code == 404
    is_scope_403 = allow_403_body and resp.status_code == 403
    is_rule_422 = allow_422_body and resp.status_code == 422
    if not (200 <= resp.status_code < 300 or is_business_error or is_resource_404
            or is_scope_403 or is_rule_422):
        logger.error("erp-api %s returned %s", path, resp.status_code)
        # erp-api's own error body goes on the row too — a 403's business
        # message ("I cannot retrieve information for other employees...") is
        # the single most useful thing to read back afterwards, and this is
        # the only place that keeps it: the exception carries the status
        # alone, and the caller never sees the body.
        _log_call_background(method=method, endpoint=path, http_status=resp.status_code,
                              latency_ms=latency_ms, success=False, error_code="UNAVAILABLE",
                              company_id=company_id, conversation_id=conversation_id,
                              request_params=logged_params, request_body=logged_body,
                              response_body=_response_payload(resp))
        # Carry erp-api's own reply on the exception, not just the status.
        # A 403/409/500 here often has a real business message behind it, and
        # the caller needs the chance to say THAT instead of "the HR system is
        # down". Parsing is best-effort: a proxy's HTML error page simply
        # yields no body and the caller falls back to its own wording.
        try:
            _error_body = resp.json()
        except ValueError:
            _error_body = None
        raise ErpApiUnavailable(f"erp-api returned {resp.status_code}",
                                status_code=resp.status_code, body=_error_body)

    logger.info("erp-api call <- %s %s | %s | %sms", method, url, resp.status_code, latency_ms)

    # Defense in depth: even for a 2xx/400 status, the body might not
    # actually be JSON (an HTML error page from a proxy/load balancer in
    # front of erp-api, an empty body, etc). resp.json() raises undecorated
    # ValueError/JSONDecodeError in that case — surfacing that as
    # ErpApiUnavailable (instead of letting it propagate) keeps this within
    # the exception contract every caller already handles, rather than
    # crashing the whole LangGraph run (this exact gap crashed a live
    # /hr-assist-stream request when a 404 briefly slipped past the check
    # above during a deploy gap).
    try:
        body = resp.json()
    except ValueError as e:
        logger.error("erp-api %s returned non-JSON body (status=%s): %s", path, resp.status_code, e)
        _log_call_background(method=method, endpoint=path, http_status=resp.status_code,
                              latency_ms=latency_ms, success=False, error_code="UNAVAILABLE",
                              company_id=company_id, conversation_id=conversation_id,
                              request_params=logged_params, request_body=logged_body,
                              response_body=_capture_text(resp.text))
        raise ErpApiUnavailable(f"erp-api returned non-JSON body (status={resp.status_code})") from e

    # Still a "successful" call from a logging standpoint whenever we get
    # here: erp-api was reached and answered, whatever the business outcome.
    _log_call_background(method=method, endpoint=path, http_status=resp.status_code,
                          latency_ms=latency_ms, success=True, error_code=None,
                          company_id=company_id, conversation_id=conversation_id,
                          request_params=logged_params, request_body=logged_body,
                          response_body=_capture_payload(body))
    return {"http_status": resp.status_code, "latency_ms": latency_ms, "body": body}


async def ping(bearer_token: str, company_id=None, conversation_id: str | None = None) -> dict:
    """Health probe — thin wrapper over _request(). No business-error body
    is expected here, so any non-2xx (401/403/404/5xx/...) raises
    ErpApiUnavailable rather than being passed through."""
    return await _request("GET", "/api/v1/ai/ping", bearer_token,
                           company_id=company_id, conversation_id=conversation_id)


async def get_leave_context(bearer_token: str, company_id=None, conversation_id: str | None = None, employee_name: str | None = None, timeout_seconds: float | None = None) -> dict:
    """{user_id, name, emp_no, is_manager, is_hr, company_id, is_confirmed,
    probation_end_date, doj} — first call per conversation.

    is_manager and is_hr are erp-api's authoritative answer on the caller's
    role, and the reason this call is worth making at all: the JWT names a
    role only for some tokens (many carry role numerically), so the token is
    a fast-path ALLOW and this is the fallback that settles it. Both flags
    are read by hr_graph.manager_gate_node and cached per conversation. There
    is no is_admin here — an administrator is recognisable from the JWT role
    claim only (see dependencies.is_admin_role).

    is_confirmed is erp-api's own
    determination of whether probation/confirmation is complete (null when it
    cannot be determined); leave_eligibility_node relies on it rather than
    deriving it from probation_end_date, so the answer can't drift from what
    applyUsersLeave() enforces.

    `employee_name` may be forwarded by privileged callers (manager lookups).
    """
    params = None
    if employee_name:
        params = {"employee_name": employee_name}
    return await _request("GET", "/api/v1/ai/leave/context", bearer_token,
                           params=params, company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True, timeout_seconds=timeout_seconds)


async def get_leave_balance(bearer_token: str, company_id=None, conversation_id: str | None = None,
                             employee_name: str | None = None, timeout_seconds: float | None = None) -> dict:
    """{leave_quota: {slug: {total, remaining}}, leave_settings}.

    leave_settings.leave_type[] also carries the REGULARIZATION policy
    (slug "regularization": benefit_start, max_apply_in_month,
    regularization_allowed_days). It is not a leave, but every leave flow
    reads leave_type[] as "this company's leave types" — the apply-leave
    "which type?" question, the "what am I eligible for?" list, the probation
    gate — so left there it would be offered as a leave to apply for. It is
    moved to leave_settings.regularization_policy instead (see
    _split_regularization_policy), the one place the regularization code
    reads it from.
    """
    params = None
    if employee_name:
        params = {"employee_name": employee_name}
    result = await _request("GET", "/api/v1/ai/leave/balance", bearer_token,
                            params=params, company_id=company_id, conversation_id=conversation_id,
                            allow_business_error_body=True, timeout_seconds=timeout_seconds)
    _split_regularization_policy(result)
    return result


REGULARIZATION_POLICY_SLUG = "regularization"


def _split_regularization_policy(result) -> None:
    """In place: leave_settings.leave_type[]'s "regularization" entry moved to
    leave_settings.regularization_policy. A response without one is left as
    it was (no regularization_policy key). Never raises — a body of an
    unexpected shape is simply not touched."""
    try:
        settings = ((result or {}).get("body") or {}).get("data", {}).get("leave_settings")
        if not isinstance(settings, dict):
            return
        types = settings.get("leave_type")
        if not isinstance(types, list):
            return
        policy = next((t for t in types
                       if isinstance(t, dict) and t.get("slug") == REGULARIZATION_POLICY_SLUG), None)
        if policy is None:
            return
        settings["leave_type"] = [t for t in types if t is not policy]
        settings["regularization_policy"] = policy
    except (AttributeError, TypeError):
        return


async def apply_leave(
    bearer_token: str,
    leave_type_slug: str,
    from_date: str,
    to_date: str,
    session_type_slug: str | None = None,
    reason: str | None = None,
    employee_name: str | None = None,
    company_id=None,
    conversation_id: str | None = None,
) -> dict:
    """Submits the leave application. Balance/eligibility validation happens
    entirely inside erp-api's existing applyUsersLeave() chain — this is a
    thin passthrough, never a duplicate check."""
    payload = {
        "leave_type_slug": leave_type_slug,
        "from_date": from_date,
        "to_date": to_date,
    }
    if session_type_slug:
        payload["session_type_slug"] = session_type_slug
    if reason:
        payload["reason"] = reason
    if employee_name:
        payload["employee_name"] = employee_name
    return await _request("POST", "/api/v1/ai/leave/apply", bearer_token, json_body=payload,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True)


async def cancel_leave(
    bearer_token: str,
    leave_id,
    cancel_reason: str,
    company_id=None,
    conversation_id: str | None = None,
) -> dict:
    """Cancels one leave request. erp-api validates ownership and
    cancellation eligibility itself and restores the applicable leave balance
    for an approved leave — this is a thin passthrough, never a duplicate
    check. Response data: {leave_id, status, status_name, leave_type_slug,
    leave_count, cancel_reason}. allow_business_error_body=True: an
    ineligible cancellation (already cancelled, locked, past, etc) comes back
    as success=false via the same sendInfo()/400 convention as every other
    leave endpoint, not an exception — that message is surfaced to the
    employee verbatim rather than raising or inventing a different reason."""
    payload = {"leave_id": leave_id, "cancel_reason": cancel_reason}
    return await _request("POST", "/api/v1/ai/leave/cancel", bearer_token, json_body=payload,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True)


async def get_leave_abbreviations(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
) -> dict:
    """{"CL": "Casual Leave", "SL": "Sick Leave", ...} under data — the
    company's own shorthand for its leave and attendance types.

    Configuration, not a fixed list: HA-665's review is explicit that the
    abbreviations an employee may type are whatever the company configured,
    never a table baked into Helix.

    Two things the caller must know about the payload:

    1. It carries ATTENDANCE markers alongside leave types — "A": "Absent",
       "P": "Present", "O": "Off", "NCNS", "R(P)"/"R(A)"/"R(PA)" — and a bare
       "L": "Leave". None of those name a type anyone can apply for, and a
       single loose letter in a leave-type parser is actively dangerous.
    2. Values are not unique: R(PA)/R(A)/R(P) all read "Approved
       Regularization", LC and PA both read "Half Day Absent". Usable as
       abbreviation -> name, never reversed.

    So this is never consumed raw. leave_action_service keeps only the
    entries whose name matches a leave type the company actually has
    CONFIGURED, which discards every item above without needing a list of
    exceptions to maintain.

    Advisory, like the holiday calendar: if it cannot be loaded the caller
    falls back to full names, which is how Helix behaved before this existed.
    """
    return await _request("GET", "/api/v1/ai/leaves/abbreviations", bearer_token,
                           company_id=company_id, conversation_id=conversation_id)


async def get_leave_holidays(bearer_token: str, company_id=None, conversation_id: str | None = None) -> dict:
    """{year, department, total_holidays, holidays: [{id, holiday_name,
    holiday_date, day}]} — the caller's department's holiday calendar.

    Advisory only. It exists so an employee can be told a date is a company
    holiday before they submit, not to decide what erp-api will accept:
    applyUsersLeave() remains the authority, so a failure to load this must
    never block a request the ERP would have taken.
    """
    return await _request("GET", "/api/v1/ai/leave/holidays", bearer_token,
                           company_id=company_id, conversation_id=conversation_id)


async def get_pending_leaves(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
    applied_leave_date: str | None = None,
) -> dict:
    """{leaves: [{id, leave_type, from_date, to_date, status, status_name, reason,
    approver_name, applied_date, total_days}, ...]} — the caller's own PENDING
    leave requests.

    Named for what it returns, not for the intent it used to serve. It was
    called get_leave_status, which collided head-on with the separate
    get_leave_status below (GET /leave/status): two functions, one name, and
    the second silently shadowed the first, so the apply flow's duplicate-date
    pre-check was calling the wrong route. The three leave read paths are now
    one name each — get_pending_leaves (pending only, this one),
    get_applied_leaves (full history, filtered by status) and get_leave_status
    (GET /leave/status).

    erp-api renamed this route from /leave/status to /leave/pending on
    2026-08-18 (confirmed live 2026-08-20 — see get_applied_leaves's
    docstring, which verified leave_status=pending returns identical records
    to this endpoint).

    Unfiltered, this is capped to erp-api's own paginate(20) ordered by id
    (creation order, NOT leave date) — for an account with a long leave
    history, an older application can silently fall off that page even
    though its date is still relevant today. Passing applied_leave_date
    (a single "YYYY-MM-DD") makes erp-api filter server-side to leaves whose
    from_date or to_date matches it, so the 20-row cap only ever has to
    hold matches for that one date — see _find_conflicting_leave, the only
    caller that needs this."""
    params = {"applied_leave_date": applied_leave_date} if applied_leave_date else None
    return await _request("GET", "/api/v1/ai/leave/pending", bearer_token, params=params,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True)


async def get_leave_status(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
    applied_leave_date: str | None = None,
) -> dict:
    """{leaves: [{id, leave_type, from_date, to_date, status, status_name, reason}, ...]}
    — the STATUS of the caller's leave applications, most recent first.

    ⚠️ NO CALLER, AND THE ROUTE MAY NOT EXIST. Kept as its own live function
    (rather than deleted or commented out) so the /leave/status contract has a
    home, but nothing is wired to it and nothing should be until erp-api
    confirms the route is back. Three separate records in this repo say it is
    gone: get_pending_leaves's docstring above (renamed away 2026-08-18,
    confirmed live 2026-08-20), tests/test_ping.py's 404 regression test
    ("this is exactly what happened live when /api/v1/ai/leave/status 404'd"),
    and tests/test_leave_action.py, which pins the duplicate-date check's URL
    to /leave/pending. The one Postman entry that still lists /leave/status
    was last committed 2026-08-18 — the day of the rename — and is missing
    /leave/balance, /leave/cancel, /leave/applied and /leave/pending/teams,
    all of which are live, so it is stale rather than evidence.

    If the route is genuinely 404ing, a call here raises ErpApiUnavailable —
    which _find_conflicting_leave catches and turns into None, i.e. the
    duplicate-date check silently passes. That is precisely what this function
    did while it shared a name with (and shadowed) get_pending_leaves. Wiring
    it up again without verifying the route reintroduces that bug.

    For "what is the status of my leave" today, the live path is
    get_applied_leaves() — GET /api/v1/ai/leave/applied?leave_status=... —
    which serves the leave_status intent and the cancel-leave matcher.

    Unfiltered, this is capped to erp-api's own paginate(20) ordered by id
    (creation order, NOT leave date) — for an account with a long leave
    history, an older application can silently fall off that page even
    though its date is still relevant today. Passing applied_leave_date
    (a single "YYYY-MM-DD") makes erp-api filter server-side to leaves whose
    from_date or to_date matches it, so the 20-row cap only ever has to
    hold matches for that one date."""
    params = {"applied_leave_date": applied_leave_date} if applied_leave_date else None
    return await _request("GET", "/api/v1/ai/leave/status", bearer_token, params=params,
                           company_id=company_id, conversation_id=conversation_id)

# The four values erp-api's `type` query parameter accepts on
# GET /api/v1/ai/team/leaves. "all" is every status the caller may see; the
# other three narrow to one. This is erp-api's OWN vocabulary and belongs
# here rather than in the node — the node's job is mapping a manager's
# wording onto one of these (see services/team_leave_filter.py).
TEAM_LEAVE_STATUS_FILTERS = ("all", "pending", "approved", "cancelled")


async def get_team_leaves(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
    leave_status: str = "pending",
    employee_id: int | None = None, employee_name: str | None = None,
) -> dict:
    """A MANAGER's direct reports' leave requests, filtered by STATUS.

    `leave_status` is one of TEAM_LEAVE_STATUS_FILTERS and becomes the
    endpoint's `type` query parameter:

      pending    -> awaiting the manager's decision (FR-07.1's original scope)
      approved   -> already approved
      cancelled  -> cancelled/withdrawn
      all        -> every status, with BOTH total_leaves and
                    total_pending_leaves present on the response

    Passed as a real querystring parameter rather than baked into the path,
    the same discipline every other call here follows: the logged route stays
    the fixed string "/api/v1/ai/team/leaves" whichever filter was asked for,
    so erp_api_call_logs groups by endpoint instead of fragmenting into four.

    An unknown filter raises ValueError rather than silently querying
    something else — the value is never raw user text (resolve_team_leave_
    status maps wording onto this closed set), so a bad one is a programming
    error and should surface as one.

    Response shape is otherwise identical to the pending-only call this
    generalises; see get_team_pending_leaves for the full field list and for
    the employee_id / employee_name narrowing FR-07.3 uses."""
    if leave_status not in TEAM_LEAVE_STATUS_FILTERS:
        raise ValueError(
            f"leave_status must be one of {TEAM_LEAVE_STATUS_FILTERS}, got {leave_status!r}"
        )
    params = {"type": leave_status}
    if employee_id is not None:
        params["employee_id"] = employee_id
    elif employee_name:
        params["employee_name"] = employee_name
    # allow_403_body is load-bearing here, not belt-and-braces. erp-api
    # refuses a caller who is not HR, admin, or a manager with direct reports
    # with a 403 that CARRIES its reason ("Team leave requests are only
    # available to ... You can still check your own leave requests"). Without
    # the opt-in that 403 raised ErpApiUnavailable, so the caller was told the
    # HR system was unreachable when it had answered them perfectly clearly -
    # and team_leave_query_node's own `http_status == 403` branch, written for
    # exactly this, could never run.
    return await _request("GET", "/api/v1/ai/team/leaves", bearer_token,
                           params=params,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True, allow_403_body=True)


async def get_team_pending_leaves(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
    employee_id: int | None = None, employee_name: str | None = None,
) -> dict:
    """{access_scope, total_pending_leaves, leaves: [{id, employee_id,
    employee_number, employee_name, leave_type, leave_type_slug,
    session_type, session_type_slug, from_date, to_date, leave_count,
    status, status_name, reason, applied_date}, ...]} — a MANAGER's direct
    reports' pending leave requests (FR-07.1).

    Confirmed live against GET /api/v1/ai/leave/pending/teams: erp-api
    returns the full pending list unpaginated (no offset/limit/has_more on
    the wire) — the top-3-by-default ordering/limiting for the chat reply
    is done client-side in team_leave_query_node, not here.

    The same endpoint answers FR-07.3's single-report lookup when narrowed
    by employee_id or employee_name (live-verified). Three response shapes:

      no params        -> the whole team's pending list (team_leave_query_node)
      employee_name=X  -> data.action_required == "select_employee" plus
                          data.search_matched and data.employees[]. NOTE the
                          employee rows here carry only employee_id /
                          employee_number / employee_name - no designation,
                          which FR-07.3 AC2 requires on a selection card.
      employee_id=N    -> that one employee's pending leaves, plus a
                          data.employee = {name, emp_no} sibling.

    A name matching nothing in the caller's team comes back with
    search_matched=false and the FULL team roster - erp-api treats it as
    "pick from your team" rather than a denial, so there is no 403 on this
    path. individual_report_node is what turns that into AC4's denial;
    scope is still erp-api's to define (it only ever searches within the
    caller's own team), this layer just reports what came back.

    Now a thin wrapper over get_team_leaves — the pending list is one value
    of that call's `type` filter. Kept as its own name because FR-07.3's
    single-report lookup reads as "pending leaves for this person" at its
    call sites, and because it is the pending default written down once."""
    return await get_team_leaves(
        bearer_token, company_id=company_id, conversation_id=conversation_id,
        leave_status="pending",
        employee_id=employee_id, employee_name=employee_name,
    )


async def approve_leave_request(
    bearer_token: str, leave_request_id: int,
    company_id=None, conversation_id: str | None = None,
) -> dict:
    """Approves ONE pending leave request the caller manages (FR-07.4).

    POST /api/v1/ai/leave/requests/{id}/approve — the only state-CHANGING
    manager endpoint this client has, which is why it is called from exactly
    one place: leave_approval.py, and only after the manager has explicitly
    confirmed (FR-08.3).

    Team scope is erp-api's to enforce, not ours: it resolves the request
    against the caller's own team hierarchy and refuses anything outside it
    with success=false / "Pending leave request was not found in your team."
    That message is deliberately the same for a request that belongs to
    another team and one that isn't pending any more, so surfacing it
    verbatim confirms nothing about who exists in which team.

    Confirmed contract on success:
      {"success": true, "message": "Leave request approved successfully.",
       "data": {leave_request_id, employee_id, employee_number, employee_name,
                leave_type, leave_type_slug, session_type, session_type_slug,
                from_date, to_date, leave_count, reason, status, status_name,
                applied_date, approved_by: {id, employee_number, name}}}

    Both body opt-ins are set, because every refusal on this route is
    erp-api ANSWERING, not erp-api failing, and leave_approval's
    _execute_approval exists to surface that answer verbatim:

      * allow_business_error_body — the team-scope refusal above comes back
        as a 400 carrying success=false and the message. Without this it
        raised ErpApiUnavailable, so the manager was told the HR system was
        unreachable when it had in fact declined them, and the "erp-api
        refused approval" branch could never run.
      * allow_404_body — this route takes an id, so unlike the fixed
        AI-leave routes a 404 is an answer about one resource ("no such
        pending request"), not the route being unreachable.
      * allow_422_body — the rules erp-api enforces INSIDE the approval come
        back as a 422 carrying success=false and the rule it hit, the live
        one being "Cannot approve this as leave count exceed remaining leave
        for this user" (also the monthly-max and attendance-lock refusals).
        This controller answers business refusals with 422 where the older
        employee routes use 400, so without it a manager who approved a
        request over the employee's remaining balance was told the HR system
        was unreachable instead of being told the balance was short.

    There is NO reject/deny counterpart on erp-api yet, and none is called
    from anywhere: rejection is a separate story (see leave_approval.py's
    AC5 handling), and adding a client method for it before that endpoint
    exists is how a half-built path gets wired up by accident.
    """
    return await _request(
        "POST", f"/api/v1/ai/leave/requests/{int(leave_request_id)}/approve",
        bearer_token, company_id=company_id, conversation_id=conversation_id,
        allow_business_error_body=True, allow_404_body=True, allow_422_body=True,
    )


async def reject_leave_request(
    bearer_token: str, leave_request_id: int, rejection_reason: str,
    company_id=None, conversation_id: str | None = None,
) -> dict:
    """Rejects ONE pending leave request the caller manages.

    POST /api/v1/ai/leave/requests/{id}/reject - the sibling of
    approve_leave_request, and the second of the two state-CHANGING manager
    routes. Called from exactly one place, leave_approval.py, and only after
    the manager has explicitly confirmed (FR-08.3).

    rejection_reason is REQUIRED by erp-api (3-500 chars) and is not defaulted
    here: a rejection the employee cannot see a reason for is the outcome this
    flow most needs to avoid, and inventing a placeholder to satisfy the
    validator would produce exactly that.

    Same opt-ins as approve: erp-api answers a refusal with a business-error
    body (400 on the older routes, 422 on this manager controller) or an
    id-scoped 404, all of which are answers to surface rather than outages
    to raise.
    """
    return await _request(
        "POST", f"/api/v1/ai/leave/requests/{int(leave_request_id)}/reject",
        bearer_token, json_body={"rejection_reason": rejection_reason},
        company_id=company_id, conversation_id=conversation_id,
        allow_business_error_body=True, allow_404_body=True, allow_422_body=True,
    )


async def get_team_members(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
) -> dict:
    """{access_scope, total_members, members: [{employee_id, employee_number,
    employee_name, employee_designation, employee_email, relation}]} - the
    caller's own team roster.

    GET /api/v1/ai/leave/team/members. Scope is erp-api's call and matches
    get_team_pending_leaves exactly (HR/admin see the company, a manager sees
    their direct reports), so "who is on my team" and "what is my team waiting
    on" can never disagree about who the team is. A caller with no reports is
    refused there with a 403 rather than shown an empty list.
    """
    # Same gap as get_team_leaves above, and for the same reason: the refusal
    # this docstring describes IS a 403 with a message, so it has to come back
    # as data rather than as an outage.
    return await _request("GET", "/api/v1/ai/leave/team/members", bearer_token,
                          company_id=company_id, conversation_id=conversation_id,
                          allow_business_error_body=True, allow_403_body=True)


async def get_team_attendance_summary(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
    date: str | None = None,
) -> dict:
    """{type, date, scope, summary_cards: {total_team, present, absent,
    on_leave, missing_punches: {..., missed_punch_count}}, breakdown:
    {attendance_recorded, not_recorded, off}, missing_punch_details:
    {employee_count, incomplete_session_count, missing_check_ins,
    missing_check_outs, missed_punch_count, employees: [...]}} — a
    MANAGER's team-level attendance summary for one date (FR-07.2).

    Confirmed live against GET /api/v1/ai/attendance/summary: `date`
    (a "YYYY-MM-DD" query param) selects the day; omitted, erp-api
    defaults to today in its own server timezone — but resolving "today"
    from the query (including defaulting when the query names no date at
    all, AC#4) is team_attendance_summary_node's job, using the app's own
    configured timezone, same division of responsibility already
    established for get_team_pending_leaves/get_leave_status."""
    params = {"date": date} if date else None
    # allow_403_body / allow_business_error_body: erp-api answers a
    # non-manager (or a manager asking outside their reporting line) with a
    # 403 carrying its own explanation, and rejects a bad date with a 400.
    # Both are erp-api ANSWERING, not erp-api failing. Without these flags
    # they raised ErpApiUnavailable and the manager was told "I'm unable to
    # reach the HR system right now" — and team_attendance_summary_node's own
    # `if result["http_status"] == 403` branch was unreachable dead code,
    # because the 403 never got far enough to be returned.
    return await _request("GET", "/api/v1/ai/attendance/summary", bearer_token,
                           params=params, company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True, allow_403_body=True)


async def get_active_shift(bearer_token: str, company_id=None, conversation_id: str | None = None,
                            employee_id: int | None = None, employee_name: str | None = None) -> dict:
    """{shift: {shift_id, shift_name, start_time, end_time, ...}} for the
    target employee's currently-active shift assignment, or an empty/absent
    shift when none is assigned (see shift_query.py's AC4 "No Active Shift
    Assigned" handling). Response also carries employee/assignment/
    work_calendar siblings alongside "shift" that this flow doesn't use.

    Passing employee_id or employee_name looks up that employee instead of
    the caller. erp-api enforces on its own whether the caller's role is
    allowed to view another employee's shift, and a disallowed or unknown
    target is erp-api ANSWERING — live-verified as 403 +
    {"success": false, "message": "I cannot retrieve information for other
    employees..."} — so both body opt-ins are set and shift_query_node
    surfaces that message the way it surfaces any other business failure.

    Both are load-bearing, not belt-and-braces. Without them _request's
    "any non-2xx is an outage" rule turned every one of those answers into
    ErpApiUnavailable, and a manager asking about a colleague erp-api had
    declined — or an employee code that doesn't exist — was told "I'm unable
    to reach the HR system right now", i.e. to retry something that could
    never succeed. This is the same gap that was found and closed on
    approve_leave_request (see its docstring); this route was missed because
    the tests that cover the refusal wording stub get_active_shift itself and
    so never exercise _request's status handling at all.

    404 is deliberately NOT opted into: this is a fixed, no-ID route, so a
    404 really does mean it isn't reachable, per _request's own rule.

    Omit both params (the default) for the caller's own shift."""
    params = {}
    if employee_id is not None:
        params["employee_id"] = employee_id
    elif employee_name:
        params["employee_name"] = employee_name
    return await _request("GET", "/api/v1/ai/shift-details", bearer_token,
                           params=params or None,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True, allow_403_body=True)


async def get_attendance_punch_details(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
    employee_id: int | None = None, employee_name: str | None = None,
    attendance_date: str | None = None,
) -> dict:
    """GET /api/v1/ai/attendance/punch-details - the recorded attendance for
    ONE employee on ONE day (FR-07.3). LIVE; this replaced the fixtures that
    stood in while erp-api had no such route.

    Live-verified response shape:
      {requested_date, logical_shift_date,
       shift: {id, name, start_time, end_time, week_off_days, relief_time, status},
       attendance: {attendance, attendance_remark, working_type, reason,
                    is_regularized} | null,
       punch_status, punch_count,
       punches: [{punch_number, check_in, check_out, complete, missing}],
       work_hours: {available, value, source, reason}}

    Two things this endpoint does NOT return, which shape the caller:
      * No "employee" block at all - nothing in the response says whose day
        this is, so the subject's name has to be carried from whatever
        resolved the employee_id (see individual_report_node).
      * No policy rule and no explanation factors. It reports the recorded
        status and the punch evidence; it does not explain the ruling. The
        renderer states the evidence and never invents a rule.

    attendance is null (with punch_status "no_records") for a day with no
    punches - including any past or future date with nothing on file, which
    comes back 200, not 404.

    Omit both employee params for the CALLER's own record - unlike
    /shift-details, this endpoint serves that happily for a manager too.
    employee_name is supported and answers with the same select_employee /
    search_matched shape as the leave endpoints. An out-of-team (or the
    manager's own) employee_id comes back 403 with a business message; an
    unparseable date comes back 400 with Laravel's field-validation body
    ({"date": ["The date field must match the format Y-m-d."]}), which is a
    validation shape, not the data shape - the caller must not read it as
    attendance.

    allow_403_body is load-bearing, not belt-and-braces - the same gap that
    was already found and closed on get_active_shift. erp-api's
    AiAuthorizeEmployee middleware answers 403 for an employee_id that is
    outside the caller's team OR does not exist at all, which is erp-api
    ANSWERING, not erp-api being unwell. Without the opt-in, _request's
    "any non-2xx is an outage" rule turned that answer into
    ErpApiUnavailable, so a manager asking "why was emp id 615 marked
    half-day" about an id that resolves to nobody was told "I'm unable to
    reach the HR system right now" - i.e. to retry something that can never
    succeed - instead of individual_report_node's AC4 denial. The 403 branch
    that node already has for exactly this case was unreachable.

    400 is deliberately NOT opted into: on this route it is Laravel's
    field-validation body, which is not the data shape, so letting it
    through would hand the caller a validation dict to read as attendance.
    404 is not opted into either - this is a fixed, no-ID route, so a 404
    really does mean it isn't reachable, per _request's own rule.
    """
    params = {"date": attendance_date} if attendance_date else {}
    if employee_id is not None:
        params["employee_id"] = employee_id
    elif employee_name:
        params["employee_name"] = employee_name
    return await _request("GET", "/api/v1/ai/attendance/punch-details", bearer_token,
                          params=params or None,
                          company_id=company_id, conversation_id=conversation_id,
                          allow_403_body=True)


async def get_attendance_status_range(
    bearer_token: str, company_id=None, conversation_id: str | None = None,
    from_date: str | None = None, to_date: str | None = None,
    employee_id: int | None = None, employee_name: str | None = None,
) -> dict:
    """GET /api/v1/ai/attendance/query?from=&to= - the day-by-day attendance
    STATUS over a date range.

    Live-verified shape:
      {type: "single"|"daily", from, to, total_days,
       records: [{date, day, status}, ...]}

    This is the companion to get_attendance_punch_details, and the reason
    both are called: punch-details carries the evidence (shift, punches,
    hours) but names the status only as an internal code plus a remark
    ("O" / "Off2"); this endpoint is where the word a person would
    recognise lives ("Present", "Off", "Absent", "Not Recorded" are the
    values seen so far). Asking "why was X marked absent" and answering
    with a code is the gap this closes.

    Same permission and disambiguation semantics as the other employee-
    scoped endpoints: employee_id for a report, employee_name answering
    with the select_employee / search_matched shape, 403 for an employee
    outside the caller's scope. A missing, unparseable or reversed range
    is a 422 "Invalid attendance query." - a validation shape, not the
    data shape.

    Both dates are required; pass the same value twice for one day, which
    comes back as type "single" with a single record.

    allow_403_body for the same reason as its companion above: the 403 is
    erp-api deciding about the named employee, not an outage. The only
    caller (individual_report._fetch_status_record) already reads
    http_status == 403 out of the result, which was unreachable while the
    status raised instead.
    """
    params = {}
    if from_date:
        params["from"] = from_date
    if to_date:
        params["to"] = to_date
    if employee_id is not None:
        params["employee_id"] = employee_id
    elif employee_name:
        params["employee_name"] = employee_name
    return await _request("GET", "/api/v1/ai/attendance/query", bearer_token,
                          params=params or None,
                          company_id=company_id, conversation_id=conversation_id,
                          allow_403_body=True)







async def get_punch_details(bearer_token: str, date: str | None = None,
                             company_id=None, conversation_id: str | None = None) -> dict:
    """{success, message, data: {requested_date, shift: {name, start_time,
    end_time}, punch_status, punch_count, punches: [{check_in, check_out,
    complete}, ...], work_hours: {available, value}}}
    — confirmed live against a real employee record; the punch
    list comes back under "punches".

    allow_business_error_body=True — erp-api answers a date it will not serve
    (malformed, outside the retention window, locked) with a 400 carrying its
    own reason. Without the flag that raised ErpApiUnavailable and the employee
    was told the attendance system was unreachable, which is both wrong and
    unactionable. Deliberately NOT opting into allow_404_body: this is a fixed,
    no-ID AI route, so a 404 here really does mean the route isn't deployed
    (see _request's own docstring) — swallowing that would report a deploy gap
    as a business answer.
    """
    return await _request("GET", "/api/v1/ai/attendance/punch-details", bearer_token,
                           params={"date": date} if date else None,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True,
    )


async def get_attendance_explanation(
    bearer_token: str, date: str, company_id=None, conversation_id: str | None = None,
) -> dict:
    """Pre-evaluated explanation parameters from the Attendance Rule Engine for
    one calendar day. Thin passthrough only — helixta-api never computes
    attendance rules, grace periods, or classification logic itself; callers
    render whatever this returns."""
    return await _request("GET", f"/api/v1/ai/attendance/explain?date={date}", bearer_token,
                           company_id=company_id, conversation_id=conversation_id)


async def get_attendance_status(
    bearer_token: str, from_date: str, to_date: str, company_id=None, conversation_id: str | None = None,
) -> dict:
    """The caller's day-by-day attendance STATUS (Present/Half Day/Late/Absent/...)
    for a date range — real erp-api endpoint, confirmed contract."""
    return await _request(
        "GET", f"/api/v1/ai/attendance/query?from={from_date}&to={to_date}", bearer_token,
        company_id=company_id, conversation_id=conversation_id,
    )


async def get_attendance_query(
    bearer_token: str,
    from_date: str,
    to_date: str,
    company_id=None,
    conversation_id: str | None = None,
    employee_name: str | None = None,
) -> dict:
    """GET /api/v1/ai/attendance/query?from=...&to=...

    Thin passthrough, same discipline as apply_leave(): no reshaping or
    duplicate range-length logic on our side."""
    params = {"from": from_date, "to": to_date}
    if employee_name:
        params["employee_name"] = employee_name

    return await _request("GET", "/api/v1/ai/attendance/query", bearer_token,
                           params=params, company_id=company_id, conversation_id=conversation_id)


async def get_punch_time(
    bearer_token: str,
    company_id=None,
    conversation_id: str | None = None,
    date: str | None = None,
    employee_name: str | None = None,
) -> dict:
    """Returns punch details for the given date (YYYY-MM-DD), or today's if date is omitted.
    employee_name forwards a privileged (manager/HR) lookup of someone else's record — omitted for a caller checking their own."""
    params = {"date": date} if date else {}
    if employee_name:
        params["employee_name"] = employee_name
    if not params:
        params = None

    return await _request(
        "GET",
        "/api/v1/ai/attendance/punch-details",
        bearer_token,
        company_id=company_id,
        conversation_id=conversation_id,
        params=params,
    )

async def post_regularization(
    bearer_token: str,
    *,
    payload: dict,
    company_id=None,
    conversation_id: str | None = None,
) -> dict:
    """Submits an attendance regularization request. Thin passthrough.

    allow_business_error_body=True — erp-api uses 400 for both validation
    errors and business-rule rejections (e.g. "already regularized",
    "outside the allowed window"), same as get_applied_leaves below. Without
    this, a 400 raised ErpApiUnavailable with no body, discarding erp-api's
    real reason and leaving regularisation_node's already-wired
    _extract_failure_message() unreachable — the employee saw a generic
    "couldn't reach the HR system" instead of why the request was rejected."""
    # allow_422_body: erp-api answers its business rules with 422 on its other
    # AI routes ("Attendance is locked for this date. Contact HR."), and a
    # rule answered that way here — "Regularization period has expired" —
    # is an answer, not an outage. Returned as data, it reaches
    # _extract_failure_message like the 400 does.
    return await _request("POST", "/api/v1/ai/apply/regularization", bearer_token, json_body=payload,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True, allow_422_body=True)


# Status filter values GET /api/v1/ai/regularizations accepts. "all" is sent
# explicitly for an unfiltered list. Anything else becomes "all" rather than
# being forwarded, so a typo'd filter can never empty the list silently.
REGULARIZATION_STATUS_ALL = "all"
REGULARIZATION_STATUS_FILTERS = ("pending", "approved", "rejected", "cancelled")


async def get_my_regularizations(
    bearer_token: str,
    company_id=None,
    conversation_id: str | None = None,
    status: str | None = None,
    timeout_seconds: float | None = None,
) -> dict:
    """{total_pending_regularizations, total_approved_regularizations,
    total_cancelled_regularizations, total_rejected_regularizations,
    total_regularizations, regularizations: [{regularization_id, applied_to,
    action_by, created_at, employee_id, employee_number, employee_name,
    apply_date, from_time, to_time, reason, status, status_name}, ...]} —
    the CALLER's OWN attendance regularization requests, most recently
    applied first (created_at, then id — NOT apply_date order).

    created_at is the applied-on date. There is no separate regularization
    type: reason is what the employee gave as it.

    GET /api/v1/ai/regularizations with NO type param. erp-api reshaped this
    route (HA-697): with no params it now answers the caller's own requests,
    and the manager's team queue moved behind type=all (see
    get_pending_regularizations below). It replaced /api/v1/ai/my/
    regularizations.

      status=all     -> every status, with every total_* count (the default)
      status=<name>  -> just that status; the total_* counts follow the filter

    status is ALWAYS sent — "all" when none (or an unknown one) is given.

    Two readers: my_regularisation_view_node (the history, HA-697 AC-01) and
    regularisation_node's duplicate-date check (AC-03), which asks for every
    status because a Rejected/Cancelled request on the date matters too.
    """
    status = (status or "").strip().lower()
    if status not in REGULARIZATION_STATUS_FILTERS:
        status = REGULARIZATION_STATUS_ALL
    params = {"status": status}
    return await _request("GET", "/api/v1/ai/regularizations", bearer_token,
                           params=params,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True, allow_422_body=True,
                           timeout_seconds=timeout_seconds)


async def get_pending_regularizations(
    bearer_token: str,
    employee_id: int | None = None,
    company_id=None,
    conversation_id: str | None = None,
) -> dict:
    """{total_pending_regularizations, regularizations: [{regularization_id,
    employee_id, employee_number, employee_name, apply_date, from_time,
    to_time, reason, status, status_name}, ...]} — the PENDING attendance
    regularization requests a manager's own direct reports have raised.

    GET /api/v1/ai/regularizations?type=all&status=pending. The read half of
    the manager regularization flow, and the sibling of get_team_pending_leaves — same
    scope discipline: erp-api resolves the list against the CALLER's own
    hierarchy, so a manager only ever sees their own direct reports and
    another manager's team is not reachable from here by any parameter.
    That boundary is erp-api's to enforce, not ours; this layer never widens
    it and never re-derives who reports to whom.

    Always the WHOLE team: erp-api does not narrow type=all by employee id
    or name. employee_id is accepted for the caller's convenience and never
    sent — regularisation_approval filters the returned rows by it.

    type=all and status=pending are ALWAYS sent. Since HA-697 the bare route
    answers the caller's OWN requests, every status; without type=all this
    queue would list the manager's own regularizations as if they were their
    team's, and without status=pending it would offer approved and cancelled
    rows for approval. erp-api still applies the role gate on type=all (a
    non-manager gets 403), so the scope guarantee below is unchanged.

    Unlike the pending-leave route there is NO employee_name search either;
    a name is matched against the returned rows' employee_name/
    employee_number, which keeps the same scope guarantee since the rows are
    erp-api's own statement of who the caller manages.

    Rows since HA-697 also carry applied_to, action_by and created_at (the
    applied-on date).

    Rows come back newest-first and unpaginated (no offset/limit/has_more on
    the wire), so any capping for a chat reply is done client-side in
    regularisation_approval.py, exactly as team_leave_query_node does for
    leaves.
    """
    params = {"type": "all", "status": "pending"}
    return await _request("GET", "/api/v1/ai/regularizations", bearer_token,
                           params=params,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True, allow_403_body=True)


# erp-api's regularization-approve route validates `browser_id` as a required
# string, inherited from the web app's own approve form. NOTHING downstream
# reads it: UsersLeaveRepository::updateUsersRegularization derives the real
# browser_id from the employee's attendance record (or a literal fallback when
# they have none), and never looks at the request field. Omitting it still
# failed the validator, so every approval from here came back
# "The browser id field is required." and no request could be approved at all.
# Sent as a fixed identifier that says which client acted, rather than a
# fabricated browser fingerprint.
_AI_ASSIST_BROWSER_ID = "helixta-ai-assistant"


async def approve_regularization(
    bearer_token: str, regularization_id: int,
    company_id=None, conversation_id: str | None = None,
) -> dict:
    """Approves ONE pending regularization request the caller manages.

    POST /api/v1/ai/regularization/approve, with the id in the BODY
    ({"regularization_id": N}) rather than the path — the one shape
    difference from approve_leave_request, which takes it as a path segment.

    Like its leave counterpart this is a state-CHANGING manager route, so it
    has exactly one call site — regularisation_approval._execute_approval —
    reached only from a stored confirmation a PREVIOUS turn armed (FR-08.3).

    Confirmed contract on success:
      {"success": true, "message": "Regularization request approved successfully.",
       "data": {regularization_id, employee_id, status, status_name}}

    The body opt-ins are set for the same reason approve_leave_request sets
    them: a refusal here is erp-api ANSWERING (the request is not pending any
    more, or belongs to another manager's team), not erp-api failing, and the
    node's job is to surface that answer verbatim rather than report an
    outage. allow_404_body applies even though the id travels in the body —
    what matters is that the route is id-scoped, so a 404 is about that one
    resource and not about the route being undeployed. allow_422_body is set
    for the same reason it is on approve_leave_request: this controller
    answers its own rules with 422 ("Attendance is locked for this date.
    Contact HR.", and anything the repository refuses), and those are
    answers, not outages.
    """
    return await _request(
        "POST", "/api/v1/ai/regularization/approve", bearer_token,
        json_body={"regularization_id": int(regularization_id),
                   "browser_id": _AI_ASSIST_BROWSER_ID},
        company_id=company_id, conversation_id=conversation_id,
        allow_business_error_body=True, allow_404_body=True, allow_422_body=True,
    )


async def reject_regularization(
    bearer_token: str, regularization_id: int, rejection_reason: str,
    company_id=None, conversation_id: str | None = None,
) -> dict:
    """Rejects ONE pending regularization request the caller manages.

    POST /api/v1/ai/regularization/reject
      {"regularization_id": N, "rejection_reason": "..."}

    Confirmed contract on success:
      {"success": true, "message": "Regularization request rejected successfully.",
       "data": {regularization_id, employee_id, status: 2, status_name: "rejected",
                rejection_reason, action_by}}

    Manager/HR/Admin only, own team only - both enforced by erp-api. One call
    site (regularisation_approval._execute_rejection), reached only from a
    stored confirmation a PREVIOUS turn armed (FR-08.3). Body opt-ins as
    approve_regularization: a refusal is erp-api answering, not failing.
    browser_id is sent for the same reason it is on approve: the web form's
    validator family requires it, and an unread extra field costs nothing.
    """
    return await _request(
        "POST", "/api/v1/ai/regularization/reject", bearer_token,
        json_body={"regularization_id": int(regularization_id),
                   "rejection_reason": rejection_reason,
                   "browser_id": _AI_ASSIST_BROWSER_ID},
        company_id=company_id, conversation_id=conversation_id,
        allow_business_error_body=True, allow_404_body=True, allow_422_body=True,
    )


async def cancel_regularization(
    bearer_token: str, regularization_id: int, cancel_reason: str,
    company_id=None, conversation_id: str | None = None,
) -> dict:
    """Cancels ONE of the CALLER'S OWN regularization requests.

    POST /api/v1/ai/regularization/cancel
      {"regularization_id": N, "cancel_reason": "..."}

    Confirmed contract on success:
      {"success": true, "message": "Regularization request cancelled successfully.",
       "data": {regularization_id, status: 3, status_name: "cancelled", cancel_reason}}

    Every role may call it; erp-api allows only the caller's own requests and
    owns every status rule (which statuses can still be cancelled), so its
    refusal is passed back verbatim. One call site
    (regularisation_cancel._execute_cancel), reached only from a stored
    confirmation a PREVIOUS turn armed.
    """
    return await _request(
        "POST", "/api/v1/ai/regularization/cancel", bearer_token,
        json_body={"regularization_id": int(regularization_id),
                   "cancel_reason": cancel_reason,
                   "browser_id": _AI_ASSIST_BROWSER_ID},
        company_id=company_id, conversation_id=conversation_id,
        allow_business_error_body=True, allow_404_body=True, allow_403_body=True,
        allow_422_body=True,
    )


async def get_applied_leaves(
    bearer_token: str,
    leave_status: str = "all",
    company_id=None,
    conversation_id: str | None = None,
    applied_leave_date: str | None = None,
) -> dict:
    """{leave_status, total_leaves, leaves: [...] } — the caller's own applied
    leave requests, filtered by leave_status (pending/approved/cancelled/rejected/all).

    Both values travel as real querystring parameters rather than baked into
    the path — the discipline get_team_leaves documents, so the logged route
    stays the fixed string "/api/v1/ai/leave/applied" instead of fragmenting
    erp_api_call_logs into one row-group per filter. That is not cosmetic
    here: httpx REPLACES a URL's existing query string when `params` is
    passed (verified against httpx 0.28.1), so leaving leave_status baked
    into the path and adding params would have silently dropped it and turned
    every scoped call into erp-api's default filter.

    applied_leave_date ("YYYY-MM-DD") asks erp-api to filter server-side to
    leaves whose from_date or to_date matches that day — the same parameter
    get_pending_leaves takes, for the same reason: an unfiltered response is
    capped to erp-api's own paginate(20) ordered by id (creation order, NOT
    leave date), so on an account with enough history an older leave for the
    requested date falls off the window and a caller looking for it sees
    nothing. See _find_conflicting_leave, the only caller that passes it.
    """
    params = {"leave_status": leave_status}
    if applied_leave_date:
        params["applied_leave_date"] = applied_leave_date
    return await _request("GET", "/api/v1/ai/leave/applied", bearer_token,
                           params=params,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True)
