import os
import sys
import unittest
from unittest.mock import MagicMock, patch, AsyncMock

os.environ.setdefault("DISCORD_TOKEN", "dummy_discord_token")
os.environ.setdefault("GH_TOKEN", "dummy_gh_token")
os.environ.setdefault("ALLOWED_USER_ID", "123456789")

try:
    import discord
    from discord.ext import commands, tasks
except ImportError:
    discord_mock = MagicMock()
    sys.modules["discord"] = discord_mock
    sys.modules["discord.ext"] = MagicMock()
    commands_mock = MagicMock()
    commands_mock.Bot.return_value.command.side_effect = lambda **kwargs: (lambda f: f)
    sys.modules["discord.ext.commands"] = commands_mock
    tasks_mock = MagicMock()
    tasks_mock.loop.side_effect = lambda **kwargs: (lambda f: f)
    sys.modules["discord.ext.tasks"] = tasks_mock

try:
    import google.genai
except ImportError:
    sys.modules["google"] = MagicMock()
    sys.modules["google.genai"] = MagicMock()
    sys.modules["google.genai.types"] = MagicMock()

from src.config import load_and_scrub_config
from src.remote_control import (
    DEFAULT_INSTANCE_NAME,
    find_agy_bin,
    get_remote_control_status,
    start_remote_control,
    stop_remote_control,
    restart_remote_control,
    ensure_remote_control,
)


class TestRemoteControl(unittest.TestCase):
    @patch("shutil.which")
    def test_find_agy_bin_in_path(self, mock_which):
        mock_which.return_value = "/usr/bin/agy"
        self.assertEqual(find_agy_bin(), "/usr/bin/agy")

    @patch("shutil.which")
    @patch("pathlib.Path.is_file")
    @patch("os.access")
    def test_find_agy_bin_fallback(self, mock_access, mock_is_file, mock_which):
        mock_which.return_value = None
        mock_is_file.return_value = True
        mock_access.return_value = True
        self.assertEqual(find_agy_bin(), "/home/agent/.local/bin/agy")

    @patch("src.remote_control.find_agy_bin", return_value=None)
    def test_status_when_not_installed(self, mock_find):
        res = get_remote_control_status()
        self.assertFalse(res["available"])
        self.assertFalse(res["active"])
        self.assertIsNone(res["instance_name"])

    @patch("src.remote_control.find_agy_bin", return_value="/dummy/agy")
    @patch("subprocess.run")
    def test_status_active(self, mock_subproc, mock_find):
        mock_subproc.return_value = MagicMock(
            returncode=0,
            stdout=(
                "Daemon status: active (background process, PID 4567)\n"
                "Instance name: mipilot (find it at https://antigravity.google.com)"
            ),
            stderr="",
        )
        res = get_remote_control_status()
        self.assertTrue(res["available"])
        self.assertTrue(res["active"])
        self.assertEqual(res["instance_name"], "mipilot")
        self.assertEqual(res["pid"], 4567)

    @patch("src.remote_control.find_agy_bin", return_value="/dummy/agy")
    @patch("subprocess.run")
    def test_status_inactive(self, mock_subproc, mock_find):
        mock_subproc.return_value = MagicMock(
            returncode=0,
            stdout="Daemon status: inactive\nInstance name: not assigned yet",
            stderr="",
        )
        res = get_remote_control_status()
        self.assertTrue(res["available"])
        self.assertFalse(res["active"])
        self.assertIsNone(res["pid"])

    @patch("src.remote_control.find_agy_bin", return_value="/dummy/agy")
    @patch("subprocess.run")
    def test_start_remote_control(self, mock_subproc, mock_find):
        mock_subproc.return_value = MagicMock(
            returncode=0,
            stdout="Remote-control daemon started.",
            stderr="",
        )
        success, out = start_remote_control("mipilot")
        self.assertTrue(success)
        mock_subproc.assert_called_once_with(
            ["/dummy/agy", "remote-control", "start", "--name", "mipilot"],
            capture_output=True,
            text=True,
            timeout=30,
        )

    @patch("src.remote_control.find_agy_bin", return_value="/dummy/agy")
    @patch("subprocess.run")
    def test_stop_remote_control(self, mock_subproc, mock_find):
        mock_subproc.return_value = MagicMock(
            returncode=0,
            stdout="Remote-control daemon stopped.",
            stderr="",
        )
        success, out = stop_remote_control()
        self.assertTrue(success)
        mock_subproc.assert_called_once_with(
            ["/dummy/agy", "remote-control", "stop"],
            capture_output=True,
            text=True,
            timeout=30,
        )

    @patch("src.remote_control.start_remote_control")
    @patch("src.remote_control.stop_remote_control")
    def test_restart_remote_control(self, mock_stop, mock_start):
        mock_stop.return_value = (True, "Stopped")
        mock_start.return_value = (True, "Started")
        success, out = restart_remote_control("test-instance")
        self.assertTrue(success)
        mock_stop.assert_called_once()
        mock_start.assert_called_once_with("test-instance")

    @patch("src.remote_control.find_agy_bin", return_value="/dummy/agy")
    @patch("src.remote_control.get_remote_control_status")
    @patch("src.remote_control.start_remote_control")
    def test_ensure_remote_control_already_active(self, mock_start, mock_status, mock_find):
        mock_status.return_value = {
            "available": True,
            "active": True,
            "instance_name": "mipilot",
            "pid": 9999,
        }
        success, msg = ensure_remote_control("mipilot")
        self.assertTrue(success)
        self.assertIn("již aktivní", msg)
        mock_start.assert_not_called()

    @patch("src.remote_control.find_agy_bin", return_value="/dummy/agy")
    @patch("src.remote_control.get_remote_control_status")
    @patch("src.remote_control.start_remote_control")
    def test_ensure_remote_control_inactive_starts(self, mock_start, mock_status, mock_find):
        mock_status.return_value = {
            "available": True,
            "active": False,
            "instance_name": None,
            "pid": None,
        }
        mock_start.return_value = (True, "Remote-control daemon started.")
        success, msg = ensure_remote_control("mipilot")
        self.assertTrue(success)
        mock_start.assert_called_once_with("mipilot")


