"""
Tests for environment bootstrapping helpers.
"""

import os
import tempfile
import unittest
from unittest.mock import patch

from vcks.env import load_app_env


class LoadAppEnvTests(unittest.TestCase):
    """
    Verifies .app_env parsing behavior.
    """

    def _create_env_file(self, content):
        with tempfile.NamedTemporaryFile('w', delete=False, encoding='utf-8') as handle:
            handle.write(content)
            return handle.name

    def test_missing_file_does_not_raise(self):
        """
        Missing env files are ignored.
        """
        with patch.dict(os.environ, {}, clear=True):
            load_app_env('/tmp/does-not-exist-vcks-app-env')

    def test_loads_simple_key_value_pairs(self):
        """
        Simple KEY=value lines are loaded.
        """
        env_file = self._create_env_file("VCKS_EMAIL_HOST=smtp.example.com\n")

        try:
            with patch.dict(os.environ, {}, clear=True):
                load_app_env(env_file)

                self.assertEqual(os.environ['VCKS_EMAIL_HOST'], 'smtp.example.com')
        finally:
            os.unlink(env_file)

    def test_supports_export_prefixed_lines_and_quotes(self):
        """
        Shell-style export lines and quoted values are supported.
        """
        env_file = self._create_env_file(
            "export VCKS_EMAIL_HOST='smtp.example.com'\n"
            'export VCKS_EMAIL_USER="mailer"\n'
        )

        try:
            with patch.dict(os.environ, {}, clear=True):
                load_app_env(env_file)

                self.assertEqual(os.environ['VCKS_EMAIL_HOST'], 'smtp.example.com')
                self.assertEqual(os.environ['VCKS_EMAIL_USER'], 'mailer')
        finally:
            os.unlink(env_file)

    def test_preserves_existing_environment_variables(self):
        """
        Existing exported variables win over file defaults.
        """
        env_file = self._create_env_file("VCKS_EMAIL_HOST=file.example.com\n")

        try:
            with patch.dict(os.environ, {'VCKS_EMAIL_HOST': 'shell.example.com'}, clear=True):
                load_app_env(env_file)

                self.assertEqual(os.environ['VCKS_EMAIL_HOST'], 'shell.example.com')
        finally:
            os.unlink(env_file)

    def test_ignores_comments_and_supports_values_with_equals(self):
        """
        Comments are ignored and values may contain '='.
        """
        env_file = self._create_env_file(
            "# comment\n"
            "VCKS_EMAIL_PASSWORD=abc=123\n"
        )

        try:
            with patch.dict(os.environ, {}, clear=True):
                load_app_env(env_file)

                self.assertEqual(os.environ['VCKS_EMAIL_PASSWORD'], 'abc=123')
        finally:
            os.unlink(env_file)
