"""services/punch_details.py

Punch Times & Work Hours (FR-03.2) — surfaces the employee's OWN recorded
check-in/check-out punch times, the shift timing applicable that day, and
the system-computed work hours, for a single specified day.

Strict scope: display only. Never explains classification/status reasoning
(a separate story) and never edits/corrects punch data. Work hours are
NEVER computed here — only ever the value erp-api itself returns.
"""
import os
import re
import difflib
import logging
from datetime import date, datetime, timedelta
from typing import Optional
from zoneinfo import ZoneInfo

from langgraph.types import StreamWriter

import services.erp_client as erp_client
from services.ai_service import _call_llm, _extract_text, _safe_json_parse, _normalize_usage, INTENT_MODEL
# Reused rather than reimplemented — same closed, unambiguous DD/MM(/YYYY) /
# day+named-month shape attendance.py's deterministic layer already
# resolves, so a year-less or slash/dash date here doesn't depend on the
# LLM following this file's own copy of the same rule correctly every time.
from services.attendance import _resolve_explicit_date_deterministic, _resolve_date_expression

logger = logging.getLogger(__name__)


def _today() -> date:
    """Company-local calendar date (QUOTA_TIMEZONE env var, same one
    quota_service.py already uses — default UTC) — NOT the server
    process's own system-clock date, which can differ by hours depending
    on where it happens to be hosted (confirmed live: server-local date
    lagged Asia/Kolkata by half a day, corrupting every "yesterday"/
    "tomorrow" resolution below). Re-reads the env var on every call, same
    as quota_service.py's _get_timezone(), so it stays test-friendly and
    reflects runtime env changes."""
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()


_WEEKDAY_NAMES = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
_WEEKDAYS = {name: idx for idx, name in enumerate(_WEEKDAY_NAMES)}

_EXPLICIT_ISO_DATE_PATTERN = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
_LAST_WEEKDAY_PATTERN = re.compile(
    r"\blast\s+(?:for\s+|on\s+)?(" + "|".join(_WEEKDAY_NAMES) + r")\b", re.IGNORECASE,
)
# Closed-vocabulary relative-day phrasing — resolved locally rather than
# trusted to the LLM, same reasoning as the weekday resolvers above.
# "day before "/"day after " each shift the named day by one more (so "day
# after tomorrow" = +2, "day before yesterday" = -2, "day after yesterday"
# = 0 — colloquial for today), which _resolve_relative_day_offset applies
# as a uniform +-1 delta on top of the bare word's own offset rather than
# needing every combination spelled out separately.
_RELATIVE_DAY_WORDS = ["yesterday", "tomorrow", "today"]
_RELATIVE_DAY_BASE_OFFSETS = {"yesterday": -1, "today": 0, "tomorrow": 1}
_RELATIVE_DAY_PREFIX_DELTAS = {"before": -1, "after": 1}
_RELATIVE_DAY_PATTERN = re.compile(
    r"\b(day\s+(?:before|after)\s+)?(yesterday|tomorrow|today)\b", re.IGNORECASE,
)
# Typo tolerance for a misspelled today/yesterday/tomorrow ("tomarrow",
# "yestarday") — same methodology (difflib ratio, empirically-swept cutoff)
# already validated for weekday-name typos in leave_action_service.py.
# 0.8 catches tomarrow/tommorow/tomorow/yestarday/yesteday (all >=0.875)
# with no false positives found against common query vocabulary
# (punch/details/status/attendance/etc.) or the weekday names themselves.
_RELATIVE_DAY_TYPO_CUTOFF = 0.8
_RELATIVE_DAY_TYPO_TOKEN_PATTERN = re.compile(
    r"\b(day\s+(?:before|after)\s+)?([a-z]{4,10})\b", re.IGNORECASE,
)


def _resolve_relative_day_offset(text: str) -> Optional[int]:
    """Resolves "yesterday"/"today"/"tomorrow", optionally "day before "/
    "day after " prefixed, tolerating a misspelling of the day-word. A
    bare, unprefixed "today" deliberately returns None — the caller
    already defaults to today.isoformat() on its own, so an explicit
    offset is only returned when it would change the answer."""
    m = _RELATIVE_DAY_PATTERN.search(text)
    if m:
        prefix, word = m.group(1), m.group(2).lower()
    else:
        prefix = word = None
        for tm in _RELATIVE_DAY_TYPO_TOKEN_PATTERN.finditer(text):
            token = tm.group(2).lower()
            close = difflib.get_close_matches(
                token, _RELATIVE_DAY_WORDS, n=1, cutoff=_RELATIVE_DAY_TYPO_CUTOFF,
            )
            if close:
                prefix, word = tm.group(1), close[0]
                break
        if word is None:
            return None

    offset = _RELATIVE_DAY_BASE_OFFSETS[word]
    if prefix:
        offset += _RELATIVE_DAY_PREFIX_DELTAS[prefix.strip().split()[1].lower()]
    elif word == "today":
        return None
    return offset
