import unittest

from hiveos.services.intent_service import (
    SESSION_TERMINAL_TARGET_ID,
    _canonicalize_tool_and_action,
    _extract_command,
    _extract_requested_language,
    _fallback_plan,
    _worker_scope_for_target,
)


class IntentNormalizationTests(unittest.TestCase):
    def test_terminal_open_alias_normalizes(self):
        tool, action = _canonicalize_tool_and_action("terminal.open", "create", {})
        self.assertEqual("terminal.session", tool)
        self.assertEqual("open", action)

    def test_terminal_execute_alias_normalizes(self):
        tool, action = _canonicalize_tool_and_action("terminal.execute", "execute", {})
        self.assertEqual("terminal.exec", tool)
        self.assertEqual("run", action)

    def test_generic_terminal_with_run_action_normalizes(self):
        tool, action = _canonicalize_tool_and_action("terminal", "run", {"command": "echo hi"})
        self.assertEqual("terminal.exec", tool)
        self.assertEqual("run", action)

    def test_extract_command_preserves_echo_with_quoted_text(self):
        command = _extract_command('spin up a terminal and echo "hello friend. Welcome to HiveOS"')
        self.assertEqual('echo "hello friend. Welcome to HiveOS"', command)

    def test_fallback_plan_uses_session_terminal_when_requested(self):
        plan = _fallback_plan('use the session terminal and run echo "hello"')
        self.assertEqual("session-terminal", plan["target_id"])
        open_step = plan["steps"][0]
        self.assertEqual("terminal.session", open_step["tool_id"])
        self.assertEqual("session-terminal", open_step["args"]["target_id"])

    def test_fallback_plan_uses_scoped_terminal_by_default(self):
        plan = _fallback_plan('spin up a terminal and run echo "hello"')
        self.assertTrue(str(plan["target_id"]).startswith("intent-terminal-"))

    def test_worker_scope_for_session_target(self):
        self.assertEqual("session", _worker_scope_for_target(SESSION_TERMINAL_TARGET_ID))

    def test_worker_scope_for_scoped_target(self):
        self.assertEqual("scoped", _worker_scope_for_target("intent-terminal-abc123"))

    def test_extract_requested_language_french(self):
        language = _extract_requested_language("translate session terminal to french")
        self.assertEqual("french", language)

    def test_fallback_localize_uses_requested_language(self):
        plan = _fallback_plan("translate session terminal to french")
        transform_steps = [
            step for step in plan.get("steps", [])
            if step.get("tool_id") == "terminal.transform" and step.get("action") == "apply"
        ]
        self.assertTrue(transform_steps)
        config = transform_steps[0].get("args", {}).get("config", {})
        self.assertEqual("french", config.get("language"))


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