import logging

from langgraph.graph import StateGraph, START, END
from langgraph.types import StreamWriter

from schema.agent import HRState
from services.punch_details import punch_details_node
from services.attendance import attendance_node, _route_after_attendance
from services.ownership_guard import ownership_guard_node, _route_after_ownership
from services.regularisation_node import regularisation_node
from services.attendance_explain import attendance_explain_node
from services.classify_node import classify_node, _VALID_INTENT_LABELS
from services.ai_service import (
    _call_llm,
    _call_llm_stream,
    _extract_text,
    _safe_json_parse,
    _build_user_message,
    _get_fallback_redirect,
    extract_structured_date_fields,
    estimate_tokens,
    HR_SYSTEM_PROMPT,
    LLM_MAX_TOKENS,
)
# erp_client, _call_llm, _extract_text and extract_structured_date_fields are
# kept imported here (unused directly by this module's own node bodies)
# because tests patch them as hr_graph.erp_client / hr_graph._call_llm /
# hr_graph._extract_text / hr_graph.extract_structured_date_fields — see
# test_leave_action.py's mock_extraction() and conftest.py's repo-wide
# autouse fixture. erp_client is the same module object
# leave_action_service.py and leave_eligibility_service.py call into, so a
# patch on its attributes still takes effect there; the
# extract_structured_date_fields patch is currently a no-op since the active
# leave_action_node doesn't call this tier-2 date extraction, but removing
# the import breaks collection via AttributeError for every test file.
import services.erp_client as erp_client
from services.leave_action_service import (
    leave_action_node,
    # Both of these are pure helper functions with their own direct unit
    # tests (TestMatchKnownLeaveType / TestQueryNeedsRelativeDateScrutiny in
    # test_leave_action.py) written against hr_graph._match_known_leave_type
    # / hr_graph._query_needs_relative_date_scrutiny — kept re-exported here
    # for that reason alone, same as erp_client/_call_llm/etc. above. The
    # real implementations (and their actual call sites) live in
    # leave_action_service.py; this module never calls either itself.
    _match_known_leave_type,
    _query_needs_relative_date_scrutiny,
)
from services.leave_eligibility_service import (
    leave_eligibility_node, evaluate_eligibility, _tenure_label, _probation_countdown_label,
    _parse_bool_ish, _parse_int_ish, _policy_details, _policy_summary_sentence,
    _ELIGIBILITY_TIMEOUT_SECONDS, _parse_flexible_date, _format_date, _display_doj,
    _extract_claimed_doj, _doj_mismatch_note, _mentions_unconfigured_leave,
    _extract_unrecognised_leave_mention,
)

logger = logging.getLogger(__name__)


# ── Node 3: Non-HR redirect ───────────────────────────────────────────────────

async def non_hr_node(state: HRState, writer: StreamWriter) -> dict:
    query = state["query"]
    redirect_prompt = f"""You are Helix AI Assistant — an HR specialist chatbot. Your ONLY expertise is HR and workforce management.

The user asked: "{query}"

This is OUTSIDE your domain. Give a short, direct response — no apologies, no filler phrases like "I wish I could help." Just state clearly that you only handle HR topics and mention 1-2 HR areas you can assist with.

HARD RULES — violating any of these is a failure:
1. Do NOT include ANY facts, figures, answers, or information about what they asked — not even a casual mention of the answer
2. No phrases like "I wish", "I'd love to", "unfortunately", "I'm restricted" — be direct, not apologetic
3. Mention 1-2 specific HR topics you CAN help with
4. No bullet points. No numbered lists. No "I'm Helix AI Assistant" opener.
5. Under 40 words total.

Example of CORRECT response for "what is the weather today":
"That's outside my area — I cover HR topics only. Ask me about leave policies, payroll, or employee benefits and I'll help you out."

Example of WRONG response (never do this):
"The weather today depends on your location — temperatures vary by region — but that's outside my domain..." ← this is wrong because it gives information about the topic."""

    usage_events = list(state.get("usage_events", []))
    full_text = ""
    captured_usage = None
    try:
        async for event in _call_llm_stream(redirect_prompt, max_tokens=150, use_tools=False):
            if event["type"] == "chunk":
                full_text += event["content"]
                writer({"type": "chunk", "content": event["content"]})
            elif event["type"] == "usage":
                captured_usage = event["usage"]
    except Exception as e:
        logger.warning(f"[Graph] non_hr LLM failed, using fallback: {e}")

    if not full_text:
        full_text = _get_fallback_redirect(query)
        writer({"type": "chunk", "content": full_text})

    if captured_usage:
        usage_events.append({"source": "redirect", "usage": captured_usage})
    elif full_text:
        estimated = estimate_tokens(redirect_prompt) + estimate_tokens(full_text)
        usage_events.append({"source": "redirect", "usage": {
            "prompt_tokens": estimate_tokens(redirect_prompt),
            "completion_tokens": estimate_tokens(full_text),
            "total_tokens": estimated,
        }, "is_estimated": True})

    writer({
        "type": "done",
        "intent": state["intent"],
        "is_hr": False,
        "data": {"answer": full_text},
        "message": full_text,
        "usage_events": usage_events,
    })
    return {"response_text": full_text, "usage_events": usage_events}