# Signals some OTHER date phrasing is present (month name, DD/MM(/YYYY), a
# bare year) that the deterministic rules below don't parse — e.g. "21 July
# 2026", "21/07/2026". Only these queries pay for an LLM extraction call.
_DATE_HINT_PATTERN = re.compile(
    r"\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\b|\d{1,2}[/-]\d{1,2}([/-]\d{2,4})?|\b(19|20)\d{2}\b",
    re.IGNORECASE,
)

# ── Compound "<year/month qualifier> + <ordinal weekday>" resolution ────────
# "last month's first Friday", "last year first month last Friday". All real
# date arithmetic — never handed to an LLM. This codebase already learned
# that lesson the hard way (see attendance_explain.py's own deterministic
# weekday resolver: "confirmed live: gpt-4o-mini resolved a bare 'Monday' to
# a Sunday").
_ORDINAL_WEEKDAY_WORDS = {
    "first": 1, "1st": 1, "second": 2, "2nd": 2, "third": 3, "3rd": 3, "fourth": 4, "4th": 4,
    "fifth": 5, "5th": 5,
}
_ORDINAL_WEEKDAY_PATTERN = re.compile(
    r"\b(first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|last)\s+(?:for\s+|on\s+|of\s+)?("
    + "|".join(_WEEKDAY_NAMES) + r")\b",
    re.IGNORECASE,
)

_LAST_YEAR_PATTERN = re.compile(r"\blast\s+year\b", re.IGNORECASE)
_THIS_YEAR_PATTERN = re.compile(r"\bthis\s+year\b", re.IGNORECASE)
_EXPLICIT_YEAR_PATTERN = re.compile(r"\b((?:19|20)\d{2})\b")

_MONTH_NAMES = {
    "january": 1, "jan": 1, "february": 2, "feb": 2, "march": 3, "mar": 3, "april": 4, "apr": 4,
    "may": 5, "june": 6, "jun": 6, "july": 7, "jul": 7, "august": 8, "aug": 8,
    "september": 9, "sep": 9, "sept": 9, "october": 10, "oct": 10, "november": 11, "nov": 11,
    "december": 12, "dec": 12,
}
_EXPLICIT_MONTH_NAME_PATTERN = re.compile(r"\b(" + "|".join(_MONTH_NAMES.keys()) + r")\b", re.IGNORECASE)
_ORDINAL_MONTH_WORDS = {
    "first": 1, "1st": 1, "second": 2, "2nd": 2, "third": 3, "3rd": 3, "fourth": 4, "4th": 4,
    "fifth": 5, "5th": 5, "sixth": 6, "6th": 6, "seventh": 7, "7th": 7, "eighth": 8, "8th": 8,
    "ninth": 9, "9th": 9, "tenth": 10, "10th": 10, "eleventh": 11, "11th": 11, "twelfth": 12, "12th": 12,
}
_ORDINAL_MONTH_PATTERN = re.compile(
    r"\b(first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|sixth|6th|seventh|7th|eighth|8th|"
    r"ninth|9th|tenth|10th|eleventh|11th|twelfth|12th)\s+month\b",
    re.IGNORECASE,
)
_LAST_MONTH_PATTERN = re.compile(r"\blast\s+month\b", re.IGNORECASE)
_THIS_MONTH_PATTERN = re.compile(r"\bthis\s+month\b", re.IGNORECASE)

# ── Compound "<last/this week> + <bare weekday>" resolution ─────────────────
# "last week Wednesday" / "Wednesday last week" / "this week Friday". NOT
# the same as the bare _LAST_WEEKDAY_PATTERN below ("last Wednesday" = most
# recent Wednesday before today) — the two can disagree by a full week
# depending on what day today is (e.g. said on a Thursday, "last Wednesday"
# is yesterday, but "last week Wednesday" is the Wednesday of the PRIOR
# calendar week, 7 days earlier). No ordinal word needed here since a week
# has only one of each weekday.
_LAST_WEEK_PATTERN = re.compile(r"\blast\s+week\b", re.IGNORECASE)
_THIS_WEEK_PATTERN = re.compile(r"\bthis\s+week\b", re.IGNORECASE)
_BARE_WEEKDAY_PATTERN = re.compile(r"\b(" + "|".join(_WEEKDAY_NAMES) + r")\b", re.IGNORECASE)


