"""Two questions in one message: "what's my leave balance and who invented
radio?", "when is the next holiday? also what is the capital of japan".

The graph answers one intent per turn, so the second question was dropped
(pilot run, 28 Oct: 26 of 35 such messages answered only the first part).
split() finds a clear seam between two complete asks; hr_graph runs the
graph once per part and merges the replies.

Deliberately narrow: a seam must be an explicit joiner ("and also", "and
then", "? also", "? <next question>", "and who/what/how ..."), each part must
be a real ask, and nothing that starts or changes a flow (apply, cancel,
approve, regularize, ...) is ever split - an action needs its own turn and
its own confirmation.
"""
import re
from typing import Optional

_SEAM_RE = re.compile(
    r"(?:[?.!,;]\s*|\s+)and\s+(?:also|then)\s+"
    r"|[?.!,;]\s*(?:also|plus|and|aur)\s+"
    r"|\?\s+(?=[A-Za-z])"
    r"|\s+and\s+(?=(?:who|what|when|where|how|why|which|whose|tell\s+me|show\s+me|give\s+me|explain)\b)",
    re.IGNORECASE)

# Anything that starts, answers or changes a flow stays one turn.
_ACTION_RE = re.compile(
    r"\b(?:apply|applying|cancel|cancell?ing|approve|approving|reject|rejecting|regulari[sz]\w*|"
    r"submit|withdraw|discard|confirm|yes|no|book|raise)\b",
    re.IGNORECASE)
_SUMMARY_RE = re.compile(r"\b(?:summar\w*|recap|what\s+did\s+we\s+(?:discuss|talk))\b", re.IGNORECASE)
_MIN_WORDS = 2


# ── Two ACTIONS in one message ──────────────────────────────────────────────
# "apply sick leave tomorrow and cancel my 2 nov leave". split() never splits
# an action (above), so one half reached its flow and the other was dropped -
# which half varied run to run (negative run, 28 Oct, #42). Running both is
# not the answer either: each needs its own turn and its own confirmation.
# So the turn asks which to do first, offering each half as a reply.
_ACTION_KINDS = (
    ("apply", r"apply|applying|book|raise"),
    ("cancel", r"cancel|cancell?ing|withdraw"),
    ("approve", r"approve|approving|accept"),
    ("reject", r"reject|rejecting|decline"),
    ("regularize", r"regulari[sz]e|regulari[sz]ing"),
)
_ACTION_SEAM_RE = re.compile(r"\s*(?:,\s*|\s+)(?:and|then|also|plus)\s+(?:then\s+|also\s+)?|\s*[,;]\s+",
                             re.IGNORECASE)
_LEADING_POLITE_RE = re.compile(r"^(?:please|pls|kindly|can\s+you|could\s+you|i\s+(?:want|need|would\s+like)\s+to)\s+",
                                re.IGNORECASE)


def _action_of(part: str) -> Optional[str]:
    """The action a part STARTS with, else None - "cancel my 2 nov leave" is
    a cancel, "3 nov" and "because I need to cancel my trip" are not."""
    text = _LEADING_POLITE_RE.sub("", part.strip())
    for kind, rx in _ACTION_KINDS:
        if re.match(rf"(?:{rx})\b", text, re.IGNORECASE):
            return kind
    return None


def two_actions(query: str) -> Optional[tuple]:
    """(first, second) - the two parts, as typed - when `query` asks for two
    DIFFERENT actions, each its own clause; else None."""
    parts = [p.strip(" .!?") for p in _ACTION_SEAM_RE.split((query or "").strip())
             if p and p.strip(" .!?")]
    actions = [(p, _action_of(p)) for p in parts]
    asked = [(p, a) for p, a in actions if a and len(p.split()) >= _MIN_WORDS]
    if len(asked) < 2 or actions[0][1] is None:
        return None
    (first, kind1), (second, kind2) = asked[0], asked[1]
    if kind1 == kind2:
        return None
    return first, second


def split(query: str) -> Optional[tuple]:
    """(first, second) when `query` holds two separate asks, else None."""
    text = (query or "").strip()
    if len(text.split()) < 5 or _ACTION_RE.search(text) or _SUMMARY_RE.search(text):
        return None
    m = _SEAM_RE.search(text)
    if not m:
        return None
    first = text[:m.start()].strip(" ,;")
    second = text[m.end():].strip(" ,;")
    if m.group(0).strip().startswith("?"):
        first += "?"
    if len(first.split()) < _MIN_WORDS or len(second.split()) < _MIN_WORDS:
        return None
    return first, second
