"""services/shift_query.py

Shift Assignment Query (FR-06.1) — answers "what shift am I assigned?" (or,
now, "what shift is <name> on?") with the target employee's currently-active
shift assignment, rendered as a summary card (name, start time, end time,
any other relevant detail available).

Strict scope boundary (per the story): no location, no timezone, no
weekly-schedule view, no shift-change request — this node only ever
resolves the CURRENTLY-active shift assignment.

Dates: a day named in the query ("what shift do I have on Friday?") is
extracted and reported back as data["date"], and labels the card. It does
NOT select the data, because there is nothing to select from — erp-api's
/shift-details accepts no date parameter and is live-verified to return
byte-identical output for a future date, a 2020 date, and an unparseable
string. So the shift shown is always the current assignment, and whenever
the labelled day is not today the card says so in as many words
(data["date_from_query"] carries the same fact for a UI). Forwarding the
date to erp-api and presenting whatever came back as that day's shift
would be a confidently wrong answer, not a feature.
Display only: nothing here computes, infers, or edits shift data — it
renders exactly what erp_client.get_active_shift() returns, or the defined
"No Active Shift Assigned" state (AC4) when there isn't one.

Who may see whose shift (FR-06.4), decided before any erp-api call:

  * EVERY caller sees their own. That is the whole answer for an ordinary
    employee — a query naming another employee, or a whole team, is refused
    with TEAMMATE_SHIFT_DENIAL before the lookup, so no shift data for
    anyone else is ever fetched (AC3). The wording is fixed and carries no
    target detail, so it reveals nothing about whether that employee exists
    (AC2).
  * A MANAGER, an HR user or an ADMIN also sees their team. A named target
    is forwarded to erp-api, which is the authority on who is actually in
    their team and answers 403 with its own message for anyone who is not; a
    team-scoped ask ("what shift is assigned to my team") is answered with
    the roster erp-api resolves, to name one of. _may_view_team_shifts owns
    that decision and fails closed — an unconfirmed role is an employee.

Targets are found two ways, and both feed the same gate: a NAMED individual
via ai_service.extract_shift_target_fields, and a COLLECTIVE subject ("my
team", "all employees") via _is_collective_shift_scope — the latter names no
individual, so the extractor reports nothing and, without its own detector,
such a query read as "no target", i.e. as the caller themselves.

One wrinkle in "every caller sees their own": erp-api's /shift-details cannot
serve a MANAGER's own record — for a caller with direct reports it answers
with a menu of those reports instead. That case is resolved from
/attendance/punch-details, which can. No employee param is sent either way,
so the caller's own token is always what selects the record.
"""
import logging
import os
import re
from datetime import date, datetime
from typing import Optional
from zoneinfo import ZoneInfo

from langgraph.types import StreamWriter

import services.ai_service as ai_service
import services.erp_client as erp_client
import services.attendance as attendance_mod
import services.permission_service as permission_service
from services.nlp_service import is_week_off_query
from services.ownership_guard import _mentions_own_identity
from services.regularisation_display import shift_hhmm, time_24h

logger = logging.getLogger(__name__)

NO_ACTIVE_SHIFT_MESSAGE = "No Active Shift Assigned."

# HA-192 (FR-06.4) — the exact, approved wording for refusing a shift query
# that targets another employee. Must match character-for-character. It is
# deliberately worded differently from erp-api's own access-control message
# ("I cannot retrieve information for other employees. You can only access
# your own records.") and must never be replaced by it.
TEAMMATE_SHIFT_DENIAL = "I can only provide shift details for your own account."


