"""Shared answer orchestrator — runs auto_respond questions for any stage."""

import json
from pathlib import Path

from mixersystem.data.repository import context_scope, init_session, update_session_run
from mixersystem.workflows.shared import question_answerer

VALID_STAGES = {"task", "plan", "work", "update", "upgrade", "report"}
VALID_MODES = {"marked", "all"}


def _load_questions(path: Path) -> list[dict]:
    if not path.is_file():
        return []
    try:
        data = json.loads(path.read_text())
        return data.get("questions", [])
    except (json.JSONDecodeError, OSError):
        return []


def _save_questions(path: Path, questions: list[dict]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps({"questions": questions}, indent=2) + "\n")


async def run(session_folder: str, stage: str = "task",
              lite: bool = False,
              depth: int | None = None,
              provider: str = "claude",
              mode: str = "marked",
              instructions: str = "") -> None:
    """Answer questions for any stage.

    mode="marked"  — only questions with auto_respond=True (default)
    mode="all"     — all unanswered, non-implemented questions
    """
    if stage not in VALID_STAGES:
        raise ValueError(f"Invalid stage '{stage}'. Must be one of: {', '.join(sorted(VALID_STAGES))}")
    if mode not in VALID_MODES:
        raise ValueError(f"Invalid mode '{mode}'. Must be one of: {', '.join(sorted(VALID_MODES))}")

    wf = Path(session_folder)
    wf.mkdir(parents=True, exist_ok=True)
    init_session(str(wf.resolve()))

    with context_scope(
        session_folder=str(wf.resolve()),
        lite=lite,
        depth=depth,
    ):
        update_session_run(str(wf.resolve()), "answer", provider=provider, mode=mode, target_stage=stage)
        questions_path = wf.resolve() / f"{stage}_questions.json"
        existing = _load_questions(questions_path)

        if mode == "all":
            # Temporarily mark all unanswered, non-implemented questions for responding
            to_answer_ids = {
                q["id"] for q in existing
                if not q.get("answer") and not q.get("implemented") and not q.get("inactive")
            }
            if not to_answer_ids:
                return
            tagged = [
                {**q, "auto_respond": True} if q["id"] in to_answer_ids else q
                for q in existing
            ]
            result = await question_answerer.run_respond(
                stage=stage, questions=tagged, provider=provider)
            # Restore original auto_respond flags for questions that weren't already marked
            for i, q in enumerate(result):
                if q["id"] in to_answer_ids and not existing[i].get("auto_respond"):
                    result[i] = {**q, "auto_respond": False}
            _save_questions(questions_path, result)
        else:
            # mode == "marked": only auto_respond=True questions
            if not any(q.get("auto_respond") for q in existing):
                return
            result = await question_answerer.run_respond(
                stage=stage, questions=existing, provider=provider)
            _save_questions(questions_path, result)


if __name__ == "__main__":
    from mixersystem.data.repository import run_cli
    run_cli(run)
