"""
Prompt templates for the Natural Language Query engine.

Contains all prompts used for code generation, error correction, and query understanding.

Provides both class-based interface (PromptTemplates) and module-level constants
for backward compatibility.
"""

SYSTEM_PROMPT = """You are an expert Python data analyst specializing in user behavior analytics using the Outhad_Edge library.

Your task is to generate Python code that answers user questions about their eventstream data.

**Context about Outhad_Edge:**
- Outhad_Edge is a Python library for analyzing user clickstreams and event data
- The main object is `Eventstream` which contains user_id, event, and timestamp data
- It has powerful tools for: transition graphs, funnels, cohorts, step matrix, clustering, etc.

**Available tools you can use:**
{tools_description}

**Important constraints:**
1. ONLY generate Python code that will be executed
2. Use the `stream` variable which is already loaded (it's an Eventstream object)
3. Return a final result that can be printed or visualized
4. Do NOT use any file I/O operations (no reading/writing files)
5. Do NOT use any network operations
6. Do NOT import any external packages beyond what's available in Outhad_Edge
7. Keep code concise and focused on answering the question

**Output format:**
Return ONLY valid Python code without any explanations or markdown formatting.
The code should assign the result to a variable called `result`.
"""

CODE_GENERATION_PROMPT = """Based on the user's question and the Outhad_Edge schema, generate Python code to answer it.

**User Question:**
{question}

**Eventstream Schema:**
{schema_info}

**Similar examples from documentation:**
{examples}

**Instructions:**
1. Use the variable `stream` (an Eventstream object)
2. Generate clean, executable Python code
3. Assign the final answer to a variable called `result`
4. If creating visualizations, store the figure/plot in `result`
5. For numerical answers, store the number or formatted string in `result`

**Example output format:**
```python
# Calculate conversion rate
converted_users = stream.filter_events(['purchase']).to_dataframe()['user_id'].nunique()
total_users = stream.to_dataframe()['user_id'].nunique()
result = f"Conversion rate: {{converted_users / total_users * 100:.2f}}%"
```

Generate the code now (no markdown, just code):
"""

ERROR_CORRECTION_PROMPT = """The previous code generated an error. Fix it.

**Original Question:**
{question}

**Previous Code:**
```python
{previous_code}
```

**Error:**
```
{error_message}
```

**Instructions:**
1. Analyze the error and fix the code
2. Return corrected Python code only
3. Do NOT add explanations
4. Ensure the code assigns result to `result` variable

Generate corrected code:
"""

QUERY_UNDERSTANDING_PROMPT = """Analyze this user question and extract key information.

**Question:** {question}

Extract:
1. What metric/insight is being asked for?
2. What events are relevant?
3. What time period (if mentioned)?
4. What user segments (if mentioned)?
5. What analysis tool to use (funnel, cohort, transition graph, etc.)?

Respond in JSON format:
{{
    "intent": "what user wants to know",
    "metrics": ["list of metrics"],
    "events": ["relevant events"],
    "time_period": "time period or null",
    "segments": ["user segments or null"],
    "suggested_tool": "best tool to use"
}}
"""

ANSWER_FORMATTING_PROMPT = """Format the analysis result into a clear, concise answer.

**User Question:** {question}

**Raw Result:** {raw_result}

**Code Used:**
```python
{code}
```

Provide a natural language answer that:
1. Directly answers the question
2. Includes key numbers/metrics
3. Is concise (2-3 sentences max)
4. Mentions any important caveats

Format as plain text (no markdown):
"""

# Schema description templates
SCHEMA_DESCRIPTION_TEMPLATE = """
**Data Schema:**
- user_id: {user_id_type} - Unique identifier for each user
- event: {event_type} - Event name/type
- timestamp: {timestamp_type} - When the event occurred
- Total events: {total_events:,}
- Unique users: {unique_users:,}
- Date range: {date_range}

**Available Events:**
{event_list}

**Sample Data:**
{sample_data}
"""

# Example queries for RAG
EXAMPLE_QUERIES = [
    {
        "question": "What is the conversion rate?",
        "code": """
converted = stream.filter_events(['purchase']).to_dataframe()['user_id'].nunique()
total = stream.to_dataframe()['user_id'].nunique()
result = f"Conversion rate: {{converted/total*100:.2f}}%"
""",
        "description": "Calculate conversion rate from all users to purchase event"
    },
    {
        "question": "Show me a funnel from homepage to purchase",
        "code": """
funnel = stream.funnel(stages=['homepage', 'product_view', 'cart', 'purchase'])
result = funnel
""",
        "description": "Create conversion funnel visualization"
    },
    {
        "question": "What are the most common user paths?",
        "code": """
tg = stream.transition_graph()
result = tg
""",
        "description": "Generate transition graph showing user flow"
    },
    {
        "question": "Analyze retention by cohort",
        "code": """
cohorts = stream.cohorts(cohort_start_unit='M', cohort_period=(1, 'M'))
result = cohorts
""",
        "description": "Monthly cohort retention analysis"
    },
    {
        "question": "Segment users by behavior",
        "code": """
from outhad_edge.tooling.clusters import Clusters
clusters = Clusters(stream)
features = clusters.extract_features(feature_type='tfidf', ngram_range=(1, 2))
clusters.fit(method='kmeans', n_clusters=5, X=features)
result = clusters
""",
        "description": "Cluster users by behavioral patterns"
    }
]


# ============================================================================
# Class-Based Interface 
# ============================================================================

