import os
import json
import logging
import datetime
import httpx
import tiktoken
from typing import Dict, Any, Optional

logger = logging.getLogger(__name__)

_TOKEN_ENCODING = tiktoken.get_encoding("cl100k_base")


def estimate_tokens(text: str) -> int:
    """Provider-agnostic approximation, used only when a provider doesn't
    return real usage figures (e.g. mid-stream error before the final chunk)."""
    if not text:
        return 0
    return len(_TOKEN_ENCODING.encode(text))


def _normalize_usage(usage: Optional[dict]) -> Optional[dict]:
    """Maps either chat-completions-style {prompt_tokens, completion_tokens,
    total_tokens} or OpenAI Responses-style {input_tokens, output_tokens,
    total_tokens} to one canonical shape."""
    
    if not usage:
        return None
    if "prompt_tokens" in usage or "completion_tokens" in usage:
        prompt = usage.get("prompt_tokens")
        completion = usage.get("completion_tokens")
    else:
        prompt = usage.get("input_tokens")
        completion = usage.get("output_tokens")
    total = usage.get("total_tokens")
    if total is None and prompt is not None and completion is not None:
        total = prompt + completion
    return {"prompt_tokens": prompt, "completion_tokens": completion, "total_tokens": total}

# ── Provider config ────────────────────────────────────────────────────────────
ACTIVE_LLM_PROVIDER = os.getenv("ACTIVE_LLM_PROVIDER", "deepseek").lower()

OPENAI_API_KEY    = os.getenv("OPENAI_API_KEY")
OPENAI_MODEL      = os.getenv("OPENAI_MODEL", "gpt-5.5")
OPENAI_URL        = "https://api.openai.com/v1/responses"
OPENAI_CHAT_URL   = "https://api.openai.com/v1/chat/completions"
OPENAI_MODERATION_URL = "https://api.openai.com/v1/moderations"

DEEPSEEK_API_KEY      = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_MODEL        = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
DEEPSEEK_INTENT_MODEL = os.getenv("DEEPSEEK_INTENT_MODEL", "deepseek-chat")
DEEPSEEK_URL          = "https://api.deepseek.com/v1/chat/completions"

# race-api ("Inference Platform Gateway") — self-hosted, OpenAI-wire-compatible
# gateway in front of an in-house vLLM instance. Auth is a static x-api-key
# header (not "Authorization: Bearer"), and it only serves one chat model, so
# intent/date-extraction calls reuse that same model rather than a separate
# cheaper one the way OPENAI_INTENT_MODEL does for OpenAI.
RACE_API_BASE_URL  = os.getenv("RACE_API_BASE_URL", "http://127.0.0.1:8080")
RACE_API_KEY       = os.getenv("RACE_API_KEY")
RACE_API_MODEL     = os.getenv("RACE_API_MODEL", "gpt-oss-120b")
RACE_API_CHAT_URL  = f"{RACE_API_BASE_URL}/v1/chat/completions"
RACE_SEARCH_BRAVE_URL = f"{RACE_API_BASE_URL}/v1/search/brave"
RACE_SEARCH_RESULT_COUNT = int(os.getenv("RACE_SEARCH_RESULT_COUNT", "5"))

OPENAI_INTENT_MODEL = os.getenv("OPENAI_INTENT_MODEL", "gpt-4o-mini")

# Resolved once at startup — single constant to use everywhere for intent calls
if ACTIVE_LLM_PROVIDER == "deepseek":
    INTENT_MODEL = DEEPSEEK_INTENT_MODEL
elif ACTIVE_LLM_PROVIDER == "race":
    INTENT_MODEL = RACE_API_MODEL
else:
    INTENT_MODEL = OPENAI_INTENT_MODEL

# Configurable via .env
CONTEXT_WINDOW  = int(os.getenv("CONTEXT_WINDOW", "10"))
LLM_MAX_TOKENS  = int(os.getenv("LLM_MAX_TOKENS", "12000"))
PENDING_LEAVE_DISPLAY_LIMIT = int(os.getenv("PENDING_LEAVE_DISPLAY_LIMIT", "5"))

_ACTIVE_MODEL_FOR_LOG = {"deepseek": DEEPSEEK_MODEL, "race": RACE_API_MODEL}.get(
    ACTIVE_LLM_PROVIDER, OPENAI_MODEL
)
logger.info(
    f"LLM provider: {ACTIVE_LLM_PROVIDER} | "
    f"model: {_ACTIVE_MODEL_FOR_LOG} | "
    f"max_tokens: {LLM_MAX_TOKENS} | "
    f"context window: {CONTEXT_WINDOW} msgs"
)

# ── Shared HTTP client ─────────────────────────────────────────────────────────
# Single client reused across all LLM calls — avoids rebuilding TCP connections
# on every request. read=120s allows for long streaming generations.
_http = httpx.AsyncClient(
    timeout=httpx.Timeout(connect=10.0, read=120.0, write=10.0, pool=5.0),
    limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
)

