"""services/regularisation_display.py

The display fields the HA-697 chat cards need on a regularization row, derived
from what GET /api/v1/ai/regularizations returns:

    reference_id         "REG-22"            from regularization_id
    regularization_type  "Missed punch-out"  from reason (one of REGULARIZATION_TYPES;
                                             DEFAULT_REGULARIZATION_TYPE when the
                                             reason names none)
    regularization_type_source  "reason" | "default"
    applied_by           "Akash Jio (geo2)"  from employee_name + employee_number
    applied_on           "2026-08-31"        from created_at
    apply_date_display   "15-Aug-2026"       Figma's date format
    applied_on_display   "31-Aug-2026"
    status_label         "Pending"           table label; card_status_label "Pending approval"
    date_from / date_to  "2026-09-12"        the request's span (erp-api files one day,
                                             so both are apply_date)
    date_range_display   "12-Sep-2026 – 12-Sep-2026"
    in_time_display      "9:15 AM"           from from_time; out_time_display from to_time

Action flags (which buttons a table row shows) are added by the views, not
here, because they depend on WHO is looking - see employee_actions /
approver_actions.

Additive only: every key erp-api sent is kept as it was, so nothing that reads
the raw row (the approval flow's id matching, the frontend's existing fields)
changes. Pure functions, no imports from the rest of the app, so the history
view, the duplicate-date check and the manager queue can all use it.
"""
import os
import re
from datetime import datetime
from typing import Optional
from zoneinfo import ZoneInfo

REFERENCE_PREFIX = "REG-"

MISSED_PUNCH_OUT = "Missed punch-out"
MISSED_PUNCH_IN = "Missed punch-in"
LATE_ARRIVAL = "Late arrival"
ON_DUTY = "On-duty"

#: The four types the design offers, in the order its chips show them.
REGULARIZATION_TYPES = (MISSED_PUNCH_OUT, MISSED_PUNCH_IN, LATE_ARRIVAL, ON_DUTY)

#: Every row gets one of the four types (product decision, HA-697). A reason
#: that names none of them — "regularize", "test", a bare "missed punch" that
#: doesn't say in or out — is shown as this. Missed punch-out: the first chip
#: in the design and the most common reason a day needs regularizing.
#: regularization_type_source says "default" for these, so a UI or report can
#: tell a derived type from a defaulted one.
DEFAULT_REGULARIZATION_TYPE = MISSED_PUNCH_OUT

TYPE_SOURCE_REASON = "reason"
TYPE_SOURCE_DEFAULT = "default"

# erp-api has no type field: the type is read from the employee's reason.
# Checked in order, first match wins. Punch-out before late ("came late and
# forgot to punch out" is a missing out-punch), late before punch-in ("punched
# in late" is a late arrival), on-duty last so a reason that also names a
# missing punch is classed by the punch.
_TYPE_RULES = (
    (MISSED_PUNCH_OUT, re.compile(
        r"\b(?:punch|check|clock|log|sign|swipe)(?:ed|ing)?[\s-]*out\b"
        r"|\bout[\s-]*(?:punch|time|swipe)\b|\blogout\b|\bleft\s+early\b",
        re.IGNORECASE)),
    (LATE_ARRIVAL, re.compile(
        r"\blate\b|\blate[\s-]*(?:arrival|coming|login|punch)\b|\btraffic\b|\bdelay(?:ed)?\b",
        re.IGNORECASE)),
    (MISSED_PUNCH_IN, re.compile(
        r"\b(?:punch|check|clock|log|sign|swipe)(?:ed|ing)?[\s-]*in\b"
        r"|\bin[\s-]*(?:punch|time|swipe)\b|\blogin\b",
        re.IGNORECASE)),
    (ON_DUTY, re.compile(
        r"\bon[\s-]*duty\b|\bofficial\s+(?:work|duty|visit|travel|tour)\b|\bclient\b"
        r"|\bvisit\b|\bfield\s*work\b|\btravel\w*\b|\bmeeting\b|\btraining\b"
        r"|\boff[\s-]*site\b|\bout[\s-]*station\b|\bseminar\b|\bconference\b",
        re.IGNORECASE)),
)

_STATUS_LABELS = {
    "pending": "Pending", "approved": "Approved", "rejected": "Rejected",
    "cancelled": "Cancelled", "canceled": "Cancelled", "withdrawn": "Withdrawn",
}
_STATUS_CODES = {0: "pending", 1: "approved", 2: "rejected", 3: "cancelled"}


