"""Score/stats/profile command."""

import time

from mudlib.commands import CommandDefinition, register
from mudlib.player import Player


def format_play_time(seconds: float) -> str:
    """Format play time as human-readable string."""
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    parts = []
    if hours:
        parts.append(f"{hours}h")
    if minutes:
        parts.append(f"{minutes}m")
    parts.append(f"{secs}s")
    return " ".join(parts)


async def cmd_score(player: Player, _args: str) -> None:
    """Display character sheet with stats."""
    # Calculate K/D ratio
    kd_ratio = f"{player.kills / player.deaths:.1f}" if player.deaths > 0 else "N/A"

    # Format play time (accumulate current session first)
    total_seconds = player.play_time_seconds
    if player.session_start > 0:
        total_seconds += time.monotonic() - player.session_start
    play_time = format_play_time(total_seconds)

    lines = [
        f"--- {player.name} ---",
        f"PL: {player.pl:.0f}/{player.max_pl:.0f}",
        f"Stamina: {player.stamina:.0f}/{player.max_stamina:.0f}",
        f"Kills: {player.kills}  Deaths: {player.deaths}  K/D: {kd_ratio}",
        f"Time played: {play_time}",
    ]

    if player.unlocked_moves:
        moves = ", ".join(sorted(player.unlocked_moves))
        lines.append(f"Unlocked moves: {moves}")

    output = "\r\n".join(lines) + "\r\n"
    await player.send(output)


register(
    CommandDefinition(
        name="score",
        handler=cmd_score,
        aliases=["stats", "profile"],
        mode="*",
        help="Display your character stats and progression",
    )
)
