"""services/policy_draft.py — writing a policy, as opposed to looking one up.

Two requests share the word "policy" and mean opposite things:

    "what is our maternity leave policy"  -> READ. policy_rag_node searches the
                                             uploaded documents and, when they
                                             do not cover it, says so. It never
                                             invents the company's rules.
    "make me a leave policy"              -> WRITE. Nothing here is a claim
                                             about this company. The documents
                                             are irrelevant, and consulting
                                             them only produced the reported
                                             bug: the request was routed to
                                             RAG, matched nothing (of course —
                                             the user was not asking what any
                                             document said), and came back
                                             "Based on the information
                                             available in your company
                                             policy/playbook, I do not have
                                             this information." A refusal, to a
                                             request to write something.

A JD has always worked, because job_description was never wired to the
documents. This node gives policy authoring the same freedom, with one
difference that matters: the output is a DRAFT the user asked for, never a
description of what this company's policy is. The prompt below says so, and
the reply is framed that way, because the same conversation also answers
"what is our policy" from real documents — the two must not blur.

The clarifying turn is the point, not a formality. "Make me a policy" names
a document and nothing else: no subject, no scope, no audience. Drafting
immediately produces a generic template nobody asked for, so the node asks
what the policy is about and what it should cover, remembers the question
(policy_draft_state), and writes on the next turn. When the opening message
already carries a subject, only what is missing is asked for.
"""
import logging
import re
from typing import Optional

from langgraph.types import StreamWriter

from services.ai_service import (
    LLM_MAX_TOKENS,
    INTENT_MODEL,
    _call_llm,
    _extract_text,
    _normalize_usage,
)
import services.policy_draft_state as policy_draft_state

logger = logging.getLogger(__name__)


#: The document words this flow writes. Kept with the node rather than in the
#: classifier because the node uses them to NAME the subject back to the user
#: ("a remote work policy"), not only to recognise the request.
_POLICY_NOUN = r"(?:policy|policies|sop|s\.o\.p\.|code\s+of\s+conduct|" \
               r"guidelines?|handbook|charter|procedures?)"

#: "a WFH policy", "policy on remote work", "policy for interns", "leave
#: policy". Three shapes because English puts the subject on either side of
#: the noun, and a bare "make me a policy" has no subject at all.
_SUBJECT_BEFORE_RE = re.compile(
    r"\b(?:a|an|the|our|new|draft)?\s*([\w][\w\s/&+-]{2,40}?)\s+" + _POLICY_NOUN + r"\b",
    re.IGNORECASE,
)
_SUBJECT_AFTER_RE = re.compile(
    _POLICY_NOUN + r"\s+(?:on|for|about|regarding|covering|related\s+to)\s+([\w][\w\s/&+-]{2,60})",
    re.IGNORECASE,
)

#: Words that are part of the REQUEST, not of the subject — "create a policy"
#: must not yield a policy about "create". Stripped from a candidate subject
#: before it is used, and a candidate made only of these is discarded.
_REQUEST_WORDS = {
    "create", "draft", "write", "make", "generate", "prepare", "build",
    "produce", "frame", "formulate", "design", "compose", "give", "get",
    "need", "want", "please", "help", "me", "us", "my", "our", "a", "an",
    "the", "new", "some", "kindly", "can", "you", "could", "would", "will",
    "i", "we", "up", "out", "together", "put", "come", "with", "for", "of",
    "another", "good", "proper", "standard", "sample", "basic",
}

#: "you decide", "anything", "whatever you think" — the user handing the
#: brief back. A drafting flow that insists on details after this is just
#: refusing to do the thing it offered.
_DEFER_TO_ASSISTANT_RE = re.compile(
    r"\b(?:you\s+(?:decide|choose|pick)|whatever\s+you\s+(?:think|want|like)|"
    r"as\s+you\s+(?:like|wish|see\s+fit)|your\s+(?:call|choice)|"
    r"up\s+to\s+you|anything(?:\s+is\s+fine)?|doesn'?t\s+matter|"
    r"standard\s+one|usual\s+one|general\s+one|just\s+(?:make|write|draft|give)\s+it|"
    r"go\s+ahead|surprise\s+me)\b",
    re.IGNORECASE,
)

#: Enough of a brief that asking "what should it cover?" would be pedantic —
#: the user already said. Any of: a "covering/including/with" clause, a list,
#: or simply a message long enough to be a brief rather than a request.
_BRIEF_MARKER_RE = re.compile(
    r"\b(?:cover(?:ing|s)?|includ(?:e|ing|es)|with\s+sections?|should\s+(?:have|state|say|mention)|"
    r"must\s+(?:have|state|include)|containing|detailing|mention(?:ing)?)\b",
    re.IGNORECASE,
)

