import os
import time
import asyncio
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)

# 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),
)


class ErpApiTimeout(Exception):
    pass


class ErpApiUnavailable(Exception):
    pass


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


def _log_call_to_db(method, endpoint, http_status, latency_ms, success, error_code, company_id, conversation_id):
    """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."""
    db = SessionLocal()
    try:
        db.add(ErpApiCallLog(
            method=method,
            endpoint=endpoint,
            http_status=http_status,
            latency_ms=latency_ms,
            success=success,
            error_code=error_code,
            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 _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,
                    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.

    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
    logger.info("erp-api call -> %s %s", method, url)
    start = time.monotonic()
    try:
        resp = await _http.request(method, url, **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)
        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)
        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)
        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 too: these 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".
    is_business_error = allow_business_error_body and resp.status_code == 400
    if not (200 <= resp.status_code < 300 or is_business_error):
        logger.error("erp-api %s returned %s", path, resp.status_code)
        _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)
        raise ErpApiUnavailable(f"erp-api returned {resp.status_code}")

    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)
        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)
    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, is_manager, company_id, is_confirmed, probation_end_date,
    doj} — first call per conversation. 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}."""
    params = None
    if employee_name:
        params = {"employee_name": employee_name}
    return 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)


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_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_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,
    approver_name, applied_date, total_days}, ...]} — the caller's own PENDING
    leave requests. 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); a merge briefly
    reintroduced the old /leave/status path here, which no longer exists.

    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_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".
    """
    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,
    )


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."""
    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)


async def get_applied_leaves(
    bearer_token: str,
    leave_status: str = "all",
    company_id=None,
    conversation_id: 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)."""
    return await _request("GET", f"/api/v1/ai/leave/applied?leave_status={leave_status}", bearer_token,
                           company_id=company_id, conversation_id=conversation_id,
                           allow_business_error_body=True)

