from mixersystem.data.agent_sdk import call_agent

MODEL = "M"

RESPOND_PROMPT = """\
Please answer the following questions about the project:

{questions_to_answer}

<constraints>
- Answer every question listed above
- Base answers on the actual project content (source code, docs, config) — not on session metadata files like questions.json or session.json
- Keep answers concise but complete
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
answers:
- Answer to first question
- Answer to second question
- Answer to third question
[NOTES]
Summary of answers provided.
</output-format>"""


def _format_to_answer(questions: list[dict]) -> str:
    pending = [q for q in questions if q.get("auto_respond") and not q.get("inactive")]
    if not pending:
        return "(none)"
    return "\n".join(f"- {q['text']}" for q in pending)


def _parse_answers_response(text: str) -> list[str]:
    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

    answers = []
    for line in section.strip().splitlines():
        line = line.strip()
        if line.startswith("- ") and len(line) > 2:
            answers.append(line[2:].strip())
    return answers


def _apply_answers(questions: list[dict], pending: list[dict], answers: list[str]) -> list[dict]:
    pending_ids = {q["id"] for q in pending}
    answer_iter = iter(answers)

    updated = []
    for q in questions:
        if q["id"] in pending_ids:
            answer = next(answer_iter, None)
            if answer:
                q = {**q, "answer": answer, "auto_respond": False}
        updated.append(q)
    return updated


async def run_respond(*, stage: str, questions: list[dict],
                      provider: str = "claude") -> list[dict]:
    pending = [q for q in questions if q.get("auto_respond") and not q.get("inactive")]
    if not pending:
        return questions

    prompt = RESPOND_PROMPT.format(
        questions_to_answer=_format_to_answer(questions),
    )

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

    answers = _parse_answers_response(response)
    return _apply_answers(questions, pending, answers)
