import httpx
import re
from typing import Optional

PERPLEXITY_API_KEY = "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"
PERPLEXITY_URL = "https://api.perplexity.ai/chat/completions"


def _is_simple_greeting(message: str) -> bool:
    normalized = re.sub(r"[^a-z\s]", "", message.lower()).strip()
    return normalized in {
        "hi",
        "hello",
        "hey",
        "hii",
        "helo",
        "good morning",
        "good afternoon",
        "good evening",
    }


def _clean_response(text: str) -> str:
    """Strip markdown formatting from AI response."""
    text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)  # bold
    text = re.sub(r'\*(.+?)\*', r'\1', text)       # italic
    text = re.sub(r'#{1,3}\s+', '', text)           # headings
    text = re.sub(r'^\s*[-*]\s+', '', text, flags=re.MULTILINE)  # bullets
    text = re.sub(r'\[(\d+)\]', '', text)           # citation refs like [1]
    text = re.sub(r'\n{3,}', '\n\n', text)          # excess newlines
    return text.strip()


async def ask_ai(message: str, context: Optional[str] = None) -> str:
    if _is_simple_greeting(message):
        return "Hi, I am here to help with financial reports, KPIs, forecasts, and insights. What would you like to analyze?"

    if context:
        user_content = (
            f"Use the following application report context as the source of truth. "
            f"Do not use web/search snippets when the answer is present here.\n\n"
            f"APPLICATION REPORT CONTEXT:\n{context}\n\n"
            f"Question: {message}\n\n"
            f"If the question is just a greeting or small talk, answer conversationally and do not analyze the report context. "
            f"Otherwise answer in max 3 short sentences. Focus on what happened, why, and one insight."
        )
    else:
        user_content = (
            f"{message}\n\n"
            f"Answer in max 3 short sentences. Focus on what happened, why, and one insight."
        )

    async with httpx.AsyncClient(timeout=30.0) as client:
        resp = await client.post(
            PERPLEXITY_URL,
            headers={
                "Authorization": f"Bearer {PERPLEXITY_API_KEY}",
                "Content-Type": "application/json",
            },
            json={
                "model": "sonar",
                "messages": [
                    {
                        "role": "system",
                        "content": (
                            "You are an expert FP&A analyst embedded in a reporting dashboard. "
                            "If the user only greets you or uses small talk, reply briefly and ask what they want to analyze. "
                            "When application report context is provided, use it as the source of truth. "
                            "Do not mention search results, snippets, or external sources. "
                            "Respond in max 3 short sentences, plain text only. "
                            "Do NOT list all months or dump raw data unless explicitly asked. "
                            "Focus on: what happened, why, and one actionable insight."
                        ),
                    },
                    {"role": "user", "content": user_content},
                ],
                "max_tokens": 200,
                "temperature": 0.3,
            },
        )
        resp.raise_for_status()

    raw = resp.json()["choices"][0]["message"]["content"]
    return _clean_response(raw)