def reference_id(row: dict) -> Optional[str]:
    value = row.get("regularization_id")
    if value in (None, ""):
        return None
    return f"{REFERENCE_PREFIX}{value}"


def regularization_type_from_reason(reason) -> Optional[str]:
    """One of REGULARIZATION_TYPES, or None when the reason names none of
    them ("Testing", a bare "missed punch" that doesn't say in or out)."""
    text = str(reason or "").strip()
    if not text:
        return None
    for label, pattern in _TYPE_RULES:
        if pattern.search(text):
            return label
    return None


def regularization_type(reason) -> str:
    """Always one of REGULARIZATION_TYPES: the type the reason names, else
    DEFAULT_REGULARIZATION_TYPE."""
    return regularization_type_from_reason(reason) or DEFAULT_REGULARIZATION_TYPE


def applied_by(row: dict) -> Optional[str]:
    name = str(row.get("employee_name") or "").strip()
    number = str(row.get("employee_number") or "").strip()
    if name and number:
        return f"{name} ({number})"
    return name or number or None


def status_key(row: dict) -> Optional[str]:
    name = str(row.get("status_name") or "").strip().lower()
    if name:
        return "cancelled" if name == "canceled" else name
    try:
        return _STATUS_CODES.get(int(row.get("status")))
    except (TypeError, ValueError):
        return None


def status_label(row: dict) -> Optional[str]:
    key = status_key(row)
    if key is None:
        return None
    return _STATUS_LABELS.get(key, key.replace("_", " ").title())


def card_status_label(row: dict) -> Optional[str]:
    """The existing-request card's wording: "Pending approval" for a pending
    request, the plain label otherwise."""
    label = status_label(row)
    return "Pending approval" if label == "Pending" else label


def display_date(value) -> Optional[str]:
    """"2026-08-15" (or "2026-08-15 10:00:00") -> "15-Aug-2026". Anything
    unparseable comes back as given rather than dropped."""
    text = str(value or "").strip()
    if not text:
        return None
    try:
        return datetime.strptime(text[:10], "%Y-%m-%d").strftime("%d-%b-%Y")
    except ValueError:
        return text


#: Which requests use up the monthly limit (product decision, HA-697 AC-05).
#: Rejected, Cancelled and Withdrawn never do.
QUOTA_COUNTED_STATUSES = ("pending", "approved")


def count_quota_used(rows, cycle) -> int:
    """How many of `rows` count against the limit in `cycle` (a
    payroll_cycle.PayrollCycle): Pending/Approved, dated inside the cycle."""
    used = 0
    for row in rows or []:
        if not isinstance(row, dict) or status_key(row) not in QUOTA_COUNTED_STATUSES:
            continue
        try:
            day = datetime.strptime(str(row.get("apply_date") or "")[:10], "%Y-%m-%d").date()
        except ValueError:
            continue
        if cycle.contains(day):
            used += 1
    return used


def time_12h(value) -> Optional[str]:
    """"09:15:00" / "19:00" -> "9:15 AM" / "7:00 PM". Unparseable comes back
    as given; empty as None."""
    text = str(value or "").strip()
    if not text:
        return None
    for fmt in ("%H:%M:%S", "%H:%M"):
        try:
            return datetime.strptime(text, fmt).strftime("%I:%M %p").lstrip("0")
        except ValueError:
            continue
    return text


_TIME_RE = re.compile(
    r"^\s*(\d{1,2})(?:\s*[:.]\s*(\d{2}))?(?:\s*[:.]\s*\d{2})?\s*"
    r"(a\.?\s*m\.?|p\.?\s*m\.?)?\s*(?:hrs?|hours?)?\s*$", re.IGNORECASE)
_COMPACT_TIME_RE = re.compile(r"^\s*(\d{1,2})(\d{2})\s*(?:hrs?|hours?)?\s*$", re.IGNORECASE)


