"""
RLM Integration - Direct, native integration with RLM core

No bridges, no HTTP, no external services. Pure Python.
"""

from dataclasses import dataclass
from typing import Any, Optional

from groknroll.core.exceptions import CompletionTimeoutError, CostLimitExceededError
from groknroll.core.rlm import RLM


@dataclass
class RLMConfig:
    """Configuration for RLM"""

    model: str = "gpt-4o-mini"
    max_cost: float = 5.0
    timeout_seconds: int = 300
    iteration_timeout_seconds: int = 30


@dataclass
class RLMResult:
    """Result from RLM completion"""

    response: str
    trace_log: str
    total_cost: float
    total_time: float
    iterations: int
    success: bool
    error: Optional[str] = None


class RLMIntegration:
    """
    Native RLM integration for groknroll

    Provides unlimited context reasoning directly integrated into the agent.
    No external services, everything runs in-process.
    """

    def __init__(self, config: Optional[RLMConfig] = None):
        """Initialize RLM integration"""
        self.config = config or RLMConfig()
        self.rlm = None
        self.env = None

    def initialize(self) -> None:
        """Initialize RLM and environment"""
        if self.rlm is None:
            self.rlm = RLM(
                backend="openai",
                backend_kwargs={"model_name": self.config.model},
                environment="local",
                max_cost=self.config.max_cost,
                timeout_seconds=self.config.timeout_seconds,
                iteration_timeout_seconds=self.config.iteration_timeout_seconds,
            )

    def complete(
        self,
        task: str,
        context: Optional[dict[str, Any]] = None,
        code_context: Optional[str] = None,
    ) -> RLMResult:
        """
        Execute RLM completion with unlimited context

        Args:
            task: The task description
            context: Additional context dict
            code_context: Code context to include

        Returns:
            RLMResult with response and metrics
        """
        self.initialize()

        try:
            # Build message with context
            message_content = self._build_message(task, context, code_context)

            # Execute RLM (RLM.completion takes a string prompt)
            result = self.rlm.completion(message_content)

            return RLMResult(
                response=result.response,
                trace_log="",  # RLM doesn't expose trace_log in public API
                total_cost=0.0,  # Would need to track via usage_summary
                total_time=result.execution_time if hasattr(result, "execution_time") else 0.0,
                iterations=len(result.iterations) if hasattr(result, "iterations") else 0,
                success=True,
            )

        except CostLimitExceededError as e:
            return RLMResult(
                response="",
                trace_log="",
                total_cost=self.config.max_cost,
                total_time=0.0,
                iterations=0,
                success=False,
                error=f"Cost limit exceeded: {e}",
            )

        except CompletionTimeoutError as e:
            return RLMResult(
                response="",
                trace_log="",
                total_cost=0.0,
                total_time=self.config.timeout_seconds,
                iterations=0,
                success=False,
                error=f"Timeout exceeded: {e}",
            )

        except Exception as e:
            return RLMResult(
                response="",
                trace_log="",
                total_cost=0.0,
                total_time=0.0,
                iterations=0,
                success=False,
                error=f"RLM execution failed: {e}",
            )

    def chat(
        self, messages: list[dict[str, str]], context: Optional[dict[str, Any]] = None
    ) -> RLMResult:
        """
        Chat with RLM using conversation history

        Args:
            messages: List of {role, content} dicts
            context: Additional context

        Returns:
            RLMResult with response
        """
        self.initialize()

        try:
            # Combine messages into a single prompt
            prompt_parts = []
            for msg in messages:
                prompt_parts.append(f"{msg['role']}: {msg['content']}")

            prompt = "\n\n".join(prompt_parts)

            # Add context if provided
            if context:
                context_str = "\n\nContext:\n" + "\n".join(
                    f"- {k}: {v}" for k, v in context.items()
                )
                prompt += context_str

            # Execute
            result = self.rlm.completion(prompt)

            return RLMResult(
                response=result.response,
                trace_log="",
                total_cost=0.0,
                total_time=result.execution_time if hasattr(result, "execution_time") else 0.0,
                iterations=len(result.iterations) if hasattr(result, "iterations") else 0,
                success=True,
            )

        except Exception as e:
            return RLMResult(
                response="",
                trace_log="",
                total_cost=0.0,
                total_time=0.0,
                iterations=0,
                success=False,
                error=str(e),
            )

    def analyze_code(
        self, code: str, analysis_type: str = "review", language: str = "python"
    ) -> RLMResult:
        """
        Analyze code using RLM

        Args:
            code: Code to analyze
            analysis_type: Type of analysis (review, security, complexity, etc)
            language: Programming language

        Returns:
            RLMResult with analysis
        """
        task = self._build_analysis_task(code, analysis_type, language)
        return self.complete(task, code_context=code)

    def _build_message(
        self, task: str, context: Optional[dict[str, Any]], code_context: Optional[str]
    ) -> str:
        """Build message content with context"""
        parts = [task]

        if context:
            parts.append("\n\nContext:")
            for key, value in context.items():
                parts.append(f"- {key}: {value}")

        if code_context:
            parts.append(f"\n\nCode:\n```\n{code_context}\n```")

        return "\n".join(parts)

    def _build_analysis_task(self, code: str, analysis_type: str, language: str) -> str:
        """Build analysis task prompt"""
        prompts = {
            "review": f"Review this {language} code for quality, bugs, and improvements:",
            "security": f"Perform a security audit of this {language} code:",
            "complexity": f"Analyze the complexity of this {language} code:",
            "refactor": f"Suggest refactorings for this {language} code:",
            "explain": f"Explain what this {language} code does:",
        }

        prompt = prompts.get(analysis_type, f"Analyze this {language} code:")
        return f"{prompt}\n\n```{language}\n{code}\n```"

    def reset(self) -> None:
        """Reset RLM environment"""
        # Re-initialize RLM to reset state
        self.rlm = None
        self.initialize()

    def get_stats(self) -> dict[str, Any]:
        """Get RLM usage statistics"""
        if self.rlm is None:
            return {"initialized": False}

        return {
            "initialized": True,
            "model": self.config.model,
            "max_cost": self.config.max_cost,
            "timeout": self.config.timeout_seconds,
        }
