"""Dialog-Prompt parsen – Sarah/Laura oder Stimme 1/2 aus Textfeld."""

from __future__ import annotations

import re

_SPEAKER_LINE = re.compile(
    r"^(Sarah|Laura|sarah|laura|Stimme\s*1|Stimme\s*2|Speaker\s*1|Speaker\s*2|"
    r"Frau\s*1|Frau\s*2|Person\s*1|Person\s*2)\s*[:\-–—]\s*(.+)$",
    re.IGNORECASE,
)


def _map_speaker(raw: str) -> str:
    n = raw.strip().lower().replace(" ", "")
    if n in ("sarah", "stimme1", "speaker1", "frau1", "person1"):
        return "sarah"
    if n in ("laura", "stimme2", "speaker2", "frau2", "person2"):
        return "laura"
    return "sarah"


def parse_dialogue_prompt(text: str) -> list[tuple[str, str]]:
    """Textfeld → Dialogzeilen [(speaker, text), …]."""
    raw = (text or "").strip()
    if not raw:
        from jam.ia1minute import weekend_date_turns

        return weekend_date_turns()

    turns: list[tuple[str, str]] = []
    for line in raw.splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        m = _SPEAKER_LINE.match(line)
        if m:
            sp = _map_speaker(m.group(1))
            txt = m.group(2).strip()
            if txt:
                turns.append((sp, txt))
        elif turns:
            prev_sp, prev_txt = turns[-1]
            turns[-1] = (prev_sp, f"{prev_txt} {line}".strip())

    if turns:
        return turns

    # Kein „Name:“ Format – abwechselnd Sarah/Laura pro Absatz
    blocks = [b.strip() for b in re.split(r"\n\s*\n", raw) if b.strip()]
    if len(blocks) >= 2:
        out: list[tuple[str, str]] = []
        for i, block in enumerate(blocks):
            sp = "sarah" if i % 2 == 0 else "laura"
            one_line = " ".join(block.split())
            if one_line:
                out.append((sp, one_line))
        if out:
            return out

    from jam.ia1minute import weekend_date_turns

    return weekend_date_turns()
