import uuid

from mixersystem.data.repository import get_context
from mixersystem.data.agent_sdk import call_agent

MODEL = "M"

ASK_PROMPT = """\
<role>
{role}
</role>

<steps>
1. Read the current artifact (if any):
{current_artifact}
2. Read other session artifacts:
{artifacts}
3. Read related session artifacts (parent/sibling/child sessions). These are for reference only — do not build according to them, they simply provide context about related work:
{family}
4. Read the following project docs:
{docs}
5. Read the rules that were used to produce this artifact:
{rules}
6. Read the template of the artifact you are producing:
{template}
7. Read the existing questions — these are for reference so you do not repeat them:
{existing_questions}
8. Read the questions the user liked — find the pattern in what the user values and generate more questions like these:
{liked_questions}
9. Read the questions the user disliked — find the pattern in what the user does not want and avoid generating questions like these:
{disliked_questions}
10. Read the additional instructions from the user:
{instructions}
</steps>

<constraints>
- Re-read your role carefully — everything it says is a hard requirement
- Only generate questions that genuinely matter — if nothing needs clarifying, generate none. If many things need clarifying, ask all of them.
- Ask questions that help clarify every field in the template — including optional fields — so the artifact builder has what it needs to fill them in
- Family context (parent/sibling/child sessions) is strictly informational — do not ask questions about parent/sibling/child sessions
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
questions:
- Question text here
- Another question here
- A third question here
[NOTES]
Summary of what areas the questions cover.
</output-format>"""


def _format_existing(questions: list[dict]) -> str:
    visible = [q for q in questions if not q.get("inactive") and not q.get("implemented")]
    if not visible:
        return "(none)"
    lines = []
    for q in visible:
        tag = " [answered]" if q.get("answer") else ""
        lines.append(f"- {q['text']}{tag}")
    return "\n".join(lines)


def _format_liked(questions: list[dict]) -> str:
    liked = [q for q in questions if q.get("reaction") == "like"]
    if not liked:
        return "(none)"
    return "\n".join(f"- {q['text']}" for q in liked)


def _format_disliked(questions: list[dict]) -> str:
    disliked = [q for q in questions if q.get("reaction") == "dislike"]
    if not disliked:
        return "(none)"
    return "\n".join(f"- {q['text']}" for q in disliked)


async def run_ask(*, stage: str, questions: list[dict],
                  provider: str = "claude", instructions: str = "") -> list[dict]:
    ctx = get_context()
    none = "(none)"

    prompt = ASK_PROMPT.format(
        role=ctx.resolve_role(stage, "question-builder"),
        current_artifact=ctx.resolve_current_artifact(stage) or none,
        artifacts=ctx.resolve_artifacts(stage) or none,
        family=ctx.resolve_family() or none,
        docs=ctx.resolve_docs() or none,
        rules=ctx.resolve_rules(stage) or none,
        template=ctx.resolve_template(stage) or none,
        existing_questions=_format_existing(questions),
        liked_questions=_format_liked(questions),
        disliked_questions=_format_disliked(questions),
        instructions=instructions or none,
    )

    response, _ = await call_agent(
        prompt=prompt,
        model=MODEL,
        provider=provider,
        agent_name=f"{stage}_question_builder",
    )

    new_questions = _parse_questions_response(response)
    return questions + new_questions


def _parse_questions_response(text: str) -> list[dict]:
    result_marker = text.find("[RESULT]")
    if result_marker == -1:
        return []

    after = text[result_marker + len("[RESULT]"):]
    notes_marker = after.find("[NOTES]")
    section = after[:notes_marker] if notes_marker != -1 else after

    questions = []
    for line in section.strip().splitlines():
        line = line.strip()
        if line.startswith("- ") and len(line) > 2:
            q_text = line[2:].strip()
            if q_text:
                questions.append({
                    "id": uuid.uuid4().hex[:8],
                    "text": q_text,
                    "answer": None,
                    "auto_respond": False,
                    "reaction": None,
                    "inactive": False,
                    "implemented": False,
                })
    return questions