class TestConfigRemoteControl(unittest.TestCase):
    def test_config_loads_remote_control_name(self):
        os.environ["DISCORD_TOKEN"] = "token123"
        os.environ["GH_TOKEN"] = "ghtoken123"
        os.environ["ALLOWED_USER_ID"] = "42"
        os.environ["REMOTE_CONTROL_NAME"] = "custom-mipilot"

        cfg = load_and_scrub_config()
        self.assertEqual(cfg.remote_control_name, "custom-mipilot")


async def _invoke_cmd_remote(ctx, action=None):
    from src.main import cmd_remote
    func = getattr(cmd_remote, "callback", cmd_remote)
    return await func(ctx, action)


class TestDiscordCmdRemote(unittest.IsolatedAsyncioTestCase):
    async def test_cmd_remote_unauthorized(self):
        ctx = MagicMock()
        ctx.author.id = 999999999
        ctx.send = AsyncMock()
        await _invoke_cmd_remote(ctx, "status")
        ctx.send.assert_not_called()

    @patch("src.main.get_remote_control_status")
    async def test_cmd_remote_status_active(self, mock_status):
        mock_status.return_value = {
            "available": True,
            "active": True,
            "instance_name": "mipilot",
            "pid": 1234,
            "url": "https://antigravity.google.com",
        }
        ctx = MagicMock()
        ctx.author.id = 123456789
        ctx.send = AsyncMock()
        await _invoke_cmd_remote(ctx, "status")
        ctx.send.assert_called_once()
        embed = ctx.send.call_args[1].get("embed")
        self.assertIsNotNone(embed)
        self.assertIn("Aktivní", embed.description)

    @patch("src.main.start_remote_control", return_value=(True, "Started"))
    @patch("src.main.get_remote_control_status", return_value={"instance_name": "mipilot"})
    async def test_cmd_remote_start(self, mock_status, mock_start):
        from src.main import CONFIG
        ctx = MagicMock()
        ctx.author.id = 123456789
        ctx.send = AsyncMock()
        await _invoke_cmd_remote(ctx, "start")
        self.assertEqual(ctx.send.call_count, 2)
        mock_start.assert_called_once_with(CONFIG.remote_control_name)

    @patch("src.main.stop_remote_control", return_value=(True, "Stopped"))
    async def test_cmd_remote_stop(self, mock_stop):
        ctx = MagicMock()
        ctx.author.id = 123456789
        ctx.send = AsyncMock()
        await _invoke_cmd_remote(ctx, "stop")
        self.assertEqual(ctx.send.call_count, 2)
        mock_stop.assert_called_once()

    @patch("src.main.restart_remote_control", return_value=(True, "Restarted"))
    @patch("src.main.get_remote_control_status", return_value={"instance_name": "mipilot"})
    async def test_cmd_remote_restart(self, mock_status, mock_restart):
        from src.main import CONFIG
        ctx = MagicMock()
        ctx.author.id = 123456789
        ctx.send = AsyncMock()
        await _invoke_cmd_remote(ctx, "restart")
        self.assertEqual(ctx.send.call_count, 2)
        mock_restart.assert_called_once_with(CONFIG.remote_control_name)

    async def test_cmd_remote_invalid(self):
        ctx = MagicMock()
        ctx.author.id = 123456789
        ctx.send = AsyncMock()
        await _invoke_cmd_remote(ctx, "unknown-action")
        ctx.send.assert_called_once()
        self.assertIn("Neznámá akce", ctx.send.call_args[0][0])


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