"""Thin Claude API wrapper — ONLY called through SecurityGateway.

This module exists solely to provide a clean interface for the orchestrator.
All actual API calls pass through security/gateway.py.
"""

from __future__ import annotations

from typing import Any

from security.gateway import SecurityGateway


class ClaudeClient:
    """High-level interface for Claude API interactions.

    IMPORTANT: Never import `anthropic` directly. Use SecurityGateway.
    """

    def __init__(self, gateway: SecurityGateway) -> None:
        self._gateway = gateway

    async def generate_sql(
        self,
        schema_context: str,
        user_question: str,
        conversation_history: list[dict[str, str]] | None = None,
        feedback: str | None = None,
    ) -> str:
        """Ask Claude to generate a SQL query from natural language.

        Args:
            schema_context: Metadata-only schema description (from ContextBuilder)
            user_question: The user's natural language question
            conversation_history: Previous messages in conversation
            feedback: Optional abstract error feedback for retry

        Returns:
            Claude's response containing SQL
        """
        messages = []

        # Add conversation history if available
        if conversation_history:
            messages.extend(conversation_history)

        # Build the user message
        user_content = f"Question: {user_question}"
        if feedback:
            user_content += f"\n\nPrevious attempt feedback: {feedback}"

        user_content += (
            "\n\nRespond ONLY with a valid PostgreSQL SELECT query. "
            "Do not include explanations, markdown formatting, or code blocks. "
            "Just the raw SQL query."
        )

        messages.append({"role": "user", "content": user_content})

        response = await self._gateway.send_to_claude(
            system_prompt=schema_context,
            messages=messages,
            metadata={"purpose": "sql_generation"},
        )

        # Clean up response — extract SQL from potential markdown
        sql = self._extract_sql(response)
        return sql

    # NOTE: Intent classification uses the LOCAL LLM (QueryRouter + Ollama),
    # NOT Claude API. This avoids an unconfirmed internet call.
    # See orchestrator/query_router.py for the implementation.

    @staticmethod
    def _extract_sql(response: str) -> str:
        """Extract SQL from Claude's response, handling markdown code blocks."""
        text = response.strip()

        # Remove markdown code blocks if present
        if text.startswith("```"):
            lines = text.split("\n")
            # Remove first line (```sql or ```)
            lines = lines[1:]
            # Remove last line (```)
            if lines and lines[-1].strip() == "```":
                lines = lines[:-1]
            text = "\n".join(lines).strip()

        return text
