"""
sborniktestov-embed — Embed quizzes from sborniktestov.ru

Generates the HTML that loader.js expects:
  <div class="st-embed" data-quiz-id="..." ...>
    <a href="https://sborniktestov.ru">Sbornik Testov</a>
  </div>
  <script async src="https://sborniktestov.ru/embed/loader.js"></script>

Usage:
    from sborniktestov_embed import Embed

    e = Embed(12345, color_accent='4CAF50', radius=12)
    print(e.render())

https://sborniktestov.ru/embed/
"""

from html import escape
from urllib.parse import urlencode

__version__ = "1.0.0"
__all__ = ["Embed"]

LOADER_URL = "https://sborniktestov.ru/embed/loader.js"
SITE_URL = "https://sborniktestov.ru"

# Allowed data-attributes (without "data-" prefix, using underscores for Python kwargs)
_ALLOWED = {
    # toggles
    "comments", "related", "header", "desc", "stats",
    # layout
    "width", "min_height", "max_width",
    # colors
    "color_accent", "color_bg", "color_title", "color_text",
    "color_btn_text", "color_selected_bg", "color_progress_bg",
    "color_progress_fill", "color_border", "color_border_selected",
    "color_btn_prev", "color_hover",
    # fonts & sizes
    "font_title", "font_desc", "font_stats", "font_question",
    "font_answer", "radius", "padding",
}


class Embed:
    """Generate embed code for a sborniktestov.ru quiz."""

    def __init__(self, quiz_id: int, **kwargs):
        self.quiz_id = quiz_id
        self.attrs = {}
        for key, value in kwargs.items():
            if key in _ALLOWED and value is not None and str(value) != "":
                self.attrs[key] = str(value)

    def render(self) -> str:
        """Full embed HTML: div + script tag."""
        return self.div() + "\n" + self.script()

    def div(self) -> str:
        """Container div only (use when loader.js is already on the page)."""
        parts = [f'class="st-embed"', f'data-quiz-id="{self.quiz_id}"']
        for key, value in self.attrs.items():
            attr_name = "data-" + key.replace("_", "-")
            parts.append(f'{attr_name}="{escape(value)}"')

        link = f'<a href="{SITE_URL}">Sbornik Testov</a>'
        return f'<div {" ".join(parts)}>\n  {link}\n</div>'

    def script(self) -> str:
        """Loader script tag."""
        return f'<script async src="{LOADER_URL}"></script>'

    def iframe_url(self) -> str:
        """Direct iframe URL (bypassing loader.js)."""
        params = {"id": self.quiz_id}

        # Toggles that enable
        for key in ("comments", "related"):
            if self.attrs.get(key) == "1":
                params[key] = "1"

        # Toggles that disable (default is 1)
        for key in ("header", "desc", "stats"):
            if self.attrs.get(key) == "0":
                params[key] = "0"

        # Colors — strip # if present
        color_keys = [
            "color_accent", "color_bg", "color_title", "color_text",
            "color_btn_text", "color_selected_bg", "color_progress_bg",
            "color_progress_fill", "color_border", "color_border_selected",
            "color_btn_prev", "color_hover",
        ]
        for key in color_keys:
            if key in self.attrs:
                params[key] = self.attrs[key].lstrip("#")

        # Size params
        size_keys = [
            "font_title", "font_desc", "font_stats", "font_question",
            "font_answer", "radius", "padding", "max_width",
        ]
        for key in size_keys:
            if key in self.attrs:
                params[key] = self.attrs[key]

        return f"{SITE_URL}/embed/?{urlencode(params)}"