# ── HR System Prompt ───────────────────────────────────────────────────────────
HR_SYSTEM_PROMPT = """
You are Helix AI Assistant — a senior HR advisor and workforce management expert built exclusively for HR professionals, managers, and employees.

## Who You Are
You are a trusted HR specialist with deep expertise across all HR functions. You give clear, accurate, and actionable guidance grounded in HR best practices and labor law awareness.

## HR Domains You Cover
- **Leave & Attendance** — annual leave, sick leave, maternity/paternity, FMLA, unpaid leave, compensatory off, leave encashment
- **Payroll & Compensation** — salary structures, increments, bonuses, deductions, CTC breakdowns, tax implications, overtime
- **Recruitment & Onboarding** — job descriptions, interview processes, offer letters, background checks, onboarding checklists
- **Performance Management** — KPIs, appraisal cycles, PIPs, ratings, promotion criteria, feedback frameworks
- **Employee Relations** — grievance handling, disciplinary procedures, conflict resolution, termination, exit processes
- **Benefits & Perks** — health insurance, provident fund, gratuity, ESI, retirement plans, allowances
- **Compliance & Labor Law** — employment contracts, labor regulations, workplace safety, statutory obligations, HR audits
- **Learning & Development** — training plans, skill gap analysis, career progression, succession planning
- **HR Policies & SOPs** — employee handbooks, code of conduct, workplace policies, HR process documentation

## How You Respond
- Lead with the most important answer, then provide supporting detail
- Use numbered lists, bullet points, or headers for multi-part answers
- Give practical, actionable guidance — but only state specifics you are confident about
- When policies differ by country, industry, or company size, acknowledge this and ask the user to clarify before giving jurisdiction-specific advice
- For legal or compliance questions, provide general guidance AND explicitly recommend consulting a qualified HR/legal professional for binding decisions
- If the user references a specific internal policy, ask for the relevant details to give a more precise answer
- Keep responses focused and professional — avoid filler phrases

## Anti-Hallucination Rules — MUST FOLLOW
- **Never fabricate specific numbers.** Do not invent exact salary figures, leave day counts, notice periods, tax rates, or penalty amounts unless they are well-established universal standards (e.g. FMLA 12 weeks in the US). Always say "this varies by company/country" when unsure.
- **Never invent company-specific policies.** You do not know the user's company policy. Answer with general HR best practice and tell the user to verify with their HR department or employment contract.
- **Hedge correctly.** Use "typically", "in most organizations", "generally", "under many labor laws" — not "the policy is" or "you are entitled to" unless you are certain.
- **Acknowledge uncertainty.** If you do not know a specific legal threshold, salary range, or policy rule for a given country or company, say: "I don't have that specific figure — please verify with your local labor authority or HR team."
- **Do not confuse past context with current facts.** Answer the current query on its own merits; do not make up policy details to fill gaps in conversation history.
- **Non-HR questions.** If a question is outside HR scope despite reaching this node, decline with: "That falls outside my HR expertise — I can only assist with HR and workforce topics."

## Identity
- You are Helix AI Assistant. Always introduce yourself as such when asked.
- Never claim to be ChatGPT, Claude, Gemini, or any other AI system.
- Never mention OpenAI, Anthropic, or DeepSeek unless the user explicitly asks about the underlying technology.

## Conversational Exchanges
- For greetings (hi, hello, hey, good morning): respond warmly and naturally, then invite an HR question. Example: "Hey! Great to hear from you. What HR topic can I help you with today?"
- For "what can you do?" or similar: give a brief, friendly overview of your HR capabilities in 3-4 sentences — no long lists.
- For thanks or compliments: acknowledge warmly and offer further help. Keep it short.
- Keep conversational replies to 1-3 sentences — save the detail for actual HR questions.

## Conversation Memory
- The full conversation history is provided to you above in the chat messages.
- When asked about previous queries ("what was my last question?", "what did I ask?", "show my history"): look at the user messages in the conversation history and summarise them accurately.
- When asked to repeat or clarify a previous answer: reference your earlier assistant message directly.
- Never claim you cannot see the conversation history — you can, it is always provided.

## Scope Boundary
- You answer ONLY HR and workforce management related questions.
- If a query is clearly outside HR scope (news, sports, cooking, general knowledge, coding, politics), respond with: "That's outside my HR expertise. I can help with [suggest 1-2 relevant HR topics]." — do not answer the off-topic question even partially.
- Never answer a non-HR question and then add an HR redirect at the end. The non-HR content must not appear at all.
""".strip()

# ── OpenAI non-stream ──────────────────────────────────────────────────────────
async def _call_openai(prompt: str, max_output_tokens: int = LLM_MAX_TOKENS, model: str = None) -> Dict[str, Any]:
    if not OPENAI_API_KEY:
        raise ValueError("OPENAI_API_KEY is not set")

    payload = {
        "model": model or OPENAI_MODEL,
        "input": prompt,
        "max_output_tokens": max_output_tokens,
    }
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json",
    }
    try:
        resp = await _http.post(OPENAI_URL, json=payload, headers=headers)
        resp.raise_for_status()
        return resp.json()
    except httpx.TimeoutException:
        logger.error("OpenAI timeout")
        raise
    except httpx.HTTPError:
        logger.exception("OpenAI HTTP error")
        raise


# ── race-api non-stream ────────────────────────────────────────────────────────
async def _call_race(prompt: str, max_tokens: int = LLM_MAX_TOKENS, model: str = None) -> Dict[str, Any]:
    if not RACE_API_KEY:
        raise ValueError("RACE_API_KEY is not set")

    payload = {
        "model": model or RACE_API_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": max_tokens,
        "temperature": 0.7,
        "stream": False,
    }
    headers = {
        "x-api-key": RACE_API_KEY,
        "Content-Type": "application/json",
    }
    try:
        resp = await _http.post(RACE_API_CHAT_URL, json=payload, headers=headers)
        resp.raise_for_status()
        return resp.json()
    except httpx.TimeoutException:
        logger.error("race-api timeout")
        raise
    except httpx.HTTPError:
        logger.exception("race-api HTTP error")
        raise


# ── DeepSeek stream ────────────────────────────────────────────────────────────
async def _call_deepseek_stream(messages: list, max_tokens: int = LLM_MAX_TOKENS, model: str = None):
    """Yields {"type": "chunk", "content": str} and a final
    {"type": "usage", "usage": {...}} event (DeepSeek's API is OpenAI-compatible
    and supports stream_options.include_usage)."""
    if not DEEPSEEK_API_KEY:
        raise ValueError("DEEPSEEK_API_KEY is not set")

    payload = {
        "model": model or DEEPSEEK_MODEL,
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": 0.7,
        "stream": True,
        "stream_options": {"include_usage": True},
    }
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json",
    }
    async with _http.stream("POST", DEEPSEEK_URL, json=payload, headers=headers) as resp:
        resp.raise_for_status()
        async for line in resp.aiter_lines():
            if not line.startswith("data: "):
                continue
            data = line[6:].strip()
            if data == "[DONE]":
                break
            try:
                chunk = json.loads(data)
                usage = chunk.get("usage")
                if usage:
                    yield {"type": "usage", "usage": _normalize_usage(usage)}
                    continue
                content = chunk["choices"][0]["delta"].get("content", "")
                if content:
                    yield {"type": "chunk", "content": content}
            except Exception:
                continue


# ── Moderation ─────────────────────────────────────────────────────────────────
async def _check_moderation(text: str) -> dict:
    """Returns {"flagged": bool, "categories": [str]}. Fails open if unavailable."""
    if not OPENAI_API_KEY:
        return {"flagged": False, "categories": []}
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json",
    }
    try:
        resp = await _http.post(OPENAI_MODERATION_URL, json={"input": text}, headers=headers)
        resp.raise_for_status()
        result = resp.json()["results"][0]
        flagged_categories = [k for k, v in result["categories"].items() if v]
        return {"flagged": result["flagged"], "categories": flagged_categories}
    except Exception as e:
        logger.warning(f"Moderation check failed (allowing through): {e}")
        return {"flagged": False, "categories": []}