def _last_day_of_month(year: int, month: int) -> int:
    next_month_first = date(year + 1, 1, 1) if month == 12 else date(year, month + 1, 1)
    return (next_month_first - timedelta(days=1)).day


def _nth_weekday_of_month(year: int, month: int, weekday: int, n: int) -> Optional[date]:
    first = date(year, month, 1)
    day = 1 + ((weekday - first.weekday()) % 7) + (n - 1) * 7
    if day > _last_day_of_month(year, month):
        return None
    return date(year, month, day)


def _last_weekday_of_month(year: int, month: int, weekday: int) -> date:
    last = date(year, month, _last_day_of_month(year, month))
    return last - timedelta(days=(last.weekday() - weekday) % 7)


def _resolve_year_month_weekday(query: str, today: date) -> Optional[str]:
    """"last month's first Friday", "last year first month last Friday",
    "second Monday of this month". Requires an ORDINAL word directly before
    the weekday name ("first Friday", "last Friday" — not a bare "Friday")
    AND at least one year/month qualifier elsewhere in the query; a bare
    ordinal weekday with no scoping ("second Friday", no year/month named)
    returns None here and falls through to existing handling — too
    ambiguous to guess a month for.

    Checked BEFORE the plain _LAST_WEEKDAY_PATTERN in
    _resolve_date_deterministic: that pattern matches "last Friday" as a
    bare substring regardless of what precedes it, so without this running
    first, "last year first month last Friday" would match on just the
    trailing "last Friday" and silently ignore "last year first month" —
    confirmed live, resolved to this year's most recent Friday, over a year
    off from what was asked."""
    text = query.lower()

    ordinal_weekday_match = _ORDINAL_WEEKDAY_PATTERN.search(text)
    if not ordinal_weekday_match:
        return None
    ordinal_word = ordinal_weekday_match.group(1).lower()
    target_weekday = _WEEKDAYS[ordinal_weekday_match.group(2).lower()]

    explicit_year = _EXPLICIT_YEAR_PATTERN.search(text)
    has_last_year = bool(_LAST_YEAR_PATTERN.search(text))
    has_this_year = bool(_THIS_YEAR_PATTERN.search(text))
    has_year_qualifier = bool(explicit_year or has_last_year or has_this_year)

    explicit_month = _EXPLICIT_MONTH_NAME_PATTERN.search(text)
    ordinal_month = _ORDINAL_MONTH_PATTERN.search(text)
    has_last_month = bool(_LAST_MONTH_PATTERN.search(text))
    has_this_month = bool(_THIS_MONTH_PATTERN.search(text))
    has_month_qualifier = bool(explicit_month or ordinal_month or has_last_month or has_this_month)

    if not has_year_qualifier and not has_month_qualifier:
        return None

    # Month resolves first — "last month" rolls the year back too when
    # today is January AND no year was separately named (year resolution
    # below only applies that rollover in that specific default case).
    #
    # "last month" is genuinely ambiguous and reads differently depending on
    # whether a year was separately named:
    #   - alone ("last month's first Friday") -> relative to TODAY, one
    #     calendar month back.
    #   - alongside an explicit year ("last year LAST month last Friday")
    #     -> ordinal position WITHIN that year, i.e. December — the same
    #     reading "last year FIRST month" already gets (January), just the
    #     other end. Confirmed live: treating it as relative-to-today here
    #     gave "last year last month" = July of last year (today's month
    #     minus one, year minus one, two independent offsets) instead of
    #     December of last year — not what "last year's last month" means.
    month_year_delta = 0
    if explicit_month:
        month = _MONTH_NAMES[explicit_month.group(1).lower()]
    elif ordinal_month:
        month = _ORDINAL_MONTH_WORDS[ordinal_month.group(1).lower()]
    elif has_last_month:
        if has_year_qualifier:
            month = 12
        elif today.month == 1:
            month, month_year_delta = 12, -1
        else:
            month = today.month - 1
    else:  # has_this_month, or no month qualifier at all (year-only query)
        month = today.month

    if explicit_year:
        year = int(explicit_year.group(1))
    elif has_last_year:
        year = today.year - 1
    elif has_this_year:
        year = today.year
    else:
        year = today.year + month_year_delta

    if ordinal_word == "last":
        target = _last_weekday_of_month(year, month, target_weekday)
    else:
        target = _nth_weekday_of_month(year, month, target_weekday, _ORDINAL_WEEKDAY_WORDS[ordinal_word])

    return target.isoformat() if target else None


