"""services/attendance_client.py

The only place that knows about URLs/mock vs live for attendance.

erp-api exposes ONE endpoint for attendance:

    GET /api/v1/ai/attendance/query?from=YYYY-MM-DD&to=YYYY-MM-DD

which returns either a day-wise ("daily") payload or an aggregate
("summary") payload depending on the size of the range — see erp_client.
get_attendance_query()'s docstring.

attendance.py (the graph node), however, wants three distinct calls —
get_attendance_single / get_attendance_range / get_attendance_summary —
each shaped the way its formatting helpers already expect. This module is
the adapter: it always calls the one real erp-api endpoint and reshapes
the response per call-site, so attendance.py never has to know that
"single" and "range" are really the same "daily" response under the hood,
or that erp-api's summary field names don't match ours.

Exceptions (ErpApiTimeout / ErpApiUnavailable / ErpApiUnauthorized) are
erp_client's own classes, re-exported here unchanged so attendance.py's
`except attendance_client.ErpApiTimeout` continues to work without needing
to import erp_client directly.
"""
from datetime import date

import services.erp_client as erp_client

# Re-exported so callers can catch attendance_client.ErpApiTimeout /
# attendance_client.ErpApiUnavailable / attendance_client.ErpApiUnauthorized
# without reaching into erp_client.
ErpApiTimeout = erp_client.ErpApiTimeout
ErpApiUnavailable = erp_client.ErpApiUnavailable
ErpApiUnauthorized = erp_client.ErpApiUnauthorized


def _iso(d: date) -> str:
    return d.strftime("%Y-%m-%d")


def _name_match_fields(data: dict) -> dict:
    """erp-api answers an employee_name lookup that doesn't match anyone in
    the caller's scope with search_matched=False (plus action_required and
    a candidates list), same shape documented on get_attendance_status_range
    and the leave/punch-details endpoints — surfaced here so attendance.py
    can tell "no employee found" apart from "found them, no records this
    period" instead of both silently looking like empty attendance."""
    fields = {}
    if "search_matched" in data:
        fields["search_matched"] = data.get("search_matched")
    if "action_required" in data:
        fields["action_required"] = data.get("action_required")
    if "employees" in data:
        fields["employees"] = data.get("employees")
    return fields


async def get_attendance_single(
    bearer_token: str,
    target_date: date,
    company_id=None,
    conversation_id: str | None = None,
    employee_name: str | None = None,
) -> dict:
    """One-day lookup. erp-api has no dedicated single-day endpoint, so we
    call /attendance/query with from == to (always <=31 days -> "daily")
    and pull the one record out."""
    date_str = _iso(target_date)
    result = await erp_client.get_attendance_query(
        bearer_token, from_date=date_str, to_date=date_str,
        company_id=company_id, conversation_id=conversation_id,
        employee_name=employee_name,
    )
    body = result["body"]
    data = body.get("data", {}) or {}
    records = data.get("records", [])
    status = records[0].get("status") if records else None

    return {
        "success": body.get("success", True),
        "message": body.get("message"),
        "data": {"status": status, **_name_match_fields(data)},
    }


async def get_attendance_range(
    bearer_token: str,
    start_date: date,
    end_date: date,
    company_id=None,
    conversation_id: str | None = None,
    employee_name: str | None = None,
) -> dict:
    """Range lookup, span already confirmed <=31 days by the caller
    (attendance_node), so erp-api is expected to answer with
    type == "daily". We pass records through as-is — _format_date_range
    only reads record["date"] / record["status"]."""
    result = await erp_client.get_attendance_query(
        bearer_token, from_date=_iso(start_date), to_date=_iso(end_date),
        company_id=company_id, conversation_id=conversation_id,
        employee_name=employee_name,
    )
    body = result["body"]
    data = body.get("data", {}) or {}

    return {
        "success": body.get("success", True),
        "message": body.get("message"),
        "data": {"records": data.get("records", []), **_name_match_fields(data)},
    }


async def get_attendance_summary(
    bearer_token: str,
    start_date: date,
    end_date: date,
    company_id=None,
    conversation_id: str | None = None,
    employee_name: str | None = None,
) -> dict:
    """Long-range lookup (>31 days), erp-api is expected to answer with
    type == "summary". erp-api's summary keys (present/absent/leave/...)
    are remapped to the *_count keys _format_long_range_summary reads,
    and navigation is passed through in case a future revision of the
    node wants the "View Attendance" deep link."""
    result = await erp_client.get_attendance_query(
        bearer_token, from_date=_iso(start_date), to_date=_iso(end_date),
        company_id=company_id, conversation_id=conversation_id,
        employee_name=employee_name,
    )
    body = result["body"]
    data = body.get("data", {}) or {}
    summary = data.get("summary", {}) or {}
    navigation = data.get("navigation", {}) or {}

    return {
        "success": body.get("success", True),
        "message": body.get("message"),
        "data": {
            "present_count": summary.get("present", 0),
            "absent_count": summary.get("absent", 0),
            "leave_count": summary.get("leave", 0),
            "half_day_absent_count": summary.get("half_day_absent", 0),
            "off_count": summary.get("off", 0),
            "regularized_count": summary.get("regularized", 0),
            "not_recorded_count": summary.get("not_recorded", 0),
            "upcoming_count": summary.get("upcoming", 0),
            "navigation": navigation,
            **_name_match_fields(data),
        },
    }