# ── Node 3: HR Response ───────────────────────────────────────────────────────
# Chunks are streamed to the client immediately as they arrive — no buffering.
# Input moderation (in classify_node) is sufficient; output guardrail removed
# to eliminate the ~entire-response-duration delay before first byte.

async def hr_response_node(state: HRState, writer: StreamWriter) -> dict:
    context = state.get("context", [])
    query = state["query"]

    messages = [{"role": "system", "content": HR_SYSTEM_PROMPT}]
    for msg in context:
        role = msg.get("role", "user")
        if role not in ("user", "assistant"):
            role = "user"
        content = msg.get("content", "")
        if content:
            messages.append({"role": role, "content": content})
    messages.append({"role": "user", "content": query})

    usage_events = list(state.get("usage_events", []))
    full_text = ""
    captured_usage = None
    try:
        async for event in _call_llm_stream(messages, max_tokens=LLM_MAX_TOKENS):
            if event["type"] == "searching":
                logger.info("[Graph] Web search triggered by LLM")
                writer({"type": "searching", "message": "Searching the web..."})
            elif event["type"] == "chunk":
                full_text += event["content"]
                writer({"type": "chunk", "content": event["content"]})
            elif event["type"] == "usage":
                captured_usage = event["usage"]
    except Exception as e:
        logger.exception(f"[Graph] LLM stream failed: {e}")
        writer({"type": "error", "message": "Sorry, something went wrong while I was putting that answer together — please try again."})
        return {"response_text": "", "output_guardrail": {"status": "skipped"}, "usage_events": usage_events}

    if not full_text:
        writer({"type": "error", "message": "Sorry, I didn't quite get an answer together there — could you try asking again?"})
        return {"response_text": "", "output_guardrail": {"status": "skipped"}, "usage_events": usage_events}

    if captured_usage:
        usage_events.append({"source": "chat", "usage": captured_usage})
    else:
        prompt_text = "\n".join(m.get("content", "") for m in messages)
        usage_events.append({"source": "chat", "usage": {
            "prompt_tokens": estimate_tokens(prompt_text),
            "completion_tokens": estimate_tokens(full_text),
            "total_tokens": estimate_tokens(prompt_text) + estimate_tokens(full_text),
        }, "is_estimated": True})

    parsed = {"answer": full_text}
    if full_text.strip().startswith("{"):
        try:
            parsed = _safe_json_parse(full_text)
        except Exception:
            pass

    message = _build_user_message(state["intent"], parsed)
    logger.info(f"[Graph] Response complete | intent={state['intent']}")

    writer({
        "type": "done",
        "intent": state["intent"],
        "is_hr": True,
        "data": parsed,
        "message": message,
        "usage_events": usage_events,
    })
    return {"response_text": full_text, "output_guardrail": {"status": "skipped"}, "usage_events": usage_events}


# ── Node 4: Apply-leave / leave-balance (AC#1-#5) — see leave_action_service.py.
# Reuses erp-api's existing UsersLeaveRepository validation chain unchanged via
# erp_client — this node only orchestrates the conversation, it never
# duplicates a business rule. Slot state (leave_slot_service) is the "maintain
# state across turns" mechanism; classify_node's Fast-path 0.5 routes any
# mid-flow reply straight here without re-classifying.

