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

import json
from importlib import import_module
from pathlib import Path

from mixersystem.data.repository import context_scope, init_session, update_session_run


# Stage -> builder module path
_BUILDERS = {
    "task": "mixersystem.workflows.task.task_question_builder",
    "plan": "mixersystem.workflows.plan.plan_question_builder",
    "work": "mixersystem.workflows.work.work_question_builder",
    "update": "mixersystem.workflows.update.update_question_builder",
    "upgrade": "mixersystem.workflows.upgrade.upgrade_question_builder",
    "report": "mixersystem.workflows.report.report_question_builder",
}

VALID_STAGES = set(_BUILDERS)


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")


def _has_pending_auto_respond(questions: list[dict]) -> bool:
    return any(q.get("auto_respond") and not q.get("answer") for q in questions)


async def run(session_folder: str, stage: str = "task",
              lite: bool = False,
              depth: int | None = None,
              provider: str = "claude",
              mode: str = "ask") -> None:
    """Generate or respond to questions for any stage."""
    if stage not in VALID_STAGES:
        raise ValueError(f"Invalid stage '{stage}'. Must be one of: {', '.join(sorted(VALID_STAGES))}")

    builder = import_module(_BUILDERS[stage])

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

        # Step 1: Respond to auto_respond questions
        if _has_pending_auto_respond(existing):
            existing = await builder.run_respond(
                questions=existing, provider=provider)
            _save_questions(questions_path, existing)

        # Step 2: Generate new questions (if mode == "ask")
        if mode == "ask":
            existing = await builder.run_ask(
                questions=existing, provider=provider)
            _save_questions(questions_path, existing)


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