"""Post-build checker: marks questions as implemented when their answers are reflected in the artifact."""

import json
from pathlib import Path

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

MODEL = "S"
_AGENT_NAME = "implementation_checker"

CHECK_PROMPT = """\
<role>
You are the Implementation Checker. You verify whether answered questions have been addressed in the built artifact.
</role>

<artifact>
{artifact_content}
</artifact>

<questions-to-check>
{questions_to_check}
</questions-to-check>

<steps>
1. For each question-answer pair below, check if the answer's intent is reflected in the artifact above
2. A question is "implemented" if the artifact demonstrates that the answer was considered and incorporated
3. Be generous — if the artifact reasonably addresses the answer's intent, mark it as implemented
</steps>

<constraints>
- Only output question IDs that ARE implemented
- If unsure, do NOT mark as implemented
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
implemented: id1, id2, id3
[NOTES]
Brief explanation of which questions were found implemented and why.
</output-format>"""


async def run(stage: str) -> None:
    """Check if answered questions have been implemented in the stage artifact.

    Reads <stage>_questions.json and <stage>.md, then marks questions as implemented.
    """
    ctx = get_context()
    if not ctx.session_folder:
        return

    questions_path = Path(ctx.session_folder) / f"{stage}_questions.json"
    artifact_path = Path(ctx.session_folder) / f"{stage}.md"

    if not questions_path.is_file() or not artifact_path.is_file():
        return

    try:
        data = json.loads(questions_path.read_text())
    except (json.JSONDecodeError, OSError):
        return

    questions = data.get("questions", [])
    to_check = [q for q in questions if q.get("answer") and not q.get("implemented")]
    if not to_check:
        return

    artifact_content = artifact_path.read_text()

    questions_text = "\n".join(
        f"- [{q['id']}] Q: {q['text']} | A: {q['answer']}"
        for q in to_check
    )

    prompt = CHECK_PROMPT.format(
        artifact_content=artifact_content,
        questions_to_check=questions_text,
    )

    response, _ = await call_agent(
        prompt=prompt,
        model=MODEL,
        agent_name=_AGENT_NAME,
    )

    # Parse implemented IDs from response
    implemented_ids = _parse_implemented(response)
    if not implemented_ids:
        return

    # Update questions
    for q in questions:
        if q["id"] in implemented_ids:
            q["implemented"] = True

    questions_path.write_text(json.dumps({"questions": questions}, indent=2) + "\n")


def _parse_implemented(text: str) -> set[str]:
    """Parse the implemented question IDs from the checker response."""
    result_marker = text.find("[RESULT]")
    if result_marker == -1:
        return set()

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

    for line in section.strip().splitlines():
        line = line.strip()
        if line.lower().startswith("implemented:"):
            ids_str = line.split(":", 1)[1].strip()
            if not ids_str or ids_str.lower() == "none":
                return set()
            return {id.strip() for id in ids_str.split(",") if id.strip()}

    return set()
