import os
import yaml
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Any


LLM_PROVIDER = "openai"
LLM_MODEL = "gpt-4o"
LLM_TEMPERATURE = 0.7

# Resolve relative to project root: config.py → llm_agent → puli_mcp_server → src → project root
_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
PROMPT_FILE_PATH = _PROJECT_ROOT / "prompts" / "analyze_code_prompt.yaml"


@dataclass
class LLMAgentConfig:
    """Configuration for LLM Agent, loaded from environment variables."""

    provider: str
    model: str
    temperature: float
    system_prompt: str

    @classmethod
    def from_env(cls) -> "LLMAgentConfig":
        """Load configuration from environment variables and local prompt file."""
        provider = os.environ.get("LLM_PROVIDER", LLM_PROVIDER)
        model = os.environ.get("LLM_MODEL", LLM_MODEL)
        temperature = float(os.environ.get("LLM_TEMPERATURE", LLM_TEMPERATURE))

        # Load prompt from absolute path
        try:
            with open(PROMPT_FILE_PATH, 'r', encoding='utf-8') as f:
                prompt_text = f.read()
            
            try:
                data = yaml.safe_load(prompt_text)
                system_prompt = data.get("prompt")
            except yaml.YAMLError as e:
                raise ValueError(f"Error parsing YAML prompt file: {e}")
            
            if not system_prompt:
                raise ValueError("System prompt 'prompt' key not found in YAML file")
            
        except FileNotFoundError:
            raise ValueError(f"Prompt file not found at {PROMPT_FILE_PATH}")
        except Exception as e:
            raise ValueError(f"Could not load prompt from {PROMPT_FILE_PATH}: {e}")

        return cls(
            provider=provider,
            model=model,
            temperature=temperature,
            system_prompt=system_prompt,
        )

    @classmethod
    def from_remote(cls, config: Dict[str, Any], prompts: Dict[str, Any]) -> "LLMAgentConfig":
        """Load configuration from remote config dict (fetched from proxy).
        
        Args:
            config: Configuration dictionary from proxy /config/mcp endpoint
            prompts: Prompts dictionary from proxy /config/mcp endpoint
        
        Returns:
            LLMAgentConfig instance with settings from remote config
        """
        provider = config.get("LLM_PROVIDER", LLM_PROVIDER)
        model = config.get("LLM_MODEL", LLM_MODEL)
        temperature = config.get("LLM_TEMPERATURE", LLM_TEMPERATURE)
        
        system_prompt = prompts.get("analyze_prompt")
        if not system_prompt:
            print(f"analyze_prompt not found in prompts configuration: {prompts}")
            raise ValueError("analyze_prompt not found in prompts configuration")
        
        return cls(
            provider=provider,
            model=model,
            temperature=temperature,
            system_prompt=system_prompt,
        )