_NO_SUBJECT_QUESTION = (
    "Happy to draft one. What kind of policy would you like — and what should it cover?\n\n"
    "For example: the topic (leave, remote work, code of conduct, expenses…), "
    "who it applies to, and any rules you want stated.\n\n"
    "If you'd rather I choose the structure, just say **you decide**."
)


def _clean_subject(raw: Optional[str]) -> Optional[str]:
    """A usable policy subject from a regex capture, or None.

    The capture groups are deliberately greedy about surrounding words, so
    this is where "create a remote work" becomes "remote work" and where a
    capture that is nothing but request vocabulary is thrown away.
    """
    if not raw:
        return None
    words = [w for w in re.split(r"\s+", raw.strip()) if w]
    while words and words[0].lower().strip(",.") in _REQUEST_WORDS:
        words.pop(0)
    while words and words[-1].lower().strip(",.") in _REQUEST_WORDS:
        words.pop()
    if not words:
        return None
    subject = " ".join(words).strip(" ,.-")
    return subject or None


#: Document names that ARE their own subject — "prepare a code of conduct"
#: needs no topic asked back, unlike a bare "prepare a policy". Matched only
#: after the two subject patterns decline, so "code of conduct policy for
#: contractors" still yields the more specific subject.
_SELF_NAMING_DOCUMENT_RE = re.compile(
    r"\b(code\s+of\s+conduct|employee\s+handbook|handbook)\b", re.IGNORECASE)


def extract_policy_subject(query: str) -> Optional[str]:
    """What the policy is ABOUT, when the message says — "a WFH policy",
    "policy on remote work", "leave policy". None for a bare "make me a
    policy", which is exactly the case the clarifying question exists for."""
    q = query or ""
    after = _SUBJECT_AFTER_RE.search(q)
    if after:
        subject = _clean_subject(after.group(1))
        if subject:
            return subject
    before = _SUBJECT_BEFORE_RE.search(q)
    if before:
        subject = _clean_subject(before.group(1))
        if subject:
            return subject
    self_naming = _SELF_NAMING_DOCUMENT_RE.search(q)
    if self_naming:
        return self_naming.group(1).lower()
    return None


def _carries_a_brief(query: str) -> bool:
    """True when the message already says what the policy should contain, so
    the flow can draft without asking. Length alone counts: someone who types
    a paragraph has given a brief, whatever words they used."""
    q = (query or "").strip()
    if _BRIEF_MARKER_RE.search(q):
        return True
    return len(q.split()) >= 18


def _scope_question(subject: str) -> str:
    return (
        f"Sure — a **{subject}** policy. What should it cover?\n\n"
        "For example: who it applies to, the rules themselves, approvals, "
        "exceptions, and anything specific to how you work.\n\n"
        "If you'd rather I choose, just say **you decide** and I'll draft a standard one."
    )


def _draft_prompt(subject: Optional[str], brief: str) -> str:
    """The authoring prompt.

    Written to stand apart from HR_SYSTEM_PROMPT, which is a prompt for
    ANSWERING and carries "Never invent company-specific policies. You do not
    know the user's company policy." That rule is right for a question about
    this company's rules and wrong for a document the user asked to be
    written — left in force here it produces a hedged half-policy full of
    "typically" and "verify with HR", which is not a policy at all.

    The two rules that stay: the draft must never claim to BE this company's
    policy, and it must not invent facts about this company (a real head-count,
    a real leave balance, a real office address). Placeholders instead, which
    is also what makes the output usable as a template.
    """
    topic = f'The policy is about: {subject}.' if subject else "The user has not named a topic."
    return (
        "You are drafting a workplace policy document that the user has asked you to write.\n\n"
        f"{topic}\n"
        f"What the user asked for, in their words: \"{brief}\"\n\n"
        "Write the policy itself — a complete, usable draft the user can take away and adapt.\n\n"
        "Structure it as a real policy document:\n"
        "- a title\n"
        "- purpose / objective\n"
        "- scope (who it applies to)\n"
        "- the policy statement and its specific rules\n"
        "- responsibilities, approvals or escalation where they apply\n"
        "- exceptions and non-compliance, where they apply\n"
        "- effective date and review cycle as placeholders\n\n"
        "Rules:\n"
        "- This is a DRAFT for the user to review and adapt. It is NOT a statement of any "
        "existing company policy, and must never be written as though it already applies here.\n"
        "- Do not invent facts about the user's company — no real head-counts, office locations, "
        "salary figures or entitlements presented as theirs. Use clear placeholders such as "
        "[Company Name], [X days], [Manager/HR] where a company-specific value belongs.\n"
        "- Write in the direct, plain register a policy uses. Do not hedge with \"typically\" or "
        "\"in most organizations\" — it is a document, not advice.\n"
        "- Where the user gave a specific rule, use it exactly as given.\n"
        "- Markdown, with headings. No preamble before the title and no commentary after the end "
        "of the document.\n"
    )


