"""
VSS VLM Agent
Handles VLM inference for Mode 1 visual queries.
"""

import logging
from typing import Optional

from orchestration.state import VSSState, add_trace
from inference.vlm_client import get_vlm
from config.settings import get_settings

logger = logging.getLogger(__name__)


MODE1_PROMPT = """Analyze the provided image and answer the user's question.

User Question: {question}

Provide a clear, detailed response based on what you observe in the image.
Be specific about counts, positions, and any notable details."""


class VLMAgent:
    """VLM Agent for Mode 1 visual queries."""
    
    def __init__(self):
        # Get client once during init (sync function)
        self.vlm = get_vlm()
    
    async def process(self, state: VSSState) -> VSSState:
        """Process VLM query."""
        if not get_settings().vlm_enabled:
            state["vlm_error"] = "VLM is disabled. Set VSS_VLM_ENABLED=true to enable."
            add_trace(state, "VLMAgent: Skipped — VLM disabled")
            return state

        add_trace(state, "VLMAgent: Starting inference")
        
        query = state.get("user_query", "Describe what you see.")
        media = state.get("uploaded_media")
        
        if not media:
            state["vlm_error"] = "No media provided for VLM analysis"
            add_trace(state, "VLMAgent: Error - no media")
            return state
        
        media_data = media.get("data")
        if not media_data:
            state["vlm_error"] = "Empty media data"
            add_trace(state, "VLMAgent: Error - empty media data")
            return state
        
        try:
            healthy = await self.vlm.health_check()
            if not healthy:
                state["vlm_error"] = "VLM server unavailable"
                add_trace(state, "VLMAgent: Error - VLM server down")
                return state
            
            add_trace(state, "VLMAgent: Processing image")
            
            prompt = MODE1_PROMPT.format(question=query)
            
            response = await self.vlm.generate(
                prompt=prompt,
                images=[media_data],
            )
            
            state["vlm_response"] = response
            add_trace(state, f"VLMAgent: Inference complete ({len(response)} chars)")
            
        except Exception as e:
            logger.error(f"VLM inference failed: {e}")
            state["vlm_error"] = str(e)
            add_trace(state, f"VLMAgent: Error - {e}")
        
        return state


_vlm_agent: Optional[VLMAgent] = None


def _get_vlm_agent() -> VLMAgent:
    """Return the module-level VLMAgent singleton (lazy init)."""
    global _vlm_agent
    if _vlm_agent is None:
        _vlm_agent = VLMAgent()
    return _vlm_agent


async def process_vlm(state: VSSState) -> VSSState:
    """LangGraph node function."""
    return await _get_vlm_agent().process(state)
