import importlib.util
import os
from pathlib import Path
import unittest
from unittest.mock import MagicMock, patch

spec = importlib.util.spec_from_file_location("kiln_daemon_refresh", Path(__file__).with_name("codex-daemon-refresh.py"))
refresh = importlib.util.module_from_spec(spec)
spec.loader.exec_module(refresh)


class DaemonRefreshTests(unittest.TestCase):
    def test_proxy_environment_only_appends_localhost_and_preserves_domains(self):
        env = {"NO_PROXY": "old.example,localhost", "no_proxy": "another.example", "HTTPS_PROXY": "http://127.0.0.1:1081"}
        with patch.dict(os.environ, env, clear=True):
            result = refresh.environment()
            self.assertEqual(dict(os.environ), env)
        self.assertEqual(result["HTTPS_PROXY"], env["HTTPS_PROXY"])
        self.assertEqual(result["NO_PROXY"], "old.example,localhost,127.0.0.1,::1")
        self.assertEqual(result["no_proxy"], "another.example,localhost,127.0.0.1,::1")

    def test_active_turn_defers_restart_without_signals_or_commands(self):
        with patch.object(refresh, "busy_turns", return_value=1), \
             patch.object(refresh.subprocess, "run") as command, patch.object(refresh.os, "kill") as kill:
            result = refresh.refresh(0)
        self.assertEqual(result, {"status": "deferred", "reason": "active_turns"})
        command.assert_not_called()
        kill.assert_not_called()

    def test_busy_count_reads_only_metadata_and_handles_all_loaded_threads(self):
        rpc = MagicMock()
        rpc.call.side_effect = [
            {"data": ["a", "b"], "nextCursor": None},
            {"thread": {"status": {"type": "active"}}},
            {"thread": {"status": {"type": "idle"}}},
        ]
        with patch.object(refresh, "LocalRpc", return_value=rpc):
            self.assertEqual(refresh.busy_turns(), 1)
        self.assertTrue(all(call.args[1]["includeTurns"] is False for call in rpc.call.call_args_list[1:]))
        rpc.close.assert_called_once()

    def test_unknown_activity_status_cannot_trigger_restart(self):
        rpc = MagicMock()
        rpc.call.side_effect = [{"data": ["a"]}, {"thread": {"status": {"type": "unknown"}}}]
        with patch.object(refresh, "LocalRpc", return_value=rpc):
            with self.assertRaises(RuntimeError):
                refresh.busy_turns()

    def test_failed_mcp_is_not_reported_as_connected(self):
        rpc = MagicMock()
        rpc.call.return_value = {"data": [{"name": "codex_tui", "tools": {}, "toolsError": "failed"}]}
        with patch.object(refresh, "LocalRpc", return_value=rpc):
            self.assertEqual(refresh.mcp_status("test"), {"connected": False, "tool_count": 0})

    def test_mcp_connection_requires_discovered_tools_without_error(self):
        rpc = MagicMock()
        rpc.call.return_value = {"data": [{"name": "codex_tui", "tools": {"tool": {}}, "toolsError": None}]}
        with patch.object(refresh, "LocalRpc", return_value=rpc):
            self.assertEqual(refresh.mcp_status("test"), {"connected": True, "tool_count": 1})

    def test_updater_with_correct_environment_is_not_signalled(self):
        record = MagicMock()
        record.exists.return_value = True
        record.read_text.return_value = '{"pid":12345}'
        with patch.object(refresh, "UPDATER_RECORD", record), \
             patch.object(refresh, "process_bypass", return_value=True), \
             patch.object(refresh.os, "kill") as kill:
            self.assertFalse(refresh.stop_stale_updater())
        kill.assert_not_called()

    def test_unknown_updater_process_is_never_signalled(self):
        record = MagicMock()
        record.exists.return_value = True
        record.read_text.return_value = '{"pid":12345}'
        path = MagicMock()
        path.__truediv__.return_value = path
        path.read_bytes.return_value = b'python\0unrelated-task\0'
        with patch.object(refresh, "UPDATER_RECORD", record), \
             patch.object(refresh, "process_bypass", return_value=False), \
             patch.object(refresh, "Path", return_value=path), \
             patch.object(refresh.os, "kill") as kill:
            with self.assertRaises(RuntimeError):
                refresh.stop_stale_updater()
        kill.assert_not_called()


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