# A shift question whose SUBJECT is a group rather than one person — "what
# shift is assigned to my team", "team shift details", "shift timings of all
# employees". The named-target gate below cannot see these: they name nobody,
# so ai_service.extract_shift_target_fields correctly returns no employee_id
# and no employee_name, is_targeted_lookup stayed False, and the query was
# answered as if the caller had asked about THEMSELVES.
#
# The live symptom: an employee asking "what shift assigned to my team" got
# their OWN shift card back — an answer to a question they did not ask, and
# one that reads as though the assistant has team-wide shift visibility.
#
# So a collective subject goes through the same role gate a named teammate
# does, BEFORE any erp-api call (and before the extraction call — this is
# deterministic, so it neither needs nor waits for an LLM's reading of who
# the subject is). An employee is refused with the same approved wording and
# the same payload; a manager, HR user or admin is answered with the team
# erp-api resolves for their token.
#
# Deliberately NOT a general "does this mention a group" test: it only ever
# matches an explicit collective subject, so ordinary self phrasings ("my
# shift", "my shift timing", "what shift am I assigned") score nothing here
# and are untouched. "employee"/"member" are matched in the PLURAL only —
# "shift details of employee 3754" is a singular, possibly-self lookup that
# the identity checks below own.
_COLLECTIVE_SHIFT_SCOPE_PATTERNS = (
    # "my team", "the team's shift", "team shift details", "teammates"
    re.compile(r"\bteams?\b|\bteam-?mates?\b", re.IGNORECASE),
    # the reporting line: "my reports", "direct reports", "reportees"
    re.compile(r"\b(?:direct\s+)?reportees?\b|\b(?:my|our|his|her|their)\s+"
               r"(?:direct\s+)?reports?\b|\bdirect\s+reports?\b|"
               r"\bsubordinates?\b", re.IGNORECASE),
    # the wider org: "my department", "the whole staff", "our org"
    re.compile(r"\bdepartments?\b|\bdept\b|\bstaff\b|"
               r"\bcolleagues?\b|\bco-?workers?\b|"
               r"\b(?:my|our|the)\s+(?:whole\s+|entire\s+)?"
               r"(?:group|org|organisation|organization|company)\b", re.IGNORECASE),
    # explicit "all of them": "everyone", "all employees", "every member"
    re.compile(r"\beveryone\b|\beverybody\b|\bemployees\b|"
               r"\b(?:all|every|each)\s+(?:of\s+)?(?:my|our|the)?\s*"
               r"(?:employees?|members?|people|staff)\b", re.IGNORECASE),
    # someone else, unnamed: "other employees' shift", "other members"
    re.compile(r"\bother\s+(?:employees?|members?|people|staff)\b", re.IGNORECASE),
)


def _may_view_team_shifts(state: dict, claims: dict) -> bool:
    """True when this caller may see a TEAM MEMBER's shift, not just their
    own — a manager, an HR user, or a company administrator.

    Delegates to services.permission_service, which owns that rule for every
    team-scoped capability (team leave, team attendance, individual reports,
    regularisation views, this). Kept as a named function here because this
    node's gate reads better for it, and because the shift route is the one
    place that ALSO has to fail closed on a tri-state: only an explicit True
    allows, so MANAGER_UNKNOWN (erp-api unreachable) is refused rather than
    guessed at.

    erp-api remains the last word regardless — it enforces which employees
    are actually in the caller's team and answers 403 with its own message
    for one who isn't.
    """
    return permission_service.may_view_team(state, claims=claims) is True


def _is_collective_shift_scope(query: str) -> bool:
    """True when the shift question is about a GROUP (team, department,
    reports, everyone) rather than the caller.

    Deterministic by design: this is a permission decision, and the same
    question must be refused identically on every run — it must not depend
    on an LLM extractor that reports only NAMED individuals and therefore
    reads "my team" as "no target at all", i.e. as the caller themselves.
    """
    return any(p.search(query or "") for p in _COLLECTIVE_SHIFT_SCOPE_PATTERNS)


# erp-api's /shift-details and /attendance/punch-details describe the SAME
# shift object with different field names — {shift_id, shift_name,
# week_off_day} here, {id, name, week_off_days} there. Renaming rather than
# teaching _render_shift_card two vocabularies keeps one card definition, and
# keeps the AC1 "any other relevant detail" pass reading one set of names.
#
# Only the fields the card actually shows are carried across. punch-details'
# remaining keys (id, relief_time, status) are the same bookkeeping
# _SHIFT_NOISE_FIELDS already suppresses under /shift-details' own names — a
# passthrough would print them back as "Relief Time: 15" purely because the
# spelling changed.
def _shift_from_punch_details(shift) -> dict:
    """The /shift-details-shaped shift object for a punch-details `shift`
    block, or {} when that day carries no shift (live-verified: the key is
    null on a week off)."""
    if not isinstance(shift, dict) or not shift.get("name"):
        return {}
    normalised = {
        "shift_id": shift.get("id"),
        "shift_name": shift.get("name"),
        "start_time": shift.get("start_time"),
        "end_time": shift.get("end_time"),
        "week_off_day": shift.get("week_off_days"),
    }
    return {key: value for key, value in normalised.items() if value not in (None, "", [])}