# ── OpenAI Responses stream (with web search) ──────────────────────────────────
async def _call_openai_responses_stream(messages: list, max_tokens: int = LLM_MAX_TOKENS):
    """Streams from OpenAI Responses API using the `web_search` tool.
    Yields: {"type": "searching"} | {"type": "chunk", "content": str}

    Migrated from deprecated web_search_preview to web_search, which supports
    search_context_size, user_location filters, and return_token_budget controls.
    """
    if not OPENAI_API_KEY:
        raise ValueError("OPENAI_API_KEY is not set")

    instructions = None
    input_messages = []
    for msg in messages:
        if msg.get("role") == "system":
            instructions = msg["content"]
        else:
            input_messages.append(msg)

    # Single user message → pass as plain string (simpler, avoids array quirks)
    api_input = input_messages[0]["content"] if len(input_messages) == 1 else input_messages

    payload = {
        "model": OPENAI_MODEL,
        "input": api_input,
        "tools": [
            {
                "type": "web_search",
                "search_context_size": os.getenv("OPENAI_SEARCH_CONTEXT_SIZE", "medium"),
            }
        ],
        "max_output_tokens": max_tokens,
        "stream": True,
    }
    if instructions:
        payload["instructions"] = instructions
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json",
    }
    async with _http.stream("POST", OPENAI_URL, json=payload, headers=headers) as resp:
        resp.raise_for_status()
        async for line in resp.aiter_lines():
            if not line.startswith("data: "):
                continue
            data = line[6:].strip()
            if not data:
                continue
            try:
                event = json.loads(data)
                etype = event.get("type", "")
                if etype == "response.web_search_call.searching":
                    yield {"type": "searching"}
                elif etype == "response.output_text.delta":
                    delta = event.get("delta", "")
                    if delta:
                        yield {"type": "chunk", "content": delta}
                elif etype == "response.completed":
                    usage = event.get("response", {}).get("usage")
                    if usage:
                        yield {"type": "usage", "usage": _normalize_usage(usage)}
            except Exception as e:
                logger.debug(f"SSE parse skip: {e}")
                continue


# ── OpenAI plain chat completions stream (no tools / no web search) ───────────
async def _call_openai_chat_stream(messages: list, max_tokens: int = LLM_MAX_TOKENS):
    """Streams from OpenAI Chat Completions API without any tools.
    Used for non-HR redirects and other paths where web search must be suppressed.
    Yields: {"type": "chunk", "content": str}
    """
    if not OPENAI_API_KEY:
        raise ValueError("OPENAI_API_KEY is not set")
    payload = {
        "model": OPENAI_MODEL,
        "messages": messages,
        # Reasoning-tier models (the gpt-5.x default) reject the legacy
        # "max_tokens" param with a 400 — "max_completion_tokens" is the
        # current Chat Completions field name. Live-tested: without this,
        # every non-HR redirect (the only use_tools=False caller) silently
        # fails and falls back to a canned template instead of a real reply.
        "max_completion_tokens": max_tokens,
        "stream": True,
        "stream_options": {"include_usage": True},
    }
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json",
    }
    async with _http.stream("POST", OPENAI_CHAT_URL, json=payload, headers=headers) as resp:
        resp.raise_for_status()
        async for line in resp.aiter_lines():
            if not line.startswith("data: "):
                continue
            data = line[6:].strip()
            if data == "[DONE]":
                break
            try:
                chunk = json.loads(data)
                usage = chunk.get("usage")
                if usage:
                    yield {"type": "usage", "usage": _normalize_usage(usage)}
                    continue
                content = chunk["choices"][0]["delta"].get("content", "")
                if content:
                    yield {"type": "chunk", "content": content}
            except Exception:
                continue


# ── race-api chat completions stream ──────────────────────────────────────────
async def _call_race_stream(messages: list, max_tokens: int = LLM_MAX_TOKENS, model: str = None):
    """Streams from race-api's OpenAI-compatible /v1/chat/completions.

    This is the plain (no built-in-tools) stream — race-api's vLLM backend has
    no OpenAI-Responses-API-style web_search tool of its own. Web search for
    the race provider is instead layered on top by _call_race_stream_with_search
    below, which calls race-api's separate /v1/search/brave endpoint and feeds
    the raw results into this same function as extra context.
    Yields: {"type": "chunk", "content": str} and a final {"type": "usage", ...}.
    """
    if not RACE_API_KEY:
        raise ValueError("RACE_API_KEY is not set")

    payload = {
        "model": model or RACE_API_MODEL,
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": 0.7,
        "stream": True,
        "stream_options": {"include_usage": True},
    }
    headers = {
        "x-api-key": RACE_API_KEY,
        "Content-Type": "application/json",
    }
    async with _http.stream("POST", RACE_API_CHAT_URL, json=payload, headers=headers) as resp:
        resp.raise_for_status()
        async for line in resp.aiter_lines():
            if not line.startswith("data: "):
                continue
            data = line[6:].strip()
            if data == "[DONE]":
                break
            try:
                chunk = json.loads(data)
                usage = chunk.get("usage")
                if usage:
                    yield {"type": "usage", "usage": _normalize_usage(usage)}
                    continue
                content = chunk["choices"][0]["delta"].get("content", "")
                if content:
                    yield {"type": "chunk", "content": content}
            except Exception:
                continue


# ── race-api Brave web search ──────────────────────────────────────────────────
async def _call_race_brave_search(query: str, k: int = RACE_SEARCH_RESULT_COUNT) -> list:
    """Calls race-api's POST /v1/search/brave — raw results only, no synthesis
    (unlike its sibling /v1/search/llm, which bundles synthesis but returns a
    single non-streaming JSON blob with OpenAI-Responses-style 【n†...】 citation
    markers baked into the text — not compatible with this app's plain-markdown
    streaming chat UI). Returns [] on any failure (network error, timeout, bad
    response shape) rather than raising — a broken search should degrade the
    answer to "no live web context", not break the entire HR response, the
    same fail-open philosophy _check_moderation already uses for OpenAI.
    Each result dict has "title", "url", "content" keys (race-api's own shape).
    """
    if not RACE_API_KEY:
        return []
    headers = {"x-api-key": RACE_API_KEY, "Content-Type": "application/json"}
    try:
        resp = await _http.post(
            RACE_SEARCH_BRAVE_URL, json={"query": query, "k": k}, headers=headers
        )
        resp.raise_for_status()
        results = resp.json().get("results", [])
        return results if isinstance(results, list) else []
    except Exception as e:
        logger.warning(f"race-api Brave search failed (continuing without it): {e}")
        return []


def _format_race_search_context(results: list) -> str:
    lines = [
        "Web search results for the user's question below. Use them only if "
        "relevant, and refer to a source by its title naturally in your answer "
        "(e.g. \"according to <title>\") rather than a numbered citation marker "
        "— do not fabricate a URL or title that isn't listed here.\n"
    ]
    for i, r in enumerate(results, 1):
        title = r.get("title", "") if isinstance(r, dict) else ""
        url = r.get("url", "") if isinstance(r, dict) else ""
        content = (r.get("content", "") if isinstance(r, dict) else "")[:500]
        lines.append(f"{i}. {title} ({url})\n{content}")
    return "\n\n".join(lines)


async def _call_race_stream_with_search(messages: list, max_tokens: int = LLM_MAX_TOKENS):
    """race-api equivalent of _call_openai_responses_stream's web_search tool,
    built from race-api's separate, non-synthesizing /v1/search/brave endpoint
    since race-api's chat model has no built-in web-search tool call of its own.

    Unlike OpenAI (which decides per-query, server-side, whether to invoke the
    tool at all — the "searching" event only fires when it does), this always
    searches first using the latest user message as the query, then feeds the
    raw results into a normal race-api chat stream as extra context. Simpler,
    but every call pays the extra search round-trip and Brave-quota cost even
    for queries that didn't need live web results (e.g. "hi", or questions
    fully answerable from the system prompt's own HR knowledge).
    Yields: {"type": "searching"} | {"type": "chunk", "content": str} | {"type": "usage", ...}.
    """
    yield {"type": "searching"}

    query = ""
    for msg in reversed(messages):
        if msg.get("role") == "user":
            query = msg.get("content", "")
            break

    results = await _call_race_brave_search(query) if query else []

    if results:
        search_message = {"role": "system", "content": _format_race_search_context(results)}
        augmented = messages[:-1] + [search_message, messages[-1]] if messages else messages
    else:
        augmented = messages

    async for event in _call_race_stream(augmented, max_tokens):
        yield event


