"""
AI Service
Handles AI generation using DeepSite workflow
"""

from typing import AsyncGenerator, Dict, Any
from workflows.ai_workflow import AIWorkflow

class AIService:
    def __init__(self):
        self.ai_workflow = AIWorkflow()
    
    async def generate_streaming_response(
        self, 
        prompt: str, 
        conversation_id: str = None
    ) -> AsyncGenerator[str, None]:
        """
        Generate streaming AI response using existing LangGraph workflow
        """
        try:
            # Use the existing LangGraph workflow for streaming
            async for chunk in self.ai_workflow.generate_response(
                prompt=prompt,
                thread_id=conversation_id or "default"
            ):
                yield chunk
                
        except Exception as e:
            yield f"Error: {str(e)}"
    
    def _extract_html_from_response(self, response: str) -> str:
        """
        Extract HTML content from AI response
        """
        # Remove any markdown code block formatting
        if '```html' in response:
            start = response.find('```html') + 7
            # Find the next ``` after ```html (not the last one)
            end = response.find('```', start)
            if end > start:
                return response[start:end].strip()
        
        # If no code blocks, return the response as is
        return response.strip()
    
    async def generate_sync_response(
        self, 
        prompt: str, 
        conversation_id: str = None
    ) -> Dict[str, Any]:
        """
        Generate synchronous AI response using existing LangGraph workflow
        """
        try:
            # Use the existing LangGraph workflow (no redundant code)
            result = await self.ai_workflow.generate_response_sync(
                prompt=prompt,
                thread_id=conversation_id or "default"
            )
            
            # Extract HTML if the LLM returned a full HTML file inside a code block
            raw_response = result.get("response", "") or ""
            extracted_html = self._extract_html_from_response(raw_response)

            return {
                "content": extracted_html,
                "is_complete": True,
                "conversation_id": conversation_id,
                "error": result.get("error")
            }
            
        except Exception as e:
            return {
                "content": f"Error: {str(e)}",
                "is_complete": True,
                "conversation_id": conversation_id,
                "error": True
            }