def _today_in_app_timezone():
    """The day the answer is for. Same configured-timezone notion of today
    the rest of the app uses (hr_graph._today_in_app_timezone,
    individual_report._today_in_app_timezone) rather than a server-local
    date.today() that could disagree with the company's actual day near
    midnight — the shift shown would then be labelled with the wrong day."""
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()


# Fields already covered by their own dedicated lines in _render_shift_card;
# excluded from the generic "any other relevant detail" pass so nothing is
# shown twice.
_SHIFT_CORE_FIELDS = {"shift_id", "shift_name", "start_time", "end_time"}

# Internal/technical fields confirmed present on the live erp-api shift
# object that aren't meaningful to an employee reading their own shift
# summary (bookkeeping ids/flags and nested session bookkeeping, not
# assignment info) — excluded from the generic "any other relevant detail"
# pass rather than dumped raw (e.g. session_summary is itself a dict).
_SHIFT_NOISE_FIELDS = {
    "shift_code", "shift_type", "working_minutes", "break_time_minutes",
    "relief_time_minutes", "status", "is_general_shift", "is_readonly",
    "session_summary", "sessions",
}


def _join_days(days: list) -> str:
    days = [str(d) for d in days if d]
    return days[0] if len(days) == 1 else ", ".join(days[:-1]) + " and " + days[-1]


def _render_week_off(shift: dict, calendar: Optional[dict],
                     subject_name: Optional[str] = None) -> str:
    """The weekly off on its own - what was asked - from the shift
    assignment, else the work calendar. Never inferred when neither has it."""
    days = shift.get("week_off_day") or (calendar or {}).get("week_off_days") or []
    if isinstance(days, str):
        days = [days]
    whose = f"**{subject_name}**'s" if subject_name else "Your"
    name = shift.get("shift_name") or "your shift"
    if not days:
        return (f"{whose} shift (**{name}**) doesn't list a weekly off. HR can confirm "
                f"{'their' if subject_name else 'your'} off days.")
    return f"{whose} weekly off is **{_join_days(days)}** (shift: {name})."


def _render_shift_card(shift: dict, subject_name: Optional[str] = None,
                       as_of=None, as_of_is_requested: bool = False) -> str:
    """Pure string formatting of whatever erp-api returned for the active
    shift — name, start/end time, plus any other non-noise field present
    (e.g. week_off_day) surfaced generically. subject_name is the resolved
    employee's own name from the response, only passed when this was a
    lookup of someone else (not the caller's own shift).

    as_of is the date this answer is for. erp-api's /shift-details response
    carries no date of its own — it answers for "right now" — so the day is
    stated explicitly rather than left for the reader to assume, which also
    keeps a card that gets saved to chat history readable later. This is
    still not a specific-date lookup: it labels the answer, it does not
    select it.

    as_of_is_requested marks that as_of came from the QUERY rather than
    being today. erp-api has no per-date shift data — live-verified: the
    endpoint returns byte-identical output for a future date, a 2020 date
    and an unparseable string — so what is shown is still the CURRENT
    assignment. Saying so is the whole point of the flag: a card headed
    with the date the reader asked for, silently carrying today's
    assignment, is a confidently wrong answer."""
    name = shift.get("shift_name") or "Unnamed Shift"
    if subject_name:
        lines = [f"**{subject_name}** is currently assigned to **{name}**."]
    else:
        lines = [f"You're currently assigned to **{name}**."]

    detail_bits = []
    if as_of is not None:
        detail_bits.append(f"Date: {as_of.strftime('%A, %d %B %Y')}")

    # HH:MM ("09:00–18:30"), not erp-api's "09:00:00".
    start = time_24h(shift.get("start_time"))
    end = time_24h(shift.get("end_time"))
    if start and end:
        detail_bits.append(f"Timing: {start}–{end}")
    if detail_bits:
        lines.append("\n".join(detail_bits))

    extra_bits = []
    if as_of_is_requested:
        extra_bits.append(
            "Note: this is the current shift assignment — I don't have a separate "
            "shift record for that date."
        )
    week_off_day = shift.get("week_off_day")
    if week_off_day:
        extra_bits.append(f"Week off: {', '.join(week_off_day) if isinstance(week_off_day, list) else week_off_day}")
    for key, value in shift.items():
        if key in _SHIFT_CORE_FIELDS or key == "week_off_day" or key in _SHIFT_NOISE_FIELDS or value in (None, "", []):
            continue
        extra_bits.append(f"{key.replace('_', ' ').title()}: {value}")
    if extra_bits:
        lines.append("\n".join(extra_bits))

    return "\n\n".join(lines)


