"""Shared question orchestrator — one workflow for all 6 stages."""

import json
from pathlib import Path

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

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


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",
              instructions: str = "") -> None:
    """Generate new questions for any stage."""
    if stage not in VALID_STAGES:
        raise ValueError(f"Invalid stage '{stage}'. Must be one of: {', '.join(sorted(VALID_STAGES))}")

    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()), "questions", provider=provider, target_stage=stage)
        questions_path = wf.resolve() / f"{stage}_questions.json"
        existing = _load_questions(questions_path)

        existing = await question_builder.run_ask(
            stage=stage, questions=existing, provider=provider, instructions=instructions)
        _save_questions(questions_path, existing)


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