"""Grade widget rendering."""
import math
from ..models import GradeData
from ..themes import THEMES, TAG_COLORS, GRADE_COLORS
from ..utils import escape, card_wrapper, icon_svg
def render_grade_widget(data: GradeData, theme_name: str = "dark") -> str:
"""Renders the developer grade widget with stats and tags."""
t = THEMES[theme_name]
base = data.grade[0]
color = GRADE_COLORS.get(base, t["accent"])
score = data.score
radius = 36
circumference = 2 * math.pi * radius
offset = circumference * (1 - score / 100)
grade_font = 30 if len(data.grade) <= 2 else 22
# Stats row with icons
stat_labels = {
"commits": "Commits",
"prs": "PRs",
"stars": "Stars",
"repos": "Repos",
"followers": "Followers"
}
stat_keys = [k for k in ["commits", "prs", "stars", "repos", "followers"] if k in data.stats]
stats_svg = ""
stat_w = 340 / max(len(stat_keys), 1)
for i, key in enumerate(stat_keys):
val = data.stats[key]
sx = i * stat_w + stat_w / 2
val_str = f"{val:,}" if val < 100000 else f"{val/1000:.0f}k"
stats_svg += f'''
{icon_svg(key, t["text_secondary"])}
{val_str}
{stat_labels.get(key, key)}
'''
# Tag pills
tags_svg = ""
tx, ty = 0, 0
max_tw = 340
for tag in (data.tags or []):
tag_color = TAG_COLORS.get(tag.tag, t["accent"])
label = tag.tag.replace("-", " ").title()
tw = int(len(label) * 6.6 + 18)
pill_opacity = 0.9 if tag.source == "earned" else 0.55
if tx + tw > max_tw:
tx = 0
ty += 30
tags_svg += f'''
{escape(label)}
'''
tx += tw + 6
tags_h = ty + 24 if data.tags else 0
# Layout
stats_y = 100
tags_y = stats_y + 54
tag_padding = 18 if tags_h > 24 else 14
card_h = (tags_y + tags_h + tag_padding) if data.tags else (stats_y + 54)
inner = f'''
{escape(data.grade)}
{score:.0f} / 100
Developer Profile
Grade {escape(data.grade)} ยท {score:.0f}/100
{stats_svg}
'''
if data.tags:
inner += f'''
{tags_svg}
'''
return card_wrapper(inner, 380, card_h, t, "")