def _resolve_week_qualified_weekday(query: str, today: date) -> Optional[str]:
    """"last week Wednesday", "this week Friday" — resolves the target
    calendar week (Mon-Sun) first, then the named weekday within it. Returns
    None when there's no "last week"/"this week" qualifier, or no weekday
    named alongside it — a bare "last week" with no day is a range, out of
    scope here (falls through to existing handling, same as "this month"/
    bare-year with no day)."""
    text = query.lower()

    has_last_week = bool(_LAST_WEEK_PATTERN.search(text))
    has_this_week = bool(_THIS_WEEK_PATTERN.search(text))
    if not has_last_week and not has_this_week:
        return None

    weekday_match = _BARE_WEEKDAY_PATTERN.search(text)
    if not weekday_match:
        return None
    target_weekday = _WEEKDAYS[weekday_match.group(1).lower()]

    this_monday = today - timedelta(days=today.weekday())
    week_monday = this_monday - timedelta(days=7) if has_last_week else this_monday
    return (week_monday + timedelta(days=target_weekday)).isoformat()


def _resolve_date_deterministic(query: str, today: date) -> Optional[str]:
    """Covers AC5's own explicit examples ("yesterday", "last Friday") plus
    bare ISO dates without an LLM round-trip. Returns None when nothing here
    matches — caller decides whether that means "today" or "needs the LLM
    fallback"."""
    text = query.lower()

    explicit = _EXPLICIT_ISO_DATE_PATTERN.search(query)
    if explicit:
        return explicit.group(1)

    explicit_symbolic = _resolve_explicit_date_deterministic(query, today)
    if explicit_symbolic:
        resolved = _resolve_date_expression(explicit_symbolic, today)
        if resolved and resolved.get("type") == "single":
            return resolved["date"].isoformat()

    relative_day_offset = _resolve_relative_day_offset(text)
    if relative_day_offset is not None:
        return (today + timedelta(days=relative_day_offset)).isoformat()

    compound = _resolve_year_month_weekday(query, today)
    if compound:
        return compound

    week_compound = _resolve_week_qualified_weekday(query, today)
    if week_compound:
        return week_compound

    last_weekday = _LAST_WEEKDAY_PATTERN.search(text)
    if last_weekday:
        target = _WEEKDAYS[last_weekday.group(1).lower()]
        # "last Friday" said ON a Friday means the previous one, not today.
        delta = (today.weekday() - target) % 7 or 7
        return (today - timedelta(days=delta)).isoformat()

    return None


def _build_date_extraction_prompt(query: str, today: date) -> str:
    today_str = today.isoformat()
    return f"""You extract the SINGLE date being asked about in an employee's punch-times/attendance question.

Today's date is {today_str} ({today.strftime('%A')}).

Resolve explicit date phrasing to YYYY-MM-DD, e.g.:
- "21 July 2026" / "21 Jul 2026" / "July 21, 2026" / "21/07/2026" -> 2026-07-21

CRITICAL: any slash- or dash-separated numeric date (e.g. "10/08/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.
- "10/08/2026" -> 2026-08-10 (10th of August, NOT October 8th)
- "05-03-2026" -> 2026-03-05 (5th of March, NOT May 3rd)

CRITICAL: a date with NO year stated — either numeric ("12-08", "21/07") or
a named-month day ("23 aug", "12 August") — is still DD/MM (day first for
the numeric form) and uses {today_str}'s year ({today.year}). NEVER output
null and never silently fall back to today's date just because no year was
given.
- "12-08" -> {today.year}-08-12 (12th of August THIS year)
- "23 aug" -> {today.year}-08-23 (23rd of August THIS year)

OUTPUT ONLY JSON. No explanation, no markdown, no code fences.
{{"date": "YYYY-MM-DD"}}

Current User Query: {query}"""


async def _extract_date_via_llm(query: str, today: date, usage_events: list) -> Optional[str]:
    try:
        raw = await _call_llm(_build_date_extraction_prompt(query, today), max_tokens=40, model=INTENT_MODEL)
        parsed = _safe_json_parse(_extract_text(raw))
        usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
        if usage:
            usage_events.append({"source": "punch_date_extraction", "usage": usage})
        value = parsed.get("date") if isinstance(parsed, dict) else None
        if value and re.match(r"^\d{4}-\d{2}-\d{2}$", value):
            return value
    except Exception as e:
        logger.warning(f"[PunchDetails] date extraction failed: {e}")
    return None