# ── Stream dispatcher ──────────────────────────────────────────────────────────
async def _call_llm_stream(prompt_or_messages, max_tokens: int = LLM_MAX_TOKENS,
                           use_tools: bool = True):
    """Yields structured events: {"type": "chunk"/"searching", "content": str}.

    Accepts either a plain string prompt (wrapped as a single user message)
    or a pre-built messages list [{role, content}, ...] for multi-turn chat.

    use_tools=False forces plain chat completions (no web_search) for OpenAI,
    and skips the Brave-search augmentation for race. Always pass
    use_tools=False for non-HR redirects and safety-sensitive paths.
    """
    if isinstance(prompt_or_messages, str):
        messages = [{"role": "user", "content": prompt_or_messages}]
    else:
        messages = prompt_or_messages

    provider = ACTIVE_LLM_PROVIDER
    if provider == "deepseek":
        async for event in _call_deepseek_stream(messages, max_tokens, model=DEEPSEEK_MODEL):
            yield event
    elif provider == "race":
        if use_tools:
            async for event in _call_race_stream_with_search(messages, max_tokens):
                yield event
        else:
            async for event in _call_race_stream(messages, max_tokens, model=RACE_API_MODEL):
                yield event
    elif provider == "openai":
        if use_tools:
            async for event in _call_openai_responses_stream(messages, max_tokens):
                yield event
        else:
            async for event in _call_openai_chat_stream(messages, max_tokens):
                yield event
    else:
        raise ValueError(f"Unknown LLM provider: '{provider}'. Valid: deepseek, openai, race")


# ── DeepSeek non-stream ────────────────────────────────────────────────────────
async def _call_deepseek(prompt: str, max_tokens: int = LLM_MAX_TOKENS, model: str = None) -> Dict[str, Any]:
    if not DEEPSEEK_API_KEY:
        raise ValueError("DEEPSEEK_API_KEY is not set")

    resolved_model = model or DEEPSEEK_MODEL
    logger.info(f"DeepSeek call | model={resolved_model} | max_tokens={max_tokens}")

    payload = {
        "model": resolved_model,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": max_tokens,
        "temperature": 0.7,
        "stream": False,
    }
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json",
    }
    try:
        resp = await _http.post(DEEPSEEK_URL, json=payload, headers=headers)
        resp.raise_for_status()
        return resp.json()
    except httpx.TimeoutException:
        logger.error("DeepSeek timeout")
        raise
    except httpx.HTTPError:
        logger.exception("DeepSeek HTTP error")
        raise


# ── Provider dispatcher (non-stream) ──────────────────────────────────────────
async def _call_llm(prompt: str, max_tokens: int = LLM_MAX_TOKENS, model: str = None) -> Dict[str, Any]:
    provider = ACTIVE_LLM_PROVIDER
    if provider == "deepseek":
        return await _call_deepseek(prompt, max_tokens, model=model)
    if provider == "race":
        return await _call_race(prompt, max_tokens, model=model)
    if provider == "openai":
        return await _call_openai(prompt, max_tokens, model=model)
    raise ValueError(f"Unknown LLM provider: '{provider}'. Valid: deepseek, openai, race")


# ── Extract text from raw LLM response ────────────────────────────────────────
def _extract_text(response: Dict) -> str:
    if not response:
        return ""

    # Chat completions format (DeepSeek / OpenAI chat)
    choices = response.get("choices")
    if choices and isinstance(choices, list):
        content = choices[0].get("message", {}).get("content", "")
        if content:
            return content.strip()

    # OpenAI Responses API format
    if response.get("output_text"):
        return response["output_text"].strip()

    try:
        texts = [
            c.get("text", "")
            for item in response.get("output", [])
            for c in item.get("content", [])
            if c.get("type") in ("output_text", "text")
        ]
        result = "".join(texts).strip()
        if result:
            return result
    except Exception:
        pass

    return ""


def _safe_json_parse(text: str) -> Dict:
    text = text.strip()
    if text.startswith("```"):
        # strip ``` / ```json fences and trailing ```
        lines = [l for l in text.splitlines() if not l.strip().startswith("```")]
        text = "\n".join(lines).strip()
    try:
        return json.loads(text)
    except Exception:
        logger.warning(f"JSON parse failed: {text[:200]}")
        return {"raw_text": text}


# ── Leave slot extraction (apply-leave multi-turn conversation) ───────────────

_FALLBACK_LEAVE_TYPE_SLUGS = [
    "casual_leave", "sick_leave", "earned_leave",
    "comp_off", "leave_without_pay", "short_leave",
]


