"""Tests for credential storage."""

import json
import os
import stat
from unittest.mock import patch

from agentcost.credentials import save, load, clear, resolve_api_key, CREDENTIALS_FILE


class TestCredentialStorage:
    def setup_method(self):
        """Use a temp config dir for tests."""
        self._original_file = CREDENTIALS_FILE
        self._test_dir = os.path.join(os.path.dirname(__file__), ".test_config")
        self._test_file = os.path.join(self._test_dir, "credentials.json")

    def teardown_method(self):
        """Clean up test files."""
        if os.path.exists(self._test_file):
            os.remove(self._test_file)
        tmp = self._test_file + ".tmp"
        if os.path.exists(tmp):
            os.remove(tmp)
        if os.path.exists(self._test_dir):
            os.rmdir(self._test_dir)

    def test_save_and_load(self):
        with patch("agentcost.credentials.CREDENTIALS_FILE", self._test_file), \
             patch("agentcost.credentials.CONFIG_DIR", self._test_dir):
            save("ac_test123")
            creds = load()
            assert creds["api_key"] == "ac_test123"
            assert creds["api_url"] == "https://agentmeter.com/api/v1"

    def test_save_custom_url(self):
        with patch("agentcost.credentials.CREDENTIALS_FILE", self._test_file), \
             patch("agentcost.credentials.CONFIG_DIR", self._test_dir):
            save("ac_test123", api_url="http://localhost:3000/api/v1")
            creds = load()
            assert creds["api_url"] == "http://localhost:3000/api/v1"

    def test_save_sets_file_permissions(self):
        with patch("agentcost.credentials.CREDENTIALS_FILE", self._test_file), \
             patch("agentcost.credentials.CONFIG_DIR", self._test_dir):
            save("ac_test123")
            mode = os.stat(self._test_file).st_mode
            # Owner read+write only (600)
            assert mode & 0o777 == 0o600

    def test_load_returns_none_when_no_file(self):
        with patch("agentcost.credentials.CREDENTIALS_FILE", "/tmp/nonexistent_agentcost_creds"):
            assert load() is None

    def test_clear_removes_file(self):
        with patch("agentcost.credentials.CREDENTIALS_FILE", self._test_file), \
             patch("agentcost.credentials.CONFIG_DIR", self._test_dir):
            save("ac_test123")
            assert os.path.exists(self._test_file)
            assert clear() is True
            assert not os.path.exists(self._test_file)

    def test_clear_returns_false_when_no_file(self):
        with patch("agentcost.credentials.CREDENTIALS_FILE", "/tmp/nonexistent_agentcost_creds"):
            assert clear() is False


class TestResolveApiKey:
    def test_explicit_key_wins(self):
        assert resolve_api_key("ac_explicit") == "ac_explicit"

    def test_env_var_second(self):
        with patch.dict(os.environ, {"AGENTCOST_API_KEY": "ac_env"}):
            assert resolve_api_key(None) == "ac_env"

    def test_stored_creds_third(self):
        with patch("agentcost.credentials.load", return_value={"api_key": "ac_stored"}), \
             patch.dict(os.environ, {}, clear=True):
            # Remove env var if set
            os.environ.pop("AGENTCOST_API_KEY", None)
            assert resolve_api_key(None) == "ac_stored"

    def test_explicit_overrides_env(self):
        with patch.dict(os.environ, {"AGENTCOST_API_KEY": "ac_env"}):
            assert resolve_api_key("ac_explicit") == "ac_explicit"

    def test_returns_none_when_nothing(self):
        with patch("agentcost.credentials.load", return_value=None), \
             patch.dict(os.environ, {}, clear=True):
            os.environ.pop("AGENTCOST_API_KEY", None)
            assert resolve_api_key(None) is None