async def shift_query_node(state: dict, writer: StreamWriter) -> dict:
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    query = state.get("query", "")
    usage_events = list(state.get("usage_events", []))
    # The day this answer is labelled with: the date named in the query when
    # there is one, otherwise today. erp-api's /shift-details carries no date
    # of its own and accepts none — live-verified, it returns byte-identical
    # output for a future date, a 2020 date and an unparseable string — so a
    # requested date can only ever LABEL the answer, never select it. The
    # shift shown is the current assignment either way, and the card says so
    # whenever the two differ (see _render_shift_card's as_of_is_requested).
    today = _today_in_app_timezone()
    as_of = today
    as_of_is_requested = False

    def _finish(message: str, extra_data: Optional[dict] = None) -> dict:
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)
        writer({"type": "done", "intent": "shift_query", "is_hr": True,
                "data": data, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    # Collective-scope gate — checked FIRST, before the extraction call below.
    # "what shift assigned to my team" names no individual, so the extractor
    # reports no target and every downstream check reads the query as a plain
    # self lookup: an employee was answered with their OWN shift card, and a
    # manager with erp-api's list of their reports. Neither is an answer to
    # the question that was asked, and both imply a team-shift capability
    # this route does not have. Same refusal as a named teammate, for every
    # role, with no erp-api call made — see _is_collective_shift_scope.
    claims = attendance_mod._decode_jwt_claims(bearer_token)
    may_view_team = _may_view_team_shifts(state, claims)
    wants_team_scope = _is_collective_shift_scope(query)

    if wants_team_scope and not may_view_team:
        logger.info(
            "[ShiftQuery] collective-scope shift query denied pre-fetch - caller may only "
            "see their own shift (is_manager=%r is_hr_role=%r company_id=%s)",
            state.get("is_manager"), state.get("is_hr_role"), company_id,
        )
        writer({"type": "shift_summary", "data": {"has_active_shift": False, "denied": True}})
        return _finish(TEAMMATE_SHIFT_DENIAL,
                       extra_data={"has_active_shift": False, "denied": True})

    target_fields, target_usage = await ai_service.extract_shift_target_fields(query, today)
    if target_usage:
        usage_events.append({"source": "shift_target_extraction", "usage": target_usage})
    target_employee_id = target_fields.get("employee_id")
    target_employee_name = target_fields.get("employee_name")
    is_targeted_lookup = bool(target_employee_id or target_employee_name)

    # Naming YOURSELF is not a teammate lookup. The extractor reports any
    # named person, and it has no idea who is asking — so "what is geo1's
    # shift" asked BY geo1 arrived here as a targeted lookup and was refused
    # its own record with "I can only provide shift details for your own
    # account", which is both wrong and confusing.
    #
    # ownership_guard closed exactly this hole one node upstream (see
    # _mentions_own_identity's docstring) and then deliberately waves every
    # shift phrasing through on the grounds that THIS node applies FR-06.4's
    # check itself — so the self-identity half has to live here too, or it
    # falls between the two nodes, which is what happened.
    #
    # Reuses the guard's own matcher rather than a second copy: it requires a
    # FULL name match or an exact emp_no token, so "Akash" cannot self-match
    # a different "Akash Kumar". Downgrading to a self lookup (rather than
    # allowing a targeted one) means erp-api is called with no target at all,
    # exactly as for "what is my shift" — the caller's token is what selects
    # the record, so this cannot widen access to anyone else.
    #
    # A THIRD self-match dimension beyond name/emp_no: the numeric employee
    # ID. The JWT's own "user_id" claim IS the caller's erp employee_id
    # (confirmed against a live token: user_id 3754 for emp_no DEMO0604262,
    # role_name "hr") — compared directly against the STRUCTURED extraction
    # rather than text-searched, since a bare id ("shift details of employee
    # 3754") carries no name or emp_no substring for _mentions_own_identity
    # to find in the query text at all. Without this, asking about your own
    # numeric id was indistinguishable from asking about a teammate's and
    # got denied your own record.
    if is_targeted_lookup:
        caller_name = (claims.get("name") or claims.get("username")
                       or claims.get("preferred_username"))
        caller_user_id = claims.get("user_id")
        is_self_by_id = (
            target_employee_id is not None and caller_user_id is not None
            and str(target_employee_id) == str(caller_user_id)
        )
        if is_self_by_id or _mentions_own_identity(query, caller_name, claims.get("emp_no")):
            logger.info("[ShiftQuery] query names the caller themselves - "
                        "treating as an own-shift lookup, not a teammate one")
            is_targeted_lookup = False
            target_employee_id = None
            target_employee_name = None

    # FR-06.4 — permission gate. A shift query about anyone other than the
    # caller is refused here, before the erp-api call below, so a teammate
    # lookup is never fetched-then-discarded (AC3), and the denial string is
    # fixed and carries no target detail: it neither confirms nor denies the
    # record and cannot be used to enumerate people (AC2).
    #
    # Refused for an ORDINARY EMPLOYEE. A manager, an HR user or an admin is
    # let through to erp-api's own per-target team scope — which is the
    # authority on whether that particular employee is in their team, and
    # answers 403 with its own message when they are not (surfaced by the
    # business-failure branch below, like any other erp-api answer).
    #
    # HA-192 briefly made this self-only for EVERY role, which is what the
    # git history of this block describes; that was reversed deliberately —
    # the denial copy itself says "you'll need manager or HR access to view
    # that", so denying the people who HAVE that access answered no one.
    # _may_view_team_shifts owns the role question, and fails closed.
    if is_targeted_lookup and not may_view_team:
        logger.info(
            "[ShiftQuery] teammate shift query denied pre-fetch - caller may only see "
            "their own shift (is_manager=%r is_hr_role=%r company_id=%s)",
            state.get("is_manager"), state.get("is_hr_role"), company_id,
        )
        writer({"type": "shift_summary", "data": {"has_active_shift": False, "denied": True}})
        return _finish(TEAMMATE_SHIFT_DENIAL,
                       extra_data={"has_active_shift": False, "denied": True})

    requested_date = target_fields.get("requested_date")
    if requested_date:
        try:
            parsed_date = date.fromisoformat(requested_date)
        except ValueError:
            logger.warning("[ShiftQuery] discarding unparseable requested_date %r", requested_date)
        else:
            if parsed_date != today:
                as_of = parsed_date
                as_of_is_requested = True
                logger.info("[ShiftQuery] query names %s (today is %s) - labelling the current "
                            "assignment with it; erp-api has no per-date shift data",
                            parsed_date, today)
    as_of_iso = as_of.isoformat()

    async def _call_erp(employee_id, employee_name):
        """(body, error_response). error_response is the already-finished
        _finish(...) return value on a transport failure — caller returns it
        immediately; otherwise it's None and body is the parsed response."""
        try:
            result = await erp_client.get_active_shift(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
                employee_id=employee_id, employee_name=employee_name,
            )
        except erp_client.ErpApiTimeout:
            return None, _finish("I couldn't reach the HR system in time — please try again in a moment.")
        except erp_client.ErpApiUnavailable:
            return None, _finish("I'm unable to reach the HR system right now — please try again shortly.")
        return result["body"], None

    async def _call_own_punch_details():
        """(shift, error_response) — the caller's OWN currently-applicable
        shift, read off /attendance/punch-details instead of /shift-details.

        Same transport-failure contract as _call_erp. No employee params are
        sent, so the caller's own token is the only thing selecting the
        record; this endpoint answers that for a manager, which is the whole
        reason it is here (see the select_employee branch below)."""
        try:
            result = await erp_client.get_attendance_punch_details(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
            )
        except erp_client.ErpApiTimeout:
            return None, _finish("I couldn't reach the HR system in time — please try again in a moment.")
        except erp_client.ErpApiUnavailable:
            return None, _finish("I'm unable to reach the HR system right now — please try again shortly.")
        punch_body = result["body"]
        if not punch_body.get("success", True):
            return None, _finish(punch_body.get("message")
                                 or "I couldn't fetch your shift assignment right now.")
        punch_data = punch_body.get("data") or {}
        return _shift_from_punch_details(punch_data.get("shift")), None

    writer({"type": "fetching_shift", "message": "Checking your shift assignment..."})
    body, error_response = await _call_erp(target_employee_id, target_employee_name)
    if error_response is not None:
        return error_response
    if not body.get("success", True):
        return _finish(body.get("message") or "I couldn't fetch your shift assignment right now.")

    data = body.get("data") or {}

    # A manager-role caller with no target named gets a completely different
    # shape back: no "shift"/"employee" at all, just a "pick one of your
    # team" prompt (live-verified — this endpoint has no concept of "my own
    # shift" for a caller with direct reports; even their own employee_id
    # comes back 403 "not found in your team"). Collapsing this into AC4's
    # "No Active Shift Assigned" on the strength of THIS response alone would
    # be actively wrong — it's not that no shift exists, it's that this
    # endpoint doesn't know whose shift to return. The else-branch below
    # answers the question from a source that does.
    if data.get("action_required") == "select_employee":
        employees = data.get("employees") or []

        # A single unambiguous match still comes back as this same "select
        # one" shape rather than the shift directly (live-verified — erp-api
        # never resolves straight to shift data, even on a single hit).
        # Silently re-fetch by that resolved employee_id instead of bouncing
        # a one-item menu back at the caller. This can only be reached by a
        # SELF query now (any named-target lookup is denied above, before
        # erp-api is ever called with a target), so the match, if any, can
        # only be resolving the caller's own record.
        resolved_employee = None
        if data.get("search_matched") and len(employees) == 1:
            resolved_employee = employees[0]

        if resolved_employee is not None:
            resolved_id = resolved_employee.get("employee_id")
            body, error_response = await _call_erp(resolved_id, None)
            if error_response is not None:
                return error_response
            if not body.get("success", True):
                return _finish(body.get("message") or "I couldn't fetch that employee's shift assignment right now.")
            data = body.get("data") or {}
            is_targeted_lookup = True
        elif wants_team_scope:
            # "what shift is assigned to my team", asked by someone allowed to
            # see that (an ordinary employee was refused before any call). The
            # menu erp-api returned IS the answer to this one: there is no
            # team-wide shift endpoint, so the honest reply is the team it
            # resolved plus "which of them?", and naming a member next turn
            # takes the targeted path above.
            names = [emp.get("employee_name") for emp in employees if emp.get("employee_name")]
            disambiguation_message = body.get("message") or "Please tell me which employee's shift you'd like to check."
            if names:
                disambiguation_message = f"{disambiguation_message} Your team: {', '.join(names)}."
            logger.info("[ShiftQuery] team-scope query answered with erp-api's roster (%d member(s))",
                        len(employees))
            writer({"type": "shift_summary", "data": {"has_active_shift": False, "action_required": "select_employee"}})
            return _finish(disambiguation_message,
                           extra_data={"has_active_shift": False, "action_required": "select_employee",
                                       "employees": employees})

        else:
            # The caller asked about THEMSELVES (no target reaches erp-api on
            # this route) and erp-api answered with a menu of their reports.
            # That menu used to be handed straight back — "Please select an
            # employee to view shift details. Your team: A, B, C." — which is
            # wrong twice over: a manager asking "what's my shift timing" was
            # never answered, and a self-only route listed other people's
            # names unprompted.
            #
            # /shift-details simply has no answer here (live-verified: for a
            # caller with direct reports it has no concept of "my own shift",
            # and even their own employee_id comes back 403 "not found in
            # your team"). /attendance/punch-details does — it serves the
            # caller's own record for a manager too, and its payload carries
            # the same shift object under different field names. So ask it
            # instead of bouncing the question back.
            #
            # This widens nothing: no employee param is sent, so the bearer
            # token alone selects the record, exactly as for an employee's
            # own "what shift am I assigned".
            logger.info(
                "[ShiftQuery] /shift-details returned a team menu for an own-shift query "
                "(%d report(s)) - resolving the caller's own shift from punch-details instead",
                len(employees),
            )
            own_shift, error_response = await _call_own_punch_details()
            if error_response is not None:
                return error_response
            # Falls through to the shared rendering below: a shift renders as
            # the ordinary own-shift card, and no shift takes AC4's "No Active
            # Shift Assigned" state — which is now the honest answer, because
            # the caller's own record really was consulted.
            data = {"shift": own_shift}

    # HH:MM - no seconds are sent or shown ("09:00", not "09:00:00").
    shift = shift_hhmm(data.get("shift") or {})
    # Only used to name the subject in the reply for a targeted lookup — the
    # caller's own case keeps the plain "You're currently assigned..." wording.
    subject_name = (data.get("employee") or {}).get("employee_name") if is_targeted_lookup else None

    # The caller named someone, but erp-api answered without saying WHOSE
    # shift this is. Live-observed for a caller with no direct reports: the
    # employee_name param is ignored outright and the caller's OWN shift
    # comes back with no "employee" block — which previously rendered as a
    # confident "You're currently assigned to X" in reply to "give me shift
    # details of <someone else>", with nothing in the payload signalling the
    # target had been dropped. An unattributed shift can't be shown as the
    # answer to a question about a named person, so refuse instead of
    # silently answering about the wrong employee.
    if is_targeted_lookup and not subject_name:
        logger.warning(
            "[ShiftQuery] targeted lookup (employee_id=%s employee_name=%s) came back with no "
            "employee attribution — refusing to answer with the caller's own shift (company_id=%s)",
            target_employee_id, target_employee_name, company_id,
        )
        writer({"type": "shift_summary", "data": {"has_active_shift": False, "target_unresolved": True}})
        return _finish(
            "I couldn't look up that employee's shift assignment — you may not have access to "
            "other employees' shift details.",
            extra_data={"has_active_shift": False, "target_unresolved": True},
        )

    # AC4 — no active shift assignment: explicit state, never blank fields
    # or a generic error.
    if not shift or not shift.get("shift_name"):
        logger.info("[ShiftQuery] no active shift assignment for company_id=%s", company_id)
        writer({"type": "shift_summary",
                "data": {"has_active_shift": False, "date": as_of_iso,
                         "date_from_query": as_of_is_requested}})
        # AC4's copy is a defined state string - the date rides the payload
        # rather than being appended to it, so the required wording is
        # untouched while a client still knows which day was checked.
        no_shift_message = (
            f"No Active Shift Assigned for {subject_name}." if subject_name else NO_ACTIVE_SHIFT_MESSAGE
        )
        return _finish(no_shift_message,
                       extra_data={"has_active_shift": False, "date": as_of_iso,
                                   "date_from_query": as_of_is_requested})

    if is_week_off_query(query):
        message = _render_week_off(shift, data.get("work_calendar"), subject_name=subject_name)
    else:
        message = _render_shift_card(shift, subject_name=subject_name, as_of=as_of,
                                     as_of_is_requested=as_of_is_requested)
    writer({"type": "shift_summary",
            "data": {"has_active_shift": True, "shift": shift, "date": as_of_iso,
                     "date_from_query": as_of_is_requested}})
    return _finish(message,
                   extra_data={"has_active_shift": True, "shift": shift, "date": as_of_iso,
                               "date_from_query": as_of_is_requested})
