"""Cortex Analyst semantic model agent.

Wraps Cortex Analyst tools (src/cortex_agent/analyst_tools.py) for
semantic model creation and natural-language querying.
"""

from __future__ import annotations

import logging
from typing import Any, Dict

from .base_agent import BaseDataBridgeAgent
from .state_schema import WorkflowState

logger = logging.getLogger(__name__)


class CortexAnalystAgent(BaseDataBridgeAgent):
    """Specialist agent for Cortex Analyst semantic model operations."""

    name = "cortex_analyst_agent"
    description = "Creates and queries Cortex Analyst semantic models"
    phase_name = "cortex_analyst"

    def __init__(self, **kwargs):
        super().__init__(
            tools=[],
            system_prompt=(
                "You are the Cortex Analyst agent for DataBridge AI. "
                "You create semantic models and answer natural-language "
                "questions about data using Snowflake Cortex Analyst."
            ),
            **kwargs,
        )

    async def run(self, state: WorkflowState) -> WorkflowState:
        """Execute Cortex Analyst operation."""
        config = state.get("config", {})
        action = config.get("analyst_action", "ask")

        if action == "ask":
            return await self._run_ask(state, config)
        elif action == "create_model":
            return await self._run_create_model(state, config)
        elif action == "bootstrap":
            return await self._run_bootstrap(state, config)

        return self._update_context(state, self.phase_name, {
            "error": f"Unknown analyst action: {action}"
        })

    async def _run_ask(self, state: WorkflowState, config: Dict) -> WorkflowState:
        """Ask a question via Cortex Analyst."""
        question = config.get("analyst_question", "")
        model_name = config.get("analyst_model", "")

        if not question or not model_name:
            return self._update_context(state, self.phase_name, {
                "error": "analyst_question and analyst_model are required"
            })

        try:
            from src.cortex_agent.analyst_tools import analyst_ask
            result = analyst_ask(question=question, semantic_model=model_name)
            return self._update_context(state, self.phase_name, {
                "action": "ask",
                "question": question,
                "result": result,
            })
        except Exception as e:
            return self._update_context(state, self.phase_name, {"error": str(e)})

    async def _run_create_model(self, state: WorkflowState, config: Dict) -> WorkflowState:
        """Create a semantic model."""
        try:
            return self._update_context(state, self.phase_name, {
                "action": "create_model",
                "status": "placeholder",
                "note": "Use create_semantic_model MCP tool directly",
            })
        except Exception as e:
            return self._update_context(state, self.phase_name, {"error": str(e)})

    async def _run_bootstrap(self, state: WorkflowState, config: Dict) -> WorkflowState:
        """Bootstrap a semantic model from discovered schema."""
        try:
            return self._update_context(state, self.phase_name, {
                "action": "bootstrap",
                "status": "placeholder",
                "note": "Use cortex_bootstrap_semantic_model MCP tool directly",
            })
        except Exception as e:
            return self._update_context(state, self.phase_name, {"error": str(e)})
