"""Configuration management for GuardRail."""

import os
from pathlib import Path
from typing import Optional

import toml


class GuardRailConfig:
    """Manages GuardRail configuration and cache paths."""

    def __init__(self, root: Optional[Path] = None):
        """
        Initialize GuardRail config.

        Args:
            root: Project root directory. Defaults to current working directory.
        """
        if root is None:
            root = Path.cwd()
        self.root = Path(root).resolve()
        self.guardrail_dir = self.root / ".guardrail"
        self.config_file = self.guardrail_dir / "config.toml"
        self.cache_file = self.guardrail_dir / "cache.sqlite"

    def ensure_initialized(self) -> bool:
        """
        Check if GuardRail is initialized in this directory.

        Returns:
            True if initialized, False otherwise.
        """
        return self.config_file.exists() and self.cache_file.exists()

    def initialize(self, openai_api_key: Optional[str] = None) -> None:
        """
        Initialize GuardRail in the current directory.

        Args:
            openai_api_key: Optional OpenAI API key to store in config.
        """
        self.guardrail_dir.mkdir(exist_ok=True)

        # Create default config if it doesn't exist
        if not self.config_file.exists():
            default_config = {
                "version": "0.1.0",
                "test_dir": "tests/guardrail_generated",
                "cache_enabled": True,
            }
            if openai_api_key:
                default_config["openai_api_key"] = openai_api_key

            with open(self.config_file, "w") as f:
                toml.dump(default_config, f)
        elif openai_api_key:
            # Update existing config with API key
            config = self.load()
            config["openai_api_key"] = openai_api_key
            with open(self.config_file, "w") as f:
                toml.dump(config, f)

        # Create cache file if it doesn't exist
        if not self.cache_file.exists():
            self.cache_file.touch()

    def load(self) -> dict:
        """
        Load configuration from config.toml.

        Returns:
            Configuration dictionary.
        """
        if not self.config_file.exists():
            return {}
        with open(self.config_file, "r") as f:
            return toml.load(f)

    def get_test_dir(self) -> Path:
        """
        Get the test directory path from config.

        Returns:
            Path to test directory.
        """
        config = self.load()
        test_dir = config.get("test_dir", "tests/guardrail_generated")
        return self.root / test_dir

    def get_openai_api_key(self) -> Optional[str]:
        """
        Get OpenAI API key from config or environment.

        Returns:
            OpenAI API key if found, None otherwise.
        """
        # First check environment variable
        env_key = os.getenv("OPENAI_API_KEY")
        if env_key:
            return env_key

        # Then check config file
        config = self.load()
        return config.get("openai_api_key")
