from __future__ import annotations

import unittest
from unittest.mock import patch

from prompt_toolkit.utils import get_cwidth
from rich.console import Console

from memnixa.config import AppConfig
from memnixa.gateway.ui import TerminalUI, _build_reply_subtitle


class GatewayUITests(unittest.TestCase):
    def _make_ui(self, *, width: int = 80) -> TerminalUI:
        return TerminalUI(
            via="local",
            config=AppConfig(api_key="test-key"),
            gateway_url="http://127.0.0.1:8787",
            console=Console(width=width, record=True),
            session=None,
            active_provider_id="provider-1",
            active_provider_label="VeryLongProviderLabel",
            active_model_name="deepseek-ai/DeepSeek-V3",
        )

    def test_render_turn_uses_memnixa_brand_for_assistant_title(self) -> None:
        ui = self._make_ui()

        with patch.dict("os.environ", {"MEMNIXA_LANG": "zh-CN"}, clear=False):
            ui.render_turn(
                "你好",
                {
                    "reply": "测试回复",
                    "mode": "local",
                    "iterations": 1,
                    "tool_events": [],
                    "provider_id": "provider-1",
                    "provider_label": "VeryLongProviderLabel",
                    "model_name": "deepseek-ai/DeepSeek-V3",
                    "run_id": "run-1",
                },
                render_user_message=False,
                render_tool_events=False,
                render_runtime_events=False,
            )

        output = ui.console.export_text()
        self.assertIn("Memnixa", output)
        self.assertNotIn("小月", output)

    def test_toolbar_text_compacts_to_terminal_width(self) -> None:
        ui = self._make_ui(width=28)

        toolbar = ui._toolbar_text(width=28)

        self.assertLessEqual(get_cwidth(toolbar), 28)
        self.assertIn("Memnixa", toolbar)
        self.assertIn("quit/exit", toolbar)

    def test_reply_subtitle_compacts_to_terminal_width(self) -> None:
        subtitle = _build_reply_subtitle(
            {
                "mode": "local",
                "iterations": 3,
                "tool_events": [{}, {}],
                "provider_id": "provider-1",
                "model_name": "deepseek-ai/DeepSeek-V3",
                "run_id": "run-1234567890",
            },
            width=26,
        )

        self.assertLessEqual(get_cwidth(subtitle), 26)


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