"""Tests for env command."""

import os
from unittest.mock import patch

import pytest
from click.testing import CliRunner

from scry_run.cli import main


class TestEnvCommand:
    """Tests for scry-run env command."""

    def test_env_outputs_shell_exports(self, scry_run_home):
        """Test env outputs export statements."""
        runner = CliRunner()
        result = runner.invoke(main, ["env"])

        assert result.exit_code == 0
        assert "export SCRY_BACKEND=" in result.output
        assert "export SCRY_QUIET=" in result.output

    def test_env_loads_from_config(self, scry_run_home):
        """Test env loads values from config file."""
        config_path = scry_run_home / "config.toml"
        config_path.write_text("""
[defaults]
backend = "claude"

[backend.claude]
model = "opus"
""")

        # Clear SCRY_BACKEND to test config file loading
        saved_backend = os.environ.pop("SCRY_BACKEND", None)
        try:
            runner = CliRunner()
            result = runner.invoke(main, ["env"])

            assert 'export SCRY_BACKEND="claude"' in result.output
            assert 'export SCRY_MODEL="opus"' in result.output
        finally:
            if saved_backend is not None:
                os.environ["SCRY_BACKEND"] = saved_backend

    def test_env_eval_usage(self, scry_run_home):
        """Test env output can be eval'd."""
        runner = CliRunner()
        result = runner.invoke(main, ["env"])

        # Output should be valid shell
        for line in result.output.strip().split("\n"):
            if line and not line.startswith("#"):
                assert line.startswith("export ")
                assert "=" in line