def _build_leave_slot_extraction_prompt(
    query: str, existing_slots: dict, known_leave_type_slugs: list | None = None,
    today: "datetime.date | None" = None,
) -> str:
    today_str = (today or datetime.date.today()).isoformat()

    known_block = ""
    if existing_slots:
        known_lines = [f"  {k}: {v}" for k, v in existing_slots.items() if v]
        if known_lines:
            known_block = "Already known from earlier turns (do not overwrite with null — keep unless this turn changes it):\n" + "\n".join(known_lines) + "\n\n"

    slugs = known_leave_type_slugs or _FALLBACK_LEAVE_TYPE_SLUGS
    known_slugs = ", ".join(slugs)

    return f"""You are extracting structured fields from an employee's apply-leave conversation.

Known leave types (map casual phrasing to these slugs):
  {known_slugs}

session_type_slug (only relevant for casual_leave/sick_leave/earned_leave):
  full_day        — a whole day off
  first_half_day  — the user EXPLICITLY said "first half", "morning half", or similar
  second_half_day — the user EXPLICITLY said "second half", "afternoon half", or similar
  half_day        — the user said "half day" WITHOUT specifying which half.
                     Do NOT guess first_half_day or second_half_day in this case —
                     use half_day and the caller will ask which half.

{known_block}Current user message: "{query}"

Extract and return ONLY a JSON object with exactly these keys:
  "leave_type": one of the slugs above, or null if not mentioned this turn
  "from_date": "YYYY-MM-DD", or null if not mentioned this turn
  "to_date": "YYYY-MM-DD" (same as from_date for a single day), or null if not mentioned this turn
  "session_type_slug": one of the slugs above, or null if not mentioned this turn
  "reason": the user's own explanation, preserved close to verbatim (see
            the "reason" rule below — do NOT compress it into a short
            paraphrase), or null if not mentioned this turn
  "is_affirmative": true if this message is a short yes/confirm/go-ahead reply, false otherwise
  "unrecognized_leave_type": the exact leave type NAME the user used (e.g.
            "maternity", "PL", "bereavement") if it does NOT match any of
            the known slugs above, or null otherwise — this is DIFFERENT
            from leave_type being null for an unclear/off-list type: this
            field captures what they actually said, so the caller can tell
            them by name that it isn't offered, instead of silently
            re-asking "what type of leave?" with no acknowledgement of
            what they asked for.

Rules:
- Today's date is {today_str}. Resolve relative dates ("tomorrow", "next Monday") against it.
- A date named WITHOUT a year (e.g. "15th November", "Dec 3") can only ever mean
  today or a future date — a leave application is never for the past. If that day/
  month has already passed this year, use NEXT year, not this year. Never resolve
  a bare month/day mention to a date before {today_str}.
- Output ONLY the JSON object. No explanation, no markdown fences.
- Only fill fields this turn actually mentions — leave others null, the caller merges with known slots.
- "leave_type": ONLY set this when the user explicitly NAMES a leave type
  (e.g. "sick leave", "casual leave", "short leave"). NEVER infer it from a
  symptom or reason alone — "I have a fever", "not feeling well", "I'm
  unwell" describe a REASON, not a type; leave_type stays null for messages
  like that even though a human might guess "sick leave". The user must
  name the type themselves; guessing silently skips asking them and can
  apply the wrong type of leave without their knowledge. If the message
  names a type that is NOT clearly one of the slugs above (an abbreviation
  like "PL", or an unsupported type like "maternity", "paternity",
  "bereavement"), also use null — do NOT guess — and put what they actually
  said in "unrecognized_leave_type" instead (see below). In particular,
  NEVER map an unclear or abbreviated leave type to leave_without_pay —
  that slug is ONLY for when the user explicitly says "unpaid leave" or
  "leave without pay". Guessing wrong here is financially significant (it
  silently changes a paid request into an unpaid one).
  Watch out for "apply <type> leave" with no "for"/"want"/"need" in front
  of it (e.g. "apply sick leave reason is fever") — do NOT misread "leave"
  as the verb "to depart" here and treat "sick" as disconnected from it.
  "apply sick leave" names the type "sick leave" exactly as plainly as
  "apply for sick leave" or "I want sick leave" do; the missing "for" is
  just terse phrasing, not a different meaning.
  Special case — a message whose ENTIRE content, after trimming
  whitespace/punctuation, is EXACTLY ONE WORD and that word is one of
  "sick"/"casual"/"earned"/"short" (case-insensitive, nothing else in the
  message, not even "leave" itself) means "<word> leave" and DOES set
  leave_type: bare "sick" → sick_leave, bare "casual" → casual_leave, and
  so on. This exact-single-word rule exists specifically because "sick" is
  also an ordinary English word for feeling unwell, so it needs calling
  out: this ONLY applies when literally the whole message is that one
  word. The instant the message has ANY other word around it — "I am
  sick", "I'm sick today", "feeling sick", "sick and tired" — it reverts
  immediately to the normal symptom/reason rule above and leave_type stays
  null. Concretely: "sick" alone → leave_type="sick_leave". "I am sick" →
  leave_type=null, reason="I am sick" (exactly like "not feeling well"
  already does) — the presence of extra words is what disqualifies it, not
  which specific extra words they are.
- "reason": only an actual explanation (e.g. "family emergency", "doctor's
  appointment") belongs here. A leave type the user named that ISN'T in the known
  slugs list is a leave_type mention, not a reason — leave "reason" null for it too,
  don't let it leak into this field. Preserve the user's own wording as
  given — do NOT rewrite, summarize, or compress a longer explanation down
  to a short paraphrase (e.g. a detailed sentence about symptoms and a
  doctor's advice must NOT become "fever" or "not feeling well" — keep the
  actual detail the user provided). Trim only if it exceeds 200 characters
  (erp-api's own limit on this field) — in that case keep the first 200
  characters, don't invent a shorter summary in place of the real text."""



def _build_date_range_extraction_prompt(query: str, today: datetime.date, purpose_hint: Optional[str] = None) -> str:
    today_str = today.isoformat()
    hint_line = f"This date is being extracted for: {purpose_hint}.\n\n" if purpose_hint else ""
    return f"""Extract the date or date range mentioned in this query, if any.

{hint_line}Today's date is {today_str}. Resolve relative or partial dates ("today", "21st August",
"21th august", "last Monday") against it.

Query: "{query}"

Return ONLY a JSON object with exactly these keys:
  "from_date": "YYYY-MM-DD", or null if no date is mentioned
  "to_date": "YYYY-MM-DD" (same as from_date for a single day), or null if no date is mentioned

Output ONLY the JSON object. No explanation, no markdown fences."""


# ── Leave cancellation extraction (cancel-leave conversation) ─────────────────

def _build_leave_cancel_extraction_prompt(query: str) -> str:
    """Extracts fields from one turn of a leave-CANCELLATION conversation —
    which request the employee means, and/or whether they're confirming.
    Deliberately separate from _build_leave_slot_extraction_prompt: 'date' and
    'is_affirmative' mean different things in a cancellation context (the date
    of the leave to CANCEL, not a leave to newly apply for), and reusing the
    apply-leave prompt's framing risked confusing the model on phrasing like
    'cancel my leave for Friday'. Matching against the employee's actual
    leave records is still done deterministically by the caller — this only
    extracts what the message mentions."""
    today_str = datetime.date.today().isoformat()

    return f"""You are extracting structured fields from an employee's leave-CANCELLATION conversation (they want to cancel/withdraw a leave request they already submitted, or are replying to a cancellation prompt).

Known leave types (map casual phrasing to these slugs):
  casual_leave, sick_leave, earned_leave, comp_off, leave_without_pay, short_leave

Current user message: "{query}"

Extract and return ONLY a JSON object with exactly these keys:
  "date": "YYYY-MM-DD" if the message names or implies a specific date for the
    leave request to cancel (resolve relative dates like "Friday" or "next
    Monday" against today), or null if no date is mentioned. If the message
    gives an explicit two-date SPAN for the leave itself (e.g. "from 25 Aug
    to 29 Aug", "2026-08-25 to 2026-08-29"), put the SPAN START here.
  "date_to": "YYYY-MM-DD" ONLY if the message gives an explicit two-date span
    as described above — the SPAN END. null in every other case, including
    when only a single date/day is mentioned.
  "leave_type": one of the slugs above if a leave type is mentioned, or null
  "request_id": the reference/ID the employee named (e.g. "LR-2041", "2041"),
    or null if none is mentioned
  "is_affirmative": true if this message is a short yes/confirm/go-ahead reply
    (e.g. "yes", "confirm", "confirm cancellation", "go ahead", "proceed"),
    false otherwise
  "reason": a short reason IF the employee actually gave one for cancelling
    (e.g. "my plans changed", "no longer needed"), or null if none is stated —
    do NOT invent one just because this is a cancellation

Rules:
- Today's date is {today_str}.
- CRITICAL: any slash- or dash-separated numeric date (e.g. "25/08/2026",
  "08/25/2026", "05-03-2026") is DD/MM/YYYY (day first), NEVER MM/DD/YYYY —
  this applies even when both numbers are <= 12 and the format looks
  ambiguous. Do NOT default to US month-first convention.
  - "25/08/2026" -> 2026-08-25, "08/25" (this year) -> 2026-08-25
  - "05-03-2026" -> 2026-03-05 (5th of March, NOT May 3rd)
- Output ONLY the JSON object. No explanation, no markdown fences.
- Only fill a field the message actually mentions — leave others null.
- Do not guess a leave_type or date that isn't actually implied by the message."""


