"""
{{ agent_name }} Agent
Generated by ABI-Core scaffolding
"""

import logging
from typing import Dict, Any, AsyncIterable

from abi_core.common import prompts
from abi_core.common.utils import abi_logging
from abi_core.agent.agent import AbiAgent
from models import {{ agent_name.title().replace('_', '') }}Response

from langchain_ollama import ChatOllama
from langchain.agents import create_agent

# Import configuration
from config import config

logger = logging.getLogger(__name__)


class {{ agent_class_name }}(AbiAgent):
    """{{ agent_description | default('ABI Agent for specialized tasks') }}"""
    
    def __init__(self):
        super().__init__(
            agent_name=config.AGENT_NAME,
            description=config.AGENT_DESCRIPTION,
            content_types=['text', 'text/plain', 'application/json']
        )
        
        # Initialize LLM
        self.llm = ChatOllama(
            model=config.MODEL_NAME,
            base_url=config.OLLAMA_HOST,
            temperature={{ temperature | default('0.1') }}
        )
        
        abi_logging(f'[✅] LLM initialized: {config.MODEL_NAME} at {config.OLLAMA_HOST}')
        
        # Create agent with tools
        self.agent = create_agent(
            model=self.llm,
            tools=[],  # Add tools as needed
            system_prompt=prompts.WORKER_PROMPT
        )
        
        abi_logging(f'[🚀] {config.AGENT_DISPLAY_NAME} agent ready')
    
    async def stream(
        self, 
        query: str, 
        context_id: str, 
        task_id: str
    ) -> AsyncIterable[Dict[str, Any]]:
        """
        Process query and stream responses
        
        Args:
            query: User query to process
            context_id: Context identifier
            task_id: Task identifier
            
        Yields:
            Dict containing response data
        """
        abi_logging(f'[📝] {{ agent_name }} processing: {query[:100]}...')
        
        try:
            # Input for the agent
            inputs = {"messages": [{"role": "user", "content": query}]}
            
            # Stream agent execution
            final_response = None
            
            async for chunk in self.agent.astream(inputs, stream_mode="updates"):
                abi_logging(f'[🔄] Chunk: {chunk}')
                
                # Extract response from chunk
                for node_name, node_data in chunk.items():
                    if "messages" in node_data:
                        for msg in node_data["messages"]:
                            if hasattr(msg, 'content') and msg.content:
                                final_response = msg.content
                                abi_logging(f'[💬] Response: {str(msg.content)[:100]}...')
            
            # Yield final result
            if final_response:
                yield {
                    'content': final_response,
                    'response_type': 'text',
                    'is_task_completed': True,
                    'require_user_input': False,
                    'metadata': {
                        'agent': '{{ agent_name }}',
                        'model': MODEL_NAME,
                        'context_id': context_id,
                        'task_id': task_id
                    }
                }
            else:
                yield {
                    'content': 'No response generated from agent',
                    'response_type': 'text',
                    'is_task_completed': True,
                    'require_user_input': False
                }
                
        except Exception as e:
            logger.error(f'[❌] Error in {{ agent_name }} agent: {e}', exc_info=True)
            yield {
                'content': f'Error processing request: {str(e)}',
                'response_type': 'text',
                'is_task_completed': True,
                'require_user_input': False,
                'metadata': {
                    'error': str(e),
                    'agent': '{{ agent_name }}'
                }
            }

# Agent class is ready to be instantiated by the factory function