"""斗地主渲染器"""

from __future__ import annotations

from rich.text import Text
from rich.console import RenderableType

from ...protocol.renderer import register_renderer, render_doc

_HEAD = 'bold #e0e0e0'
_DIM = '#808080'
_SCORE = '#b0b0b0'
_SEP = '#454545'
_ACTIVE = 'bold #d0d0d0'
_DIZHU = 'bold #c0c0c0'
_FARMER = '#a0a0a0'
_WIN = 'bold #a0a0a0'
_IDX = '#606060'

_DOC_COMMANDS = {
    'create', 'rooms', 'start', 'invite', 'kick',
    'bid', 'play', 'pass', 'back', 'help',
}

_SUIT_DISPLAY = {'♠': '#b0b0b0', '♥': '#c07070', '♦': '#c07070', '♣': '#b0b0b0'}


def _card_style(card_str: str) -> str:
    if '☆' in card_str:
        return 'bold #d0d0d0'
    for suit, color in _SUIT_DISPLAY.items():
        if suit in card_str:
            return f'bold {color}'
    return 'bold #b0b0b0'


class DoudizhuRenderer:
    """斗地主渲染器"""

    game_type = 'doudizhu'

    def render_board(self, room_data: dict) -> RenderableType:
        state = room_data.get('room_state', 'lobby')
        if state == 'waiting':
            return self._render_waiting(room_data)
        if state == 'bidding':
            return self._render_bidding(room_data)
        if state in ('playing', 'finished'):
            return self._render_game(room_data)
        return self._render_lobby(room_data)

    def _render_lobby(self, data: dict) -> RenderableType:
        parts = []
        doc = data.get('doc')
        if doc:
            parts.append(render_doc(doc, _DOC_COMMANDS))
        msg = data.get('message')
        if msg:
            t = Text()
            if parts:
                t.append('\n')
            for line in msg.split('\n'):
                t.append(f'  {line}\n', style=_SCORE)
            parts.append(t)
        if not parts:
            return Text('')
        if len(parts) == 1:
            return parts[0]
        combined = Text()
        for p in parts:
            combined.append_text(p) if isinstance(p, Text) else combined.append(str(p))
        return combined

    def _render_waiting(self, data: dict) -> RenderableType:
        text = Text()
        room_id = data.get('room_id', '????')
        host = data.get('host', '???')
        players = data.get('players', [])
        max_p = data.get('max_players', 3)

        text.append('  🃏 斗地主\n\n', style=_HEAD)
        text.append(f'  房间 #{room_id}  房主: {host}\n', style=_SCORE)
        count = len(players) if isinstance(players, list) else 0
        text.append(f'  等待中 ({count}/{max_p})\n\n', style=_DIM)

        for p in players:
            if isinstance(p, str):
                text.append(f'  · {p}\n', style='#c0c0c0')
        msg = data.get('message')
        if msg:
            text.append(f'\n  {msg}\n', style=_SCORE)
        return text

    def _render_bidding(self, data: dict) -> RenderableType:
        text = Text()
        players = data.get('players', [])
        bids = data.get('bids', {})
        current = data.get('current_player', '')
        my_cards = data.get('my_cards', [])

        text.append('  🃏 斗地主 — 叫分阶段\n\n', style=_HEAD)

        for p in players:
            bid = bids.get(p)
            prefix = '→ ' if p == current else '  '
            text.append(prefix, style=_DIM)
            style = _ACTIVE if p == current else _SCORE
            text.append(p, style=style)
            if bid is not None:
                text.append(f'  叫了 {bid} 分' if bid > 0 else '  不叫', style=_DIM)
            else:
                text.append('  等待中...', style=_DIM)
            text.append('\n')

        # 显示自己的手牌
        if my_cards:
            text.append('\n  ' + '─' * 30 + '\n', style=_SEP)
            text.append('  你的手牌:\n  ', style=_HEAD)
            for i, c in enumerate(my_cards):
                text.append(f'{i}', style=_IDX)
                text.append(f'[{c}]', style=_card_style(c))
                text.append(' ')
            text.append('\n')

        msg = data.get('message')
        if msg:
            text.append(f'\n  {msg}\n', style=_SCORE)
        return text

    def _render_game(self, data: dict) -> RenderableType:
        text = Text()
        players = data.get('players', [])
        dizhu = data.get('dizhu', '')
        multiplier = data.get('multiplier', 1)
        hand_counts = data.get('hand_counts', {})
        current = data.get('current_player', '')
        last_play = data.get('last_play')
        dizhu_cards = data.get('dizhu_cards', [])
        my_cards = data.get('my_cards', [])
        state = data.get('room_state', 'playing')

        text.append('  🃏 斗地主', style=_HEAD)
        text.append(f'  倍率×{multiplier}', style=_DIM)
        text.append('\n\n')

        # 底牌
        if dizhu_cards:
            text.append('  底牌: ', style=_DIM)
            for c in dizhu_cards:
                text.append(f'[{c}]', style=_card_style(c))
                text.append(' ')
            text.append('\n')

        # 各玩家状态
        for p in players:
            prefix = '→ ' if p == current else '  '
            text.append(prefix, style=_DIM)

            role_style = _DIZHU if p == dizhu else _FARMER
            role_label = '👑' if p == dizhu else '  '
            text.append(f'{role_label}{p}', style=role_style)

            count = hand_counts.get(p, 0)
            text.append(f'  [{count}张]', style=_DIM)
            text.append('\n')

        # 上一手牌
        text.append('\n  ' + '─' * 30 + '\n', style=_SEP)
        if last_play:
            lp_player = last_play.get('player', '')
            lp_type = last_play.get('type', '')
            lp_cards = last_play.get('cards', [])
            text.append(f'  {lp_player} ({lp_type}): ', style=_SCORE)
            for c in lp_cards:
                text.append(f'[{c}]', style=_card_style(c))
                text.append(' ')
            text.append('\n')
        else:
            text.append('  (新一轮)\n', style=_DIM)

        # 自己的手牌
        if my_cards:
            text.append('\n  你的手牌:\n  ', style=_HEAD)
            for i, c in enumerate(my_cards):
                text.append(f'{i}', style=_IDX)
                text.append(f'[{c}]', style=_card_style(c))
                text.append(' ')
            text.append('\n')

        # 结果
        if state == 'finished':
            winner = data.get('winner', '')
            spring = data.get('spring', False)
            results = data.get('results', {})
            text.append('\n')
            role = '地主' if winner == dizhu else '农民'
            text.append(f'  ★ {winner} ({role}) 获胜！', style=_WIN)
            if spring:
                text.append(' 春天！', style=_WIN)
            text.append(f'  倍率×{multiplier}\n', style=_DIM)

        # 提示
        elif current:
            text.append(f'\n  轮到 {current}', style='bold #b8b8b8')
            if not last_play:
                text.append(' — 自由出牌', style=_DIM)
            text.append('\n')

        msg = data.get('message')
        if msg:
            text.append(f'\n  {msg}\n', style=_SCORE)

        return text


register_renderer(DoudizhuRenderer())