# ── Non-HR redirect fallback templates ─────────────────────────────────────────
# Used only when the LLM-generated redirect (hr_graph.py's non_hr_node) fails.
_NON_HR_FALLBACKS = [
    "That's outside my area — I'm an HR specialist. Ask me about leave policies, payroll, recruitment, or compliance and I'll get you sorted.",
    "I only cover HR and workforce topics. If you have questions on compensation, onboarding, performance, or employee benefits, I'm here to help.",
    "My expertise is HR only. Feel free to ask about leave policies, payroll, hiring, or employee management — that's exactly what I'm here for.",
    "That's not something I can help with — I focus purely on HR topics. Try me on attendance, compliance, recruitment, or employee relations.",
    "I specialise in HR only. Questions on workforce management, payroll, benefits, or compliance? I'm ready.",
]


def _get_fallback_redirect(query: str) -> str:
    """Pick a varied fallback template using query hash so the same non-HR topic
    never shows exactly the same message twice across sessions."""
    import hashlib
    idx = int(hashlib.md5(query.lower().encode()).hexdigest(), 16) % len(_NON_HR_FALLBACKS)
    # Extract a short topic label from the query for template interpolation
    words = [w for w in query.split() if len(w) > 3]
    topic = " ".join(words[:3]) if words else "that topic"
    return _NON_HR_FALLBACKS[idx].replace("{topic}", topic)


# ── Build human-readable summary from structured LLM response ─────────────────
def _build_user_message(intent: str, data: Dict) -> str:
    try:
        ans = data.get("answer", "")

        if intent in ("greeting", "small_talk"):
            return ans or "Hello! How can I help you with an HR question today?"
        if intent == "capabilities_inquiry":
            return ans or "I'm Helix AI Assistant — your HR specialist. Ask me anything about leave, payroll, recruitment, compliance, and more!"

        if intent == "salary":
            return (
                f"A {data.get('role')} typically earns {data.get('salary_range')} "
                f"in {data.get('location')}. {data.get('insights', '')}"
            )
        if intent == "skills":
            skills = ", ".join(data.get("required_skills", []))
            tools  = ", ".join(data.get("tools", []))
            return (
                f"For a {data.get('role')} role with {data.get('experience')} experience, "
                f"key skills: {skills}. Tools: {tools}."
            )
        if intent == "experience":
            return (
                f"For a {data.get('role')}, {data.get('experience_expectations')}. "
                f"Career path: {data.get('career_path')}."
            )
        if intent == "job_description":
            resp = ", ".join(data.get("responsibilities", []))
            return f"{data.get('job_title')}: {data.get('summary')}. Responsibilities: {resp}."
        if intent == "interview_questions":
            return (
                f"Interview questions for a {data.get('role')} "
                f"with {data.get('experience')} experience."
            )
        if intent == "leave_policy":
            return ans or "Here is the leave policy information."
        if intent == "payroll":
            return ans or "Here is the payroll information."
        if intent == "attendance":
            return ans or "Here is the attendance policy information."
        if intent == "recruitment":
            return ans or "Here is the recruitment guidance."
        if intent == "benefits":
            return ans or "Here are the employee benefits details."
        if intent == "performance":
            return ans or "Here is the performance management guidance."
        if intent == "employee_management":
            return ans or "Here is the employee management guidance."
        if intent == "onboarding":
            return ans or "Here is the onboarding information."
        if intent == "training":
            return ans or "Here is the training and development information."
        if intent == "compliance":
            return ans or "Here is the compliance and labor law guidance."

        return ans or "Here is the information you requested."

    except Exception:
        return data.get("answer", "Here is the information you requested.")




async def classify_intent_structured(
    prompt: str, valid_labels: frozenset, fallback_label: str = "general_hr",
) -> tuple[str, Optional[dict], bool]:
    """Returns (label, usage, classification_failed). label is always a
    member of valid_labels — classification_failed is True when that label
    is only there because the real classification attempt broke (the LLM
    call raised, or it returned something outside valid_labels), as opposed
    to the LLM genuinely picking fallback_label on its own merits. Callers
    that care about the difference (e.g. surfacing a "not sure what you
    mean" reply instead of silently guessing) should check this flag rather
    than comparing the label to fallback_label, since a legitimate query
    can resolve to that same label."""
    json_instruction = (
        '\n\nRespond with ONLY a JSON object of the exact shape {"intent": "<label>"} '
        "— no other text, no markdown fences, no explanation."
    )
    full_prompt = prompt + json_instruction

    try:
        if ACTIVE_LLM_PROVIDER == "deepseek":
            raw = await _call_classification_deepseek(full_prompt)
        elif ACTIVE_LLM_PROVIDER == "race":
            raw = await _call_classification_race(full_prompt, sorted(valid_labels))
        elif ACTIVE_LLM_PROVIDER == "openai":
            raw = await _call_classification_openai(full_prompt, sorted(valid_labels))
        else:
            raise ValueError(f"Unknown LLM provider: '{ACTIVE_LLM_PROVIDER}'. Valid: deepseek, openai, race")
    except Exception as e:
        logger.exception(f"[Classify] structured classification call failed: {e}")
        return fallback_label, None, True

    usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
    text = _extract_text(raw)
    parsed = _safe_json_parse(text)
    label = str(parsed.get("intent", "")).strip().lower()

    if label not in valid_labels:
        logger.warning(
            "[Classify] LLM returned unrecognized label %r (raw text: %r) — falling back to %r",
            label, text[:200], fallback_label,
        )
        return fallback_label, usage, True

    return label, usage, False


async def _call_classification_deepseek(prompt: str) -> Dict[str, Any]:
    if not DEEPSEEK_API_KEY:
        raise ValueError("DEEPSEEK_API_KEY is not set")
    payload = {
        "model": DEEPSEEK_INTENT_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 30,
        "temperature": 0,
        # DeepSeek's OpenAI-compatible JSON mode — guarantees valid JSON, not
        # a specific schema/enum (unlike OpenAI's strict json_schema below),
        # so the prompt spells out the exact key/shape and the caller still
        # validates "intent" against the known label set regardless.
        "response_format": {"type": "json_object"},
        "stream": False,
    }
    headers = {"Authorization": f"Bearer {DEEPSEEK_API_KEY}", "Content-Type": "application/json"}
    resp = await _http.post(DEEPSEEK_URL, json=payload, headers=headers)
    resp.raise_for_status()
    return resp.json()