_LEAVE_ACTION_INTENTS = {"leave_balance", "apply_leave", "leave_status", "cancel_leave"}
_PUNCH_DETAILS_INTENTS = {"punch_details"}
# NOTE: named distinctly from _ATTENDANCE_INTENTS below — that one is the
# plain "attendance" intent (live record lookup, attendance_node), this one
# is "attendance_explain" (WHY a specific day was classified a certain way,
# attendance_explain_node). Easy to conflate since both are attendance-
# adjacent; keep the names apart.
_ATTENDANCE_EXPLAIN_INTENTS = {"attendance_explain"}
_ATTENDANCE_INTENTS = {"attendance"}
_HRMS_REGULARIZATION = {"regularisation"}


# ── Conditional edges ─────────────────────────────────────────────────────────

def _route_after_classify(state: HRState) -> str:
    if state.get("error"):
        return END
    intent = state.get("intent")
    # classify_node already streamed the "done" event (the leave-type
    # clarifying question, e.g. "would you like your sick leave balance,
    # eligibility, ...") and set response_text itself for this sentinel —
    # nothing downstream should run, or the user gets a second, contradictory
    # answer for the same turn.
    if intent == "leave_type_clarify":
        return END
    # Checked before _LEAVE_ACTION_INTENTS and deliberately kept out of that
    # set: eligibility is a read-only question, and leave_action_node owns the
    # apply-flow slot state that must not be touched by one.
    if intent == "leave_eligibility":
        return "leave_eligibility_node"
    if intent in _LEAVE_ACTION_INTENTS:
        return "leave_action_node"
    if intent in _PUNCH_DETAILS_INTENTS:
        return "punch_details_node"
    if intent in _ATTENDANCE_EXPLAIN_INTENTS:
        return "attendance_explain_node"
    if intent in _ATTENDANCE_INTENTS:
        return "attendance_node"
    if intent in _HRMS_REGULARIZATION:
        return "regularisation_node"
    return "hr_response_node" if state.get("is_hr") else "non_hr_node"

# ── Build & compile ───────────────────────────────────────────────────────────

def build_hr_graph():
    graph = StateGraph(HRState)
    graph.add_node("ownership_guard_node", ownership_guard_node)
    graph.add_node("classify_node", classify_node)
    graph.add_node("non_hr_node", non_hr_node)
    graph.add_node("hr_response_node", hr_response_node)
    graph.add_node("leave_action_node", leave_action_node)
    graph.add_node("leave_eligibility_node", leave_eligibility_node)
    graph.add_node("punch_details_node", punch_details_node)
    graph.add_node("attendance_explain_node", attendance_explain_node)
    graph.add_node("attendance_node", attendance_node)
    graph.add_node("regularisation_node", regularisation_node)

    graph.add_edge(START, "ownership_guard_node")
    graph.add_conditional_edges(
        "ownership_guard_node",
        _route_after_ownership,
        {
            END: END,
            "classify_node": "classify_node",
        },
    )
    graph.add_conditional_edges(
        "classify_node",
        _route_after_classify,
        {
            END: END,
            "hr_response_node": "hr_response_node",
            "non_hr_node": "non_hr_node",
            "leave_action_node": "leave_action_node",
            "leave_eligibility_node": "leave_eligibility_node",
            "punch_details_node": "punch_details_node",
            "attendance_explain_node": "attendance_explain_node",
            "attendance_node": "attendance_node",
            "regularisation_node": "regularisation_node",
        },
    )
    graph.add_edge("hr_response_node", END)
    graph.add_edge("non_hr_node", END)
    graph.add_edge("leave_action_node", END)
    graph.add_edge("leave_eligibility_node", END)
    graph.add_edge("punch_details_node", END)
    graph.add_conditional_edges(
        "attendance_node",
        _route_after_attendance,
        {
            END: END,
            "regularisation_node": "regularisation_node",
        },
    )
    graph.add_conditional_edges(
            "attendance_explain_node",
            _route_after_attendance,
            {
                END: END,
                "regularisation_node": "regularisation_node",
            },
        )
    graph.add_edge("regularisation_node", END)


    return graph.compile()


hr_graph = build_hr_graph()