"""Tests for configuration management."""

import os
import tempfile
from pathlib import Path

from wcg.config import ConfigManager, Config, LLMConfig, RepositoryConfig


class TestConfigManager:
    """Test configuration manager."""
    
    def test_create_default_config(self):
        """Test creating default configuration."""
        with tempfile.TemporaryDirectory() as tmpdir:
            config_path = os.path.join(tmpdir, "config.yaml")
            manager = ConfigManager(config_path)
            
            config = manager.load()
            
            assert isinstance(config, Config)
            assert isinstance(config.llm, LLMConfig)
            assert len(config.repositories) > 0
            assert Path(config_path).exists()
    
    def test_save_and_load_config(self):
        """Test saving and loading configuration."""
        with tempfile.TemporaryDirectory() as tmpdir:
            config_path = os.path.join(tmpdir, "config.yaml")
            manager = ConfigManager(config_path)
            
            # Create custom config
            config = Config(
                llm=LLMConfig(
                    api_url="https://test.example.com",
                    api_key="test-key",
                    model="gpt-4"
                ),
                repositories=[
                    RepositoryConfig(
                        name="test/repo",
                        branch="main",
                        webhook_url="https://webhook.test"
                    )
                ],
                schedule_time="09:00",
                summary_dir="test_summaries",
                github_token="test-token"
            )
            
            # Save and reload
            manager.save(config)
            loaded_config = manager.load()
            
            # Verify
            assert loaded_config.llm.api_url == "https://test.example.com"
            assert loaded_config.llm.api_key == "test-key"
            assert loaded_config.llm.model == "gpt-4"
            assert len(loaded_config.repositories) == 1
            assert loaded_config.repositories[0].name == "test/repo"
            assert loaded_config.schedule_time == "09:00"
            assert loaded_config.github_token == "test-token"
    
    def test_add_repository(self):
        """Test adding repository configuration."""
        with tempfile.TemporaryDirectory() as tmpdir:
            config_path = os.path.join(tmpdir, "config.yaml")
            manager = ConfigManager(config_path)
            
            # Load default config
            manager.load()
            
            # Add repository
            manager.add_repository(
                name="new/repo",
                branch="develop",
                webhook_url="https://new-webhook.test"
            )
            
            # Verify
            config = manager.load()
            repo_names = [repo.name for repo in config.repositories]
            assert "new/repo" in repo_names
    
    def test_remove_repository(self):
        """Test removing repository configuration."""
        with tempfile.TemporaryDirectory() as tmpdir:
            config_path = os.path.join(tmpdir, "config.yaml")
            manager = ConfigManager(config_path)
            
            # Load default and add repository
            manager.load()
            manager.add_repository(
                name="test/repo",
                branch="main",
                webhook_url="https://test.webhook"
            )
            
            # Remove it
            manager.remove_repository("test/repo", "main")
            
            # Verify
            config = manager.load()
            repo_names = [repo.name for repo in config.repositories]
            assert "test/repo" not in repo_names
    
    def test_update_llm(self):
        """Test updating LLM configuration."""
        with tempfile.TemporaryDirectory() as tmpdir:
            config_path = os.path.join(tmpdir, "config.yaml")
            manager = ConfigManager(config_path)
            
            # Load default
            manager.load()
            
            # Update LLM config
            manager.update_llm(
                api_url="https://updated.example.com",
                api_key="updated-key",
                model="gpt-4-turbo"
            )
            
            # Verify
            config = manager.load()
            assert config.llm.api_url == "https://updated.example.com"
            assert config.llm.api_key == "updated-key"
            assert config.llm.model == "gpt-4-turbo"
    
    def test_custom_prompts_in_config(self):
        """Test that custom prompts can be saved and loaded."""
        with tempfile.TemporaryDirectory() as tmpdir:
            config_path = os.path.join(tmpdir, "config.yaml")
            manager = ConfigManager(config_path)
            
            # Create config with custom prompts
            custom_system = "Custom system prompt"
            custom_user_template = "Custom user prompt with {repo_name}"
            
            config = Config(
                llm=LLMConfig(
                    api_url="https://test.example.com",
                    api_key="test-key",
                    model="gpt-4",
                    system_prompt=custom_system,
                    user_prompt_template=custom_user_template
                ),
                repositories=[
                    RepositoryConfig(
                        name="test/repo",
                        branch="main",
                        webhook_url="https://webhook.test"
                    )
                ],
                github_token="test-token"
            )
            
            # Save and reload
            manager.save(config)
            loaded_config = manager.load()
            
            # Verify custom prompts are preserved
            assert loaded_config.llm.system_prompt == custom_system
            assert loaded_config.llm.user_prompt_template == custom_user_template
    
    def test_update_llm_with_prompts(self):
        """Test updating LLM configuration with custom prompts."""
        with tempfile.TemporaryDirectory() as tmpdir:
            config_path = os.path.join(tmpdir, "config.yaml")
            manager = ConfigManager(config_path)
            
            # Load default
            manager.load()
            
            # Update LLM config with prompts
            custom_system = "Updated system prompt"
            custom_user = "Updated user prompt template"
            
            manager.update_llm(
                api_url="https://test.com",
                api_key="test-key",
                model="gpt-4",
                system_prompt=custom_system,
                user_prompt_template=custom_user
            )
            
            # Verify
            config = manager.load()
            assert config.llm.system_prompt == custom_system
            assert config.llm.user_prompt_template == custom_user
    
    def test_default_prompts_when_not_specified(self):
        """Test that default prompts are used when not specified."""
        with tempfile.TemporaryDirectory() as tmpdir:
            config_path = os.path.join(tmpdir, "config.yaml")
            manager = ConfigManager(config_path)
            
            # Load default config
            config = manager.load()
            
            # Verify default prompts exist
            assert config.llm.system_prompt is not None
            assert len(config.llm.system_prompt) > 0
            assert config.llm.user_prompt_template is not None
            assert len(config.llm.user_prompt_template) > 0
            assert "{repo_name}" in config.llm.user_prompt_template
            assert "{branch}" in config.llm.user_prompt_template
            assert "{organized}" in config.llm.user_prompt_template