async def _call_classification_openai(prompt: str, valid_labels: list) -> Dict[str, Any]:
    if not OPENAI_API_KEY:
        raise ValueError("OPENAI_API_KEY is not set")
    payload = {
        "model": OPENAI_INTENT_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        # max_completion_tokens (not max_tokens) works across all current
        # chat models, including reasoning-tier ones that reject max_tokens
        # outright — see the identical fix already made for the non-HR
        # redirect path (_call_openai_chat_stream) for the live 400 this
        # avoided there.
        "max_completion_tokens": 30,
        "temperature": 0,
        # Strict JSON schema — OpenAI enforces the enum at the API level, so
        # a malformed/off-list value can't come back at all (the DeepSeek
        # path can't get this guarantee, hence the extra server-side check
        # in classify_intent_structured applying to both providers equally).
        "response_format": {
            "type": "json_schema",
            "json_schema": {
                "name": "intent_classification",
                "strict": True,
                "schema": {
                    "type": "object",
                    "properties": {"intent": {"type": "string", "enum": valid_labels}},
                    "required": ["intent"],
                    "additionalProperties": False,
                },
            },
        },
        "stream": False,
    }
    headers = {"Authorization": f"Bearer {OPENAI_API_KEY}", "Content-Type": "application/json"}
    resp = await _http.post(OPENAI_CHAT_URL, json=payload, headers=headers)
    resp.raise_for_status()
    return resp.json()


async def _call_classification_race(prompt: str, valid_labels: list) -> Dict[str, Any]:
    if not RACE_API_KEY:
        raise ValueError("RACE_API_KEY is not set")
    payload = {
        "model": RACE_API_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        # RACE_API_MODEL (gpt-oss-120b) is a reasoning-tier model: it burns
        # completion tokens on a hidden "reasoning" field *before* writing
        # the visible "content" field, and if max_tokens runs out first,
        # content comes back null with finish_reason="length" — live-tested,
        # a 30-token budget (the OpenAI gpt-4o-mini equivalent) never
        # reaches content at all. reasoning_effort="low" cuts that overhead
        # roughly a third but doesn't eliminate it, so this still needs a
        # much larger budget than the non-reasoning OpenAI/DeepSeek classifiers.
        "max_tokens": 200,
        "reasoning_effort": "low",
        "temperature": 0,
        # Enforced server-side only if the vLLM instance behind race-api is
        # running with a guided-decoding backend — if it isn't, this is
        # advisory only, and the valid_labels check in
        # classify_intent_structured is what actually guarantees a safe
        # label comes back (same safety net DeepSeek's non-strict JSON mode
        # already relies on above).
        "response_format": {
            "type": "json_schema",
            "json_schema": {
                "name": "intent_classification",
                "strict": True,
                "schema": {
                    "type": "object",
                    "properties": {"intent": {"type": "string", "enum": valid_labels}},
                    "required": ["intent"],
                    "additionalProperties": False,
                },
            },
        },
        "stream": False,
    }
    headers = {"x-api-key": RACE_API_KEY, "Content-Type": "application/json"}
    resp = await _http.post(RACE_API_CHAT_URL, json=payload, headers=headers)
    resp.raise_for_status()
    return resp.json()


# ── Structured date-field extraction (tier 2 of the date-hallucination fix) ──
# Same "force the model to pick from a fixed vocabulary" problem
# classify_intent_structured solves for intent labels, applied to date
# expressions instead. The model NEVER computes or outputs a final date —
# only these six structured fields; services.date_resolver.resolve_
# structured_date (pure, already-tested arithmetic, no LLM) turns them into
# an actual date. This is the fix for the recurring live-bug shape this
# session kept hitting: a new English phrasing of an already-computable
# date concept had no regex pattern yet, so the model was asked to compute
# the final date itself and got the arithmetic wrong. Structured-field
# extraction is a parsing task (the model's strength); date arithmetic
# stays 100% in deterministic Python (its weak point, entirely removed).
_DATE_FIELD_ENUMS = {
    "target_weekday": ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"],
    "weekday_relation": ["this", "next", "next_to_next"],
    "ordinal": ["first", "second", "third", "fourth", "last"],
}
_MAX_MONTH_OFFSET = 12  # bounds an obviously-runaway extraction, not a real product limit


def _build_structured_date_extraction_prompt(query: str, today: datetime.date) -> str:
    today_str = today.isoformat()
    return f"""You are extracting structured fields describing a date expression from an employee's message — you do NOT compute or output a final date yourself. A separate deterministic system does all date arithmetic from the fields you extract.

Today's date is {today_str}.

Current user message: "{query}"

Extract and return ONLY a JSON object with exactly these keys:
  "day_offset": a signed integer number of days from today (0=today, 1=tomorrow, -1=yesterday, 2=day after tomorrow), or null if the message doesn't use a simple day-offset phrase like this. Also covers a bare duration-offset phrase: "in two weeks"=14, "a month from now"=30, "15 days from now"=15, "after 10 days"=10.
  "target_weekday": one of monday/tuesday/wednesday/thursday/friday/saturday/sunday if the message names a weekday, or null. "week" is NOT a weekday — "first week of next month" names no day at all (target_weekday must stay null there), only "first Monday of next month" does. Never guess which day of the week is meant just because an ordinal ("first"/"second"/...) is present.
  "weekday_relation": ONLY set when target_weekday is set AND there is no month reference (no "of next month" / "this month" style anchor) —
    "this"          — "this Wednesday", "coming Wednesday", "upcoming Wednesday" (nearest occurrence, inclusive of today)
    "next"          — "next Wednesday" (nearest occurrence strictly after today, never today itself)
    "next_to_next"  — "next to next Wednesday", "the Wednesday after next", "week after next Wednesday"
    null if not applicable.
  "ordinal": ONLY set when the message anchors the weekday to a specific month — "first"/"second"/"third"/"fourth"/"last" (e.g. "second Friday", "last Wednesday"), or null.
  "month_offset": ONLY set together with ordinal — a non-negative integer count of months from today's own month: 0="this month", 1="next month", 2="the month after next" / "2 months from now", 3="3 months from now", etc. Read the actual number the message states — do NOT default to 1 ("next month") when a different, larger count is stated ("next 2 months" is month_offset=2, NOT 1. If you cannot tell exactly how many months, leave both ordinal and month_offset null rather than guessing a count). Do NOT set this for an explicitly NAMED month (e.g. "October") — leave both ordinal and month_offset null in that case.
  "duration_days": a plain integer count of days if the message states an explicit duration ("3 days"=3, "a week"=7, "two weeks"=14, "Wednesday to Friday"=3 inclusive), or null if no duration is stated.

Rules:
- Set day_offset ONLY for simple day-offset phrases. Set target_weekday+weekday_relation for a bare weekday reference with no month anchor. Set target_weekday+ordinal+month_offset for a month-anchored weekday reference. NEVER set more than one of these three shapes at once — if the message is ambiguous or doesn't clearly match exactly one shape, leave the relevant fields null rather than guessing.
- For a bare two-weekday range with NO modifier word on either side ("Wednesday to Friday", "Monday to Wednesday" — no "next"/"this"/"coming"/"upcoming" anywhere near either weekday), leave weekday_relation null even though duration_days can still be set (e.g. "Wednesday to Friday" -> target_weekday="wednesday", weekday_relation=null, duration_days=3). Which week "Wednesday" falls in is genuinely ambiguous without a modifier — do not guess "this" or "next" just because one has to be picked.
- If you are not fully confident in a field's value, leave it null. A null field is handled safely downstream; a wrong guess — including silently rounding an unusual count down to the nearest value you're more sure about — is not. Never approximate.
- Output ONLY the JSON object. No explanation, no markdown fences."""