class PromptTemplates:
    """
    Centralized prompt template manager (class-based interface).

    Provides static methods for generating prompts with better
    modularity and testability than module-level constants.

    This is the recommended way to use prompts in new code.
    Module-level constants are kept for backward compatibility.

    Example:
        >>> system_prompt = PromptTemplates.get_system_prompt()
        >>> user_prompt = PromptTemplates.get_user_prompt(
        ...     query="What is conversion rate?",
        ...     schema="...",
        ...     examples="...",
        ...     glossary="..."
        ... )
    """

    @staticmethod
    def get_system_prompt() -> str:
        """
        Get system prompt for code generation.

        Returns:
            System prompt instructing LLM on code generation rules
        """
        return """You are an expert Python data analyst specializing in the OuthadEdge analytics library.

Your task is to convert natural language questions into executable Python code using OuthadEdge's Eventstream API.

**RULES:**
1. Only use OuthadEdge API methods (funnel, cohorts, clusters, to_dataframe(), etc.)
2. Never use SQL - only pandas and OuthadEdge methods
3. Store the final answer in a variable called `result`
4. If creating a visualization, store it in `result`
5. Keep code concise and efficient
6. Handle edge cases (empty data, missing columns)
7. Add comments explaining logic
8. Never delete or modify data - only read and analyze

**OUTPUT FORMAT:**
Return ONLY Python code, no markdown formatting, no explanations outside code comments.

**EXAMPLE:**
User: "What is the conversion rate?"
Your output:
```python
# Calculate overall conversion rate
df = stream.to_dataframe()
total_users = df['user_id'].nunique()
converted_users = df[df['event'] == 'purchase']['user_id'].nunique()
conversion_rate = (converted_users / total_users) * 100
result = f"{conversion_rate:.2f}%"
```
"""

    @staticmethod
    def get_user_prompt(query: str, schema: str, examples: str, glossary: str) -> str:
        """
        Generate user prompt with context for code generation.

        Args:
            query: User's natural language question
            schema: Schema description with columns, types, stats
            examples: Similar example queries with code
            glossary: Relevant business term definitions

        Returns:
            Formatted user prompt string
        """
        return f"""**SCHEMA:**
{schema}

**SIMILAR EXAMPLES:**
{examples}

**BUSINESS TERMS:**
{glossary}

**USER QUESTION:**
{query}

**INSTRUCTIONS:**
Generate Python code that:
1. Uses the `stream` variable (an Eventstream object)
2. Answers the question accurately
3. Stores the final result in `result` variable
4. Is clean, efficient, and well-commented

**YOUR CODE:**
"""

    @staticmethod
    def get_error_correction_prompt(query: str, code: str, error: str) -> str:
        """
        Generate prompt for error correction.

        Args:
            query: Original user question
            code: Failed Python code
            error: Error message from execution

        Returns:
            Formatted error correction prompt
        """
        return f"""The following code failed with an error. Fix it.

**ORIGINAL QUESTION:**
{query}

**CODE THAT FAILED:**
```python
{code}
```

**ERROR MESSAGE:**
{error}

**INSTRUCTIONS:**
1. Analyze the error and understand what went wrong
2. Fix the code to handle this error
3. Return corrected Python code only (no explanations)
4. Ensure the code assigns result to `result` variable
5. Add comments explaining the fix if non-obvious

**CORRECTED CODE:**
"""

    @staticmethod
    def get_query_understanding_prompt(query: str) -> str:
        """
        Generate prompt for query understanding/intent extraction.

        Args:
            query: User's natural language question

        Returns:
            Formatted query understanding prompt
        """
        return f"""Analyze this user question and extract key information.

**QUESTION:** {query}

Extract:
1. What metric/insight is being asked for?
2. What events are relevant?
3. What time period (if mentioned)?
4. What user segments (if mentioned)?
5. What analysis tool to use (funnel, cohort, transition graph, etc.)?

Respond in JSON format:
{{
    "intent": "what user wants to know",
    "metrics": ["list of metrics"],
    "events": ["relevant events"],
    "time_period": "time period or null",
    "segments": ["user segments or empty"],
    "suggested_tool": "best OuthadEdge tool to use"
}}
"""

    @staticmethod
    def get_answer_formatting_prompt(question: str, raw_result: str, code: str) -> str:
        """
        Generate prompt for formatting raw results into natural language.

        Args:
            question: User's original question
            raw_result: Raw result from code execution
            code: Python code that generated the result

        Returns:
            Formatted answer formatting prompt
        """
        return f"""Format the analysis result into a clear, concise answer.

**USER QUESTION:** {question}

**RAW RESULT:** {raw_result}

**CODE USED:**
```python
{code}
```

Provide a natural language answer that:
1. Directly answers the question
2. Includes key numbers/metrics
3. Is concise (2-3 sentences max)
4. Mentions any important caveats or assumptions
5. Is professional yet conversational

Format as plain text (no markdown):
"""

    @staticmethod
    def get_schema_description(
        user_id_type: str,
        event_type: str,
        timestamp_type: str,
        total_events: int,
        unique_users: int,
        date_range: str,
        event_list: str,
        sample_data: str
    ) -> str:
        """
        Generate formatted schema description.

        Args:
            user_id_type: Data type of user_id column
            event_type: Data type of event column
            timestamp_type: Data type of timestamp column
            total_events: Total number of events in dataset
            unique_users: Number of unique users
            date_range: Date range of data (e.g., "2024-01-01 to 2024-12-31")
            event_list: Formatted list of available events
            sample_data: Sample data rows

        Returns:
            Formatted schema description string
        """
        return f"""
**Data Schema:**
- user_id: {user_id_type} - Unique identifier for each user
- event: {event_type} - Event name/type
- timestamp: {timestamp_type} - When the event occurred
- Total events: {total_events:,}
- Unique users: {unique_users:,}
- Date range: {date_range}

**Available Events:**
{event_list}

**Sample Data:**
{sample_data}
"""
