# -*- coding: utf-8 -*-
"""
_print_resumed_messages 视觉规则测试：
- user 消息：绿色粗体 `>`
- assistant content：前后灰色分隔线 + 青色内容
- assistant tool_calls：不加分隔线
"""
import types

import click
import pytest

from abyss.main import _print_resumed_messages
from abyss.ansi_menu import ansi_gray_line


@pytest.fixture(autouse=True)
def force_color(monkeypatch):
    """click.echo 在非 TTY 环境会剥离 ANSI 颜色码，测试时强制 color=True 保留。"""
    real_echo = click.echo

    def echo_keep_ansi(message="", **kwargs):
        kwargs.pop("color", None)
        return real_echo(message, color=True, **kwargs)

    monkeypatch.setattr(click, "echo", echo_keep_ansi)


def _make_session(messages):
    """构造一个简单的 session 对象，只含 messages 属性。"""
    s = types.SimpleNamespace()
    s.messages = messages
    return s


class TestUserMessageStyle:
    def test_user_message_uses_green_bold(self, capsys):
        """user 消息输出应含绿色粗体码 `\x1b[1;32m` 和 `>` 前缀。"""
        session = _make_session([
            {"role": "user", "content": "你好"},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        assert "\x1b[1;32m> 你好\x1b[0m" in out

    def test_user_message_not_plain_bold(self, capsys):
        """不应再使用旧的纯粗体 `\x1b[1m> `（无颜色码）。"""
        session = _make_session([
            {"role": "user", "content": "test"},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        # 不应出现 \x1b[1m> （纯粗体无颜色），应改为 \x1b[1;32m>
        assert "\x1b[1m> " not in out


class TestAssistantContentStyle:
    def test_assistant_content_has_leading_separator(self, capsys):
        """assistant content 前应有灰色分隔线。"""
        session = _make_session([
            {"role": "assistant", "content": "回复内容"},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        # 应包含 ansi_gray_line 的输出（灰色码 + ─）
        assert "\x1b[90m" in out
        assert "─" in out

    def test_assistant_content_uses_cyan(self, capsys):
        """assistant content 应使用青色 `\x1b[36m`。"""
        session = _make_session([
            {"role": "assistant", "content": "hello"},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        assert "\x1b[36mhello\x1b[0m" in out

    def test_assistant_content_has_trailing_separator(self, capsys):
        """assistant content 后应有灰色分隔线。"""
        session = _make_session([
            {"role": "assistant", "content": "回复"},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        # 分隔线应出现至少两次（前 + 后）
        count = out.count("─" * 20)
        # 至少有两条分隔线（每条至少 20 个 ─）
        assert count >= 2 or out.count("\x1b[90m") >= 2

    def test_assistant_content_separator_surrounds_content(self, capsys):
        """分隔线应分别出现在 content 之前和之后。"""
        session = _make_session([
            {"role": "assistant", "content": "MIDDLE"},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        # 找到 MIDDLE 的位置
        middle_idx = out.find("\x1b[36mMIDDLE")
        assert middle_idx > 0
        # MIDDLE 之前应有 ─（前分隔线）
        assert "─" in out[:middle_idx]
        # MIDDLE 之后应有 ─（后分隔线）
        assert "─" in out[middle_idx:]


class TestAssistantToolCallsStyle:
    def test_tool_calls_no_separator(self, capsys):
        """assistant tool_calls 占位不应加分隔线。"""
        session = _make_session([
            {"role": "assistant", "content": "", "tool_calls": [
                {"function": {"name": "read_file"}},
                {"function": {"name": "write_file"}},
            ]},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        # 不应有分隔线
        assert "─" not in out
        # 不应有青色码
        assert "\x1b[36m" not in out
        # 应有工具调用占位
        assert "[工具调用: read_file, write_file]" in out
        assert "\x1b[2m" in out  # dim 灰色

    def test_empty_assistant_no_output(self, capsys):
        """content 和 tool_calls 都为空的 assistant 消息不应输出任何内容。"""
        session = _make_session([
            {"role": "assistant", "content": "", "tool_calls": None},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        assert out == ""


class TestMixedMessages:
    def test_user_then_assistant_distinct(self, capsys):
        """user 和 assistant 消息应有明显的视觉区分。"""
        session = _make_session([
            {"role": "user", "content": "问题"},
            {"role": "assistant", "content": "回答"},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        # user 部分：绿色粗体
        assert "\x1b[1;32m> 问题\x1b[0m" in out
        # assistant 部分：青色 + 分隔线
        assert "\x1b[36m回答\x1b[0m" in out
        assert "─" in out

    def test_system_role_skipped(self, capsys):
        """system 角色的消息应被跳过。"""
        session = _make_session([
            {"role": "system", "content": "system prompt"},
            {"role": "user", "content": "hi"},
        ])
        _print_resumed_messages(session)
        out = capsys.readouterr().out
        assert "system prompt" not in out
        assert "hi" in out
