"""Tests for config.write_global_config function."""

import tempfile
from pathlib import Path
from unittest.mock import patch

import pytest
from returns.result import Failure, Success

from lattice.shell.config import write_global_config


class TestWriteGlobalConfig:
    """Tests for write_global_config function."""

    def test_file_absent_creates_file(self, tmp_path: Path) -> None:
        """File absent — creates file with template content, returns Success((path, True))."""
        # Mock resolve_global_dir to return tmp_path
        with patch(
            "lattice.shell.config.resolve_global_dir",
            return_value=Success(tmp_path),
        ):
            result = write_global_config()

        assert isinstance(result, Success)
        config_path, created = result.unwrap()
        assert config_path == tmp_path / "config.toml"
        assert created is True
        assert config_path.exists()

        content = config_path.read_text()
        assert "[compiler]" in content
        assert "[embedding]" in content
        assert "[thresholds]" in content
        assert "# base_url" in content

    def test_file_present_is_noop(self, tmp_path: Path) -> None:
        """File present — no-op, returns Success((path, False)), file content unchanged."""
        config_path = tmp_path / "config.toml"
        original_content = "# Original config\n[model]\nname = 'test'\n"
        config_path.write_text(original_content)

        with patch(
            "lattice.shell.config.resolve_global_dir",
            return_value=Success(tmp_path),
        ):
            result = write_global_config()

        assert isinstance(result, Success)
        path, created = result.unwrap()
        assert path == config_path
        assert created is False
        assert config_path.read_text() == original_content

    def test_base_url_uncomments_and_sets(self, tmp_path: Path) -> None:
        """base_url provided — uncomments and sets base_url line in [compiler] section."""
        with patch(
            "lattice.shell.config.resolve_global_dir",
            return_value=Success(tmp_path),
        ):
            result = write_global_config(base_url="http://localhost:11434/v1")

        assert isinstance(result, Success)
        config_path, created = result.unwrap()
        assert created is True
        content = config_path.read_text()

        # The entire commented line (including trailing example comment) should be replaced
        assert 'base_url = "http://localhost:11434/v1"\n' in content
        # No stale comment should remain on the same line
        assert '# e.g., "https://' not in content

    def test_parent_directory_absent_creates_it(self, tmp_path: Path) -> None:
        """Parent directory absent — creates it, then writes file."""
        # Create a nested path that doesn't exist
        nested_path = tmp_path / "nested" / "deep" / "config"

        with patch(
            "lattice.shell.config.resolve_global_dir",
            return_value=Success(nested_path),
        ):
            result = write_global_config()

        assert isinstance(result, Success)
        config_path, created = result.unwrap()
        assert created is True
        assert config_path.exists()
        assert config_path.parent.exists()
        assert (config_path.parent).is_dir()