def time_24h(value) -> Optional[str]:
    """Any way a time is written -> "HH:MM", 24-hour, the shape erp-api
    compares against the shift: "10 am" / "10:00 AM" -> "10:00", "11 pm" /
    "11:00 PM" / "23" / "23:00:00" / "2300" -> "23:00", "12 am" -> "00:00",
    "noon" -> "12:00". Unparseable comes back as given; empty as None."""
    text = str(value or "").strip()
    if not text:
        return None
    low = text.lower()
    if low in ("noon", "12 noon", "midday"):
        return "12:00"
    if low in ("midnight", "12 midnight"):
        return "00:00"
    m = _TIME_RE.match(text)
    if m:
        hour, minute = int(m.group(1)), int(m.group(2) or 0)
        meridiem = (m.group(3) or "").replace(".", "").replace(" ", "").lower()
        if meridiem:
            if not 1 <= hour <= 12:
                return text
            hour = (0 if hour == 12 else hour) + (12 if meridiem == "pm" else 0)
        if hour > 23 or minute > 59:
            return text
        return f"{hour:02d}:{minute:02d}"
    m = _COMPACT_TIME_RE.match(text)
    if m and int(m.group(1)) <= 23 and int(m.group(2)) <= 59:
        return f"{int(m.group(1)):02d}:{m.group(2)}"
    return text


def shift_hhmm(shift):
    """A copy of a shift dict with its times - and its sessions' times - as
    "HH:MM" ("15:00"), never erp-api's "15:00:00": no seconds are sent or shown.
    Anything that isn't a dict comes back as given."""
    if not isinstance(shift, dict):
        return shift
    out = dict(shift)
    for key in ("start_time", "end_time"):
        if out.get(key):
            out[key] = time_24h(out[key])
    if isinstance(out.get("sessions"), list):
        out["sessions"] = [shift_hhmm(s) for s in out["sessions"]]
    return out


def future_date_message(dates: str, today: str, plural: bool = False) -> str:
    """The one refusal for a regularization date that hasn't happened yet,
    on every path (first message, date reply, form)."""
    when = f"{dates} haven't" if plural else f"{dates} hasn't"
    return (f"You can't regularize future dates — {when} happened yet. "
            f"Regularization is only for attendance that's already happened, so "
            f"please give me a date on or before today ({today}).")


def date_range_display(row: dict) -> Optional[str]:
    start = display_date(row.get("date_from") or row.get("apply_date"))
    end = display_date(row.get("date_to") or row.get("apply_date"))
    if not start:
        return None
    return f"{start} – {end or start}"


def action_time_display(now: Optional[datetime] = None) -> str:
    """"05-Oct-2026, 10:24 AM" in the app's timezone - the "Approved on" /
    "Rejected on" / "Cancelled on" of a success card. erp-api's responses
    carry no timestamp, so this is the moment it confirmed the action."""
    now = now or datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC")))
    return now.strftime("%d-%b-%Y, %I:%M %p").replace(", 0", ", ")


def employee_actions(row: dict) -> dict:
    """Buttons on the EMPLOYEE's own table: {"cancel": true} only while
    Pending. Only the key this table uses is sent, so the frontend never sees
    an approve/reject flag where those buttons don't exist."""
    return {"cancel": status_key(row) == "pending"}


def approver_actions(row: dict) -> dict:
    """Buttons on a Manager/HR/Admin's TEAM table: {"approve", "reject"} true
    only while Pending. Only these two keys - no cancel flag on this table."""
    pending = status_key(row) == "pending"
    return {"approve": pending, "reject": pending}


def enrich_row(row: dict) -> dict:
    """The row as erp-api sent it, plus the display fields above."""
    if not isinstance(row, dict):
        return row
    applied_on = str(row.get("created_at") or "").strip()[:10] or None
    derived_type = regularization_type_from_reason(row.get("reason"))
    day = str(row.get("apply_date") or "").strip()[:10] or None
    return {
        **row,
        "date_from": row.get("date_from") or day,
        "date_to": row.get("date_to") or day,
        "date_range_display": date_range_display(row),
        "in_time_display": time_12h(row.get("from_time")),
        "out_time_display": time_12h(row.get("to_time")),
        "reference_id": reference_id(row),
        "regularization_type": derived_type or DEFAULT_REGULARIZATION_TYPE,
        "regularization_type_source": TYPE_SOURCE_REASON if derived_type else TYPE_SOURCE_DEFAULT,
        "applied_by": applied_by(row),
        "applied_on": applied_on,
        "apply_date_display": display_date(row.get("apply_date")),
        "applied_on_display": display_date(applied_on),
        "status_label": status_label(row),
        "card_status_label": card_status_label(row),
    }


def enrich_rows(rows) -> list:
    return [enrich_row(r) for r in (rows or [])]