async def extract_structured_date_fields(query: str, today: datetime.date) -> tuple[dict, Optional[dict]]:
    """Returns (fields, usage). fields always has all six keys, each either
    a validated enum/int value or None — an off-vocabulary value from a
    non-strict-schema provider (DeepSeek) is normalized to None rather than
    passed through, same "never let a malformed value escape" guarantee
    classify_intent_structured gives for intent labels."""
    prompt = _build_structured_date_extraction_prompt(query, today)
    empty_fields = {
        "day_offset": None, "target_weekday": None, "weekday_relation": None,
        "ordinal": None, "month_offset": None, "duration_days": None,
    }
    try:
        if ACTIVE_LLM_PROVIDER == "deepseek":
            raw = await _call_structured_date_deepseek(prompt)
        elif ACTIVE_LLM_PROVIDER == "race":
            raw = await _call_structured_date_race(prompt)
        elif ACTIVE_LLM_PROVIDER == "openai":
            raw = await _call_structured_date_openai(prompt)
        else:
            raise ValueError(f"Unknown LLM provider: '{ACTIVE_LLM_PROVIDER}'. Valid: deepseek, openai, race")
    except Exception as e:
        logger.exception(f"[StructuredDate] extraction call failed: {e}")
        return empty_fields, None

    usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
    parsed = _safe_json_parse(_extract_text(raw))

    fields = dict(empty_fields)
    for key in ("day_offset", "duration_days"):
        value = parsed.get(key)
        if isinstance(value, int) and not isinstance(value, bool):
            fields[key] = value
    # month_offset must be non-negative and within a sane bound — an
    # off-vocabulary value here (a negative count, or a wildly large one
    # that's more likely a parsing slip than a genuine request) is treated
    # the same as "not extracted" rather than passed through.
    month_offset = parsed.get("month_offset")
    if isinstance(month_offset, int) and not isinstance(month_offset, bool) and 0 <= month_offset <= _MAX_MONTH_OFFSET:
        fields["month_offset"] = month_offset
    for key, allowed in _DATE_FIELD_ENUMS.items():
        value = parsed.get(key)
        if isinstance(value, str) and value.lower() in allowed:
            fields[key] = value.lower()
    return fields, usage


async def _call_structured_date_deepseek(prompt: str) -> Dict[str, Any]:
    if not DEEPSEEK_API_KEY:
        raise ValueError("DEEPSEEK_API_KEY is not set")
    payload = {
        "model": DEEPSEEK_INTENT_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 80,
        "temperature": 0,
        "response_format": {"type": "json_object"},
        "stream": False,
    }
    headers = {"Authorization": f"Bearer {DEEPSEEK_API_KEY}", "Content-Type": "application/json"}
    resp = await _http.post(DEEPSEEK_URL, json=payload, headers=headers)
    resp.raise_for_status()
    return resp.json()


async def _call_structured_date_openai(prompt: str) -> Dict[str, Any]:
    if not OPENAI_API_KEY:
        raise ValueError("OPENAI_API_KEY is not set")
    payload = {
        "model": OPENAI_INTENT_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "max_completion_tokens": 80,
        "temperature": 0,
        "response_format": {
            "type": "json_schema",
            "json_schema": {
                "name": "structured_date_fields",
                "strict": True,
                "schema": {
                    "type": "object",
                    "properties": {
                        "day_offset": {"type": ["integer", "null"]},
                        "target_weekday": {"type": ["string", "null"], "enum": [*_DATE_FIELD_ENUMS["target_weekday"], None]},
                        "weekday_relation": {"type": ["string", "null"], "enum": [*_DATE_FIELD_ENUMS["weekday_relation"], None]},
                        "ordinal": {"type": ["string", "null"], "enum": [*_DATE_FIELD_ENUMS["ordinal"], None]},
                        "month_offset": {"type": ["integer", "null"]},
                        "duration_days": {"type": ["integer", "null"]},
                    },
                    "required": [
                        "day_offset", "target_weekday", "weekday_relation",
                        "ordinal", "month_offset", "duration_days",
                    ],
                    "additionalProperties": False,
                },
            },
        },
        "stream": False,
    }
    headers = {"Authorization": f"Bearer {OPENAI_API_KEY}", "Content-Type": "application/json"}
    resp = await _http.post(OPENAI_CHAT_URL, json=payload, headers=headers)
    resp.raise_for_status()
    return resp.json()


async def _call_structured_date_race(prompt: str) -> Dict[str, Any]:
    if not RACE_API_KEY:
        raise ValueError("RACE_API_KEY is not set")
    payload = {
        "model": RACE_API_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        # See the identical reasoning-tier-overhead note in
        # _call_classification_race — live-tested against race-api, this
        # prompt's own reasoning trace alone ran ~180 tokens before content
        # even started, so the 80-token OpenAI-equivalent budget would
        # reliably return content=null here.
        "max_tokens": 400,
        "reasoning_effort": "low",
        "temperature": 0,
        "response_format": {
            "type": "json_schema",
            "json_schema": {
                "name": "structured_date_fields",
                "strict": True,
                "schema": {
                    "type": "object",
                    "properties": {
                        "day_offset": {"type": ["integer", "null"]},
                        "target_weekday": {"type": ["string", "null"], "enum": [*_DATE_FIELD_ENUMS["target_weekday"], None]},
                        "weekday_relation": {"type": ["string", "null"], "enum": [*_DATE_FIELD_ENUMS["weekday_relation"], None]},
                        "ordinal": {"type": ["string", "null"], "enum": [*_DATE_FIELD_ENUMS["ordinal"], None]},
                        "month_offset": {"type": ["integer", "null"]},
                        "duration_days": {"type": ["integer", "null"]},
                    },
                    "required": [
                        "day_offset", "target_weekday", "weekday_relation",
                        "ordinal", "month_offset", "duration_days",
                    ],
                    "additionalProperties": False,
                },
            },
        },
        "stream": False,
    }
    headers = {"x-api-key": RACE_API_KEY, "Content-Type": "application/json"}
    resp = await _http.post(RACE_API_CHAT_URL, json=payload, headers=headers)
    resp.raise_for_status()
    return resp.json()
