from __future__ import annotations

import unittest
from pathlib import Path

from agent_integration.config import AgentConfig, AgentConfigurationError


class AgentConfigTests(unittest.TestCase):
    def test_from_env_requires_key_for_network_use(self):
        with self.assertRaises(AgentConfigurationError):
            AgentConfig.from_env({}, require_api_key=True)

    def test_redacted_summary_never_contains_key(self):
        secret = "df_open_do_not_print_this_value"
        config = AgentConfig.from_env(
            {
                "DEERFLOW_OPEN_API_KEY": secret,
                "DEERFLOW_BASE_URL": "https://example.test/",
                "DEERFLOW_AUTH_MODE": "x-api-key",
                "DEERFLOW_SESSION_DB": "runtime/test.sqlite3",
            }
        )

        summary = config.redacted_summary()

        self.assertEqual(summary["base_url"], "https://example.test")
        self.assertEqual(summary["auth_mode"], "x-api-key")
        self.assertTrue(summary["api_key_configured"])
        self.assertNotIn(secret, repr(summary))
        self.assertEqual(config.session_db, Path("runtime/test.sqlite3"))

    def test_invalid_url_auth_mode_and_timeout_are_rejected(self):
        cases = (
            {"DEERFLOW_OPEN_API_KEY": "key", "DEERFLOW_BASE_URL": "not-a-url"},
            {"DEERFLOW_OPEN_API_KEY": "key", "DEERFLOW_BASE_URL": "http://remote.example"},
            {"DEERFLOW_OPEN_API_KEY": "key", "DEERFLOW_AUTH_MODE": "basic"},
            {"DEERFLOW_OPEN_API_KEY": "key", "DEERFLOW_TIMEOUT_SECONDS": "0"},
        )
        for env in cases:
            with self.subTest(env=env), self.assertRaises(AgentConfigurationError):
                AgentConfig.from_env(env)

    def test_example_placeholder_is_not_treated_as_configured(self):
        config = AgentConfig.from_env(
            {"DEERFLOW_OPEN_API_KEY": "df_open_replace_me"},
            require_api_key=False,
        )
        self.assertFalse(config.api_key_configured)
        with self.assertRaises(AgentConfigurationError):
            AgentConfig.from_env({"DEERFLOW_OPEN_API_KEY": "df_open_replace_me"})

    def test_plain_http_is_allowed_for_local_development_only(self):
        config = AgentConfig.from_env(
            {
                "DEERFLOW_OPEN_API_KEY": "df_open_test",
                "DEERFLOW_BASE_URL": "http://127.0.0.1:8000",
            }
        )
        self.assertEqual(config.base_url, "http://127.0.0.1:8000")


if __name__ == "__main__":
    unittest.main(verbosity=2)
