"""
Survey stimulus — questions presented to the participant, responses captured and
saved per participant, event-locked by LSL markers like any other stimulus.

A survey is just a stimulus leaf with kind="survey"; its questions live in the
block's `props["questions"]`. Question types: likert, choice, multi, scale, text.
This module builds the question model and renders the survey HTML the player shows;
the app stores responses and includes them in the statistical export.
"""

from __future__ import annotations

from dataclasses import dataclass, field, asdict


@dataclass
class Question:
    id: str
    text: str
    type: str = "likert"            # likert | choice | multi | scale | text
    options: list = field(default_factory=list)   # for choice/multi
    min: int = 1                    # for likert/scale
    max: int = 7
    min_label: str = ""
    max_label: str = ""
    required: bool = True

    def to_dict(self):
        return asdict(self)


def likert(id, text, points=7, min_label="Strongly disagree",
           max_label="Strongly agree", **kw) -> dict:
    return Question(id, text, "likert", min=1, max=points,
                    min_label=min_label, max_label=max_label, **kw).to_dict()


def choice(id, text, options, multi=False, **kw) -> dict:
    return Question(id, text, "multi" if multi else "choice",
                    options=list(options), **kw).to_dict()


def text(id, text_, **kw) -> dict:
    return Question(id, text_, "text", **kw).to_dict()


def example_survey() -> list[dict]:
    return [
        likert("clarity", "The ad's message was clear."),
        likert("appeal", "I found the ad appealing."),
        choice("recall", "Which brand was shown?",
               ["Brand A", "Brand B", "Don't remember"]),
        text("comment", "Any other thoughts?", required=False),
    ]


# --------------------------------------------------------------------------
def render_questions(questions: list[dict]) -> str:
    """Render the question widgets (the player wraps this in a themed page)."""
    out = []
    for q in questions:
        qid = q["id"]
        head = (f'<div class="q"><div class="qtext">{q["text"]}'
                f'{" *" if q.get("required", True) else ""}</div>')
        t = q.get("type", "likert")
        if t in ("likert", "scale"):
            lo, hi = q.get("min", 1), q.get("max", 7)
            pts = "".join(
                f'<label class="pt"><input type="radio" name="{qid}" value="{v}">'
                f'<span>{v}</span></label>' for v in range(lo, hi + 1))
            out.append(head + f'<div class="scale"><span class="end">{q.get("min_label","")}</span>'
                       f'<div class="pts">{pts}</div><span class="end">{q.get("max_label","")}</span></div></div>')
        elif t in ("choice", "multi"):
            it = "checkbox" if t == "multi" else "radio"
            opts = "".join(
                f'<label class="opt"><input type="{it}" name="{qid}" value="{o}"> {o}</label>'
                for o in q.get("options", []))
            out.append(head + f'<div class="opts">{opts}</div></div>')
        else:  # text
            out.append(head + f'<textarea name="{qid}" rows="3" '
                       f'style="width:100%"></textarea></div>')
    return "\n".join(out)