def _format_sessions(sessions: list) -> str:
    parts = []
    for i, s in enumerate(sessions, start=1):
        check_in, check_out = s.get("check_in"), s.get("check_out")
        if s.get("complete") and check_in and check_out:
            parts.append(f"Session {i}: {check_in} to {check_out}")
        elif check_in and not check_out:
            parts.append(f"Session {i}: checked in at {check_in} — check-out not recorded")
        elif check_out and not check_in:
            parts.append(f"Session {i}: checked out at {check_out} — check-in not recorded")
    return "; ".join(parts)


async def punch_details_node(state: dict, writer: StreamWriter) -> dict:
    query = state["query"]
    bearer_token = state.get("bearer_token")
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id")
    usage_events = list(state.get("usage_events", []))

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

    today = _today()
    requested_date = _resolve_date_deterministic(query, today)
    if requested_date is None and _DATE_HINT_PATTERN.search(query):
        requested_date = await _extract_date_via_llm(query, today, usage_events)

    writer({"type": "fetching_punch_details", "message": "Checking your punch details..."})
    try:
        result = await erp_client.get_punch_details(
            bearer_token, date=requested_date, company_id=company_id, conversation_id=conversation_id,
        )
    except erp_client.ErpApiTimeout:
        return _finish("I couldn't reach the attendance system in time — please try again in a moment.")
    # ErpApiUnauthorized is a SUBCLASS of ErpApiUnavailable (see
    # erp_client.py) — must be caught first, or the general clause below
    # silently swallows every 401 into the wrong message.
    except erp_client.ErpApiUnauthorized:
        return _finish("Sorry, your session has expired — please log in again to continue.")
    except erp_client.ErpApiUnavailable:
        return _finish("I'm unable to reach the attendance system right now — please try again shortly.")

    body = result["body"]
    if not body.get("success", True):
        return _finish(body.get("message") or "I couldn't fetch your punch details right now.")

    data = body.get("data", {}) or {}
    display_date = data.get("requested_date") or requested_date or today.isoformat()
    shift = data.get("shift") or {}
    # erp-api's real /attendance/punch-details response returns this list
    # under "punches" (confirmed live) — "sessions" kept as a fallback in
    # case an older/other deployment still uses that name.
    sessions = data.get("punches") or data.get("sessions") or []
    work_hours = data.get("work_hours") or {}

    shift_desc = ""
    if shift.get("name"):
        shift_desc = f" Shift: {shift['name']} ({shift.get('start_time', '?')}–{shift.get('end_time', '?')})."

    # AC7 — non-working day / no punch records at all for the day. Only
    # "day_status" is used as the reason — confirmed live against a real
    # ordinary no-punch day (2026-08-18: day_status null, punch_status
    # "no_records") and a real regularized-but-punchless day (2026-08-14:
    # day_status still null, but attendance.attendance = "P", a raw
    # single-letter status code). Deliberately NOT falling back to
    # attendance.attendance — it's an internal code (P/A/WO/...), not a
    # human-readable day type, and would render as nonsense like "as it was
    # a P." work_hours.reason is also excluded — it duplicates the
    # top-level "no records" message rather than naming a day type.
    if not sessions:
        reason = data.get("day_status")
        reason_clause = f" as it was a {reason}" if reason else ""
        return _finish(
            f"No punch records found for {display_date}{reason_clause}.{shift_desc}",
            extra_data={"requested_date": display_date, "shift": shift},
        )

    sessions_desc = _format_sessions(sessions)

    # AC3 — hours shown ONLY when erp-api marks them available. Never
    # computed locally — this story's core trust boundary.
    if work_hours.get("available"):
        msg = (f"Punch details for {display_date} — {sessions_desc}.{shift_desc} "
               f"Total work hours: {work_hours.get('value')}.")
        return _finish(msg, extra_data={
            "requested_date": display_date, "shift": shift, "sessions": sessions, "work_hours": work_hours,
        })

    # AC4 — incomplete: show what exists, explicitly no hours value shown.
    msg = (f"Punch details for {display_date} — {sessions_desc}.{shift_desc} "
           f"Work hours aren't available since a punch is missing.")
    return _finish(msg, extra_data={"requested_date": display_date, "shift": shift, "sessions": sessions})