async def policy_draft_node(state: dict, writer: StreamWriter) -> dict:
    """Ask what the policy should be, then write it.

    Two turns by design, and the second one is reached through
    classify_node's pending-state check rather than by re-classifying the
    reply — a bare "remote work, applies to everyone" is not a question, and
    left to the classifier it reads as a policy LOOKUP and gets answered from
    the documents (the same shape of bug as a bare date landing on a shift
    card mid-regularisation).
    """
    query = state.get("query", "") or ""
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    usage_events = list(state.get("usage_events", []))

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

    pending = policy_draft_state.get_state(company_id, conversation_id) or {}

    if not pending:
        subject = extract_policy_subject(query)

        # Enough to write from already — a named topic plus a brief, or a
        # topic plus an explicit "you decide". Asking anyway would be the
        # flow refusing to do the thing it just offered.
        if subject and (_carries_a_brief(query) or _DEFER_TO_ASSISTANT_RE.search(query)):
            logger.info("[PolicyDraft] brief supplied up front for %r - drafting now", subject)
            return await _draft(subject, query, state, writer, usage_events)

        question = _scope_question(subject) if subject else _NO_SUBJECT_QUESTION
        policy_draft_state.set_state(company_id, conversation_id, {
            "step": "awaiting_brief", "subject": subject, "asked": question,
        })
        logger.info("[PolicyDraft] asking for the brief (subject=%r)", subject)
        return _finish(question, "policy_draft_clarify",
                       extra_data={"policy_draft": {"step": "awaiting_brief",
                                                    "subject": subject}})

    # ── The reply to our own question ──────────────────────────────────────
    subject = pending.get("subject") or extract_policy_subject(query)
    policy_draft_state.clear_state(company_id, conversation_id)

    if _DEFER_TO_ASSISTANT_RE.search(query) and not subject:
        # "you decide" with no topic anywhere: there is still nothing to write
        # ABOUT. Ask once more rather than inventing a subject, and keep the
        # flow open so the next message is still read as the answer.
        policy_draft_state.set_state(company_id, conversation_id, {
            "step": "awaiting_brief", "subject": None, "asked": _NO_SUBJECT_QUESTION,
        })
        message = ("I can choose the structure, but I still need the topic — "
                   "what should the policy be about?")
        return _finish(message, "policy_draft_clarify",
                       extra_data={"policy_draft": {"step": "awaiting_brief", "subject": None}})

    return await _draft(subject, query, state, writer, usage_events)


async def _draft(subject: Optional[str], brief: str, state: dict,
                 writer: StreamWriter, usage_events: list) -> dict:
    writer({"type": "searching", "message": "Drafting the policy..."})

    prompt = _draft_prompt(subject, brief)
    try:
        raw = await _call_llm(prompt, max_tokens=LLM_MAX_TOKENS, model=INTENT_MODEL,
                              temperature=0.3)
        body = _extract_text(raw).strip()
        usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
        if usage:
            usage_events.append({"source": "policy_draft", "usage": usage})
    except Exception as e:
        logger.exception("[PolicyDraft] drafting call failed: %s", e)
        body = ""

    if not body:
        message = ("I couldn't draft that just now — please try again in a moment.")
        writer({"type": "chunk", "content": message})
        writer({"type": "done", "intent": "policy_draft_failed", "is_hr": True,
                "data": {"answer": message}, "message": message,
                "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    # Said once, above the document, and never inside it: this is a draft the
    # user asked for, not a description of what this company already does.
    # The same conversation answers "what is our policy" from real uploaded
    # documents, so the two kinds of answer must not read alike.
    preamble = ("Here's a draft you can adapt — it's a starting point, not your "
                "company's current policy.\n\n")
    message = preamble + body

    writer({"type": "chunk", "content": message})
    writer({"type": "done", "intent": "policy_draft", "is_hr": True,
            "data": {"answer": message, "policy_draft": {"subject": subject, "is_draft": True}},
            "message": message, "usage_events": usage_events})
    return {"response_text": message, "usage_events": usage_events}
