"""Natural assistant voice — identity, help, and LLM context without repetitive templates."""

from __future__ import annotations

import re

IDENTITY_PROMPT = """You are {agent_name}, an AI assistant that answers from the user's uploaded knowledge base.

The user asked about your identity — not about their files.
Write 2–4 natural sentences. Be warm and professional.
- Say you are an AI assistant (not a person) — neither a boy nor a girl; you don't have a gender.
- Your focus: answering questions using documents they upload to Knowledge, plus general questions.
- If they have documents loaded, mention that briefly in ONE short phrase — do not list every capability or filename.
- If the user's name is known, you may use it once naturally.
- Do NOT repeat a full onboarding script.
- Do NOT mention RAG, vectors, embeddings, or internal systems.
- No greeting if you already spoke this session; no goodbye.

{context_block}
User: {question}
Reply:"""

CAPABILITY_PROMPT = """You are {agent_name}, an AI assistant for uploaded knowledge-base documents.

The user asked how you can help — not for a specific document answer yet.
Write 2–4 natural sentences. Give 2–3 concrete examples as questions they could ask (e.g. summarize the file, find a name or date, explain a section).
If documents are loaded, reference that you can use their uploaded files — without repeating the same capability paragraph from earlier in the chat.
If the user's name is known, you may use it once.
Vary your wording from prior turns; do not copy-paste previous replies.
Do NOT list filenames unless they explicitly asked what files you have.
Do NOT mention RAG, vectors, or internal systems.
No greeting if you already spoke this session.

{context_block}
User: {question}
Reply:"""

CONCEPT_WITH_CONTEXT = """You are {agent_name}, a helpful AI assistant.

The user asked a general knowledge question — NOT about their uploaded documents unless they explicitly tied it to their files.
Answer accurately in 2–5 short sentences. Start with a brief natural lead-in when it fits ("Good question.", "Sure —", etc.) — not every time.
Do not invent document-specific numbers. Do not quote or summarize uploaded documents unless the question is about them.
If the user's name is known, you may use it once.
Never mention RAG, datasets, or internal systems.

{context_block}
User: {question}
Answer:"""


def is_identity_question(question: str) -> bool:
    q = (question or "").strip()
    return bool(
        re.search(
            r"(?i)\b("
            r"who\s+(?:are|r)\s+you|"
            r"tell\s+me\s+about\s+(?:yourself|you|the\s+bot|this\s+bot|the\s+assistant|alex)|"
            r"about\s+(?:yourself|you)\b|"
            r"what\s+are\s+you\b|"
            r"are\s+you\s+(?:a\s+)?(?:boy|girl|male|female|man|woman|guy|human|robot|ai|bot|person)|"
            r"are\s+you\s+(?:male\s+or\s+female|a\s+boy\s+or\s+(?:a\s+)?girl|real)|"
            r"your\s+gender|what\s+gender\s+are\s+you|"
            r"do\s+you\s+have\s+(?:a\s+)?gender"
            r")\b",
            q,
        )
    )


def is_capability_question(question: str) -> bool:
    q = (question or "").strip()
    if is_identity_question(q):
        return False
    return bool(
        re.search(
            r"(?i)\b("
            r"how\s+can\s+you\s+help|what\s+can\s+you\s+do|how\s+do\s+you\s+work|"
            r"what\s+do\s+you\s+do|help\s+me\s+(?:with|out)|what\s+are\s+you\s+(?:able|capable)|"
            r"what\s+(?:can|could)\s+i\s+ask"
            r")\b",
            q,
        )
    )


def build_context_block(
    *,
    user_name: str | None = None,
    has_knowledge: bool = False,
    has_statement: bool = False,
    history: str = "",
    already_spoke: bool = False,
) -> str:
    lines: list[str] = []
    if user_name:
        lines.append(f"The user's name is {user_name}.")
    if has_statement:
        lines.append("They have an uploaded statement ready to analyze.")
    elif has_knowledge:
        lines.append("They have documents in their knowledge base.")
    else:
        lines.append("No documents uploaded yet.")
    if already_spoke:
        lines.append("You have already chatted this session — do not re-introduce yourself.")
    if history.strip():
        lines.append("")
        lines.append(history.strip())
    return "\n".join(lines) if lines else "No extra context."


def build_meta_prompt(
    *,
    agent_name: str,
    question: str,
    user_name: str | None,
    has_knowledge: bool,
    has_statement: bool,
    history: str,
    already_spoke: bool,
) -> str:
    ctx = build_context_block(
        user_name=user_name,
        has_knowledge=has_knowledge,
        has_statement=has_statement,
        history=history,
        already_spoke=already_spoke,
    )
    template = IDENTITY_PROMPT if is_identity_question(question) else CAPABILITY_PROMPT
    return template.format(
        agent_name=agent_name,
        context_block=ctx,
        question=question.strip(),
    )


def build_concept_prompt(
    *,
    agent_name: str,
    question: str,
    user_name: str | None,
    history: str,
) -> str:
    ctx = build_context_block(user_name=user_name, history=history)
    base = CONCEPT_WITH_CONTEXT.format(
        agent_name=agent_name,
        context_block=ctx,
        question=question.strip(),
    )
    if history.strip():
        base = (
            f"{history.strip()}\n\n"
            "Answer the latest user question. Use conversation context when relevant.\n\n"
            f"{base}"
        )
    return base
