"""Stage machine for orchestrator pipeline.

Stages:
  created → analysis → architecture → development → review → testing → deploy-staging → deploy → done

Each stage defines:
  - next: the stage to advance to
  - agent: the agent to launch when advancing FROM this stage (NOT the next stage's agent)
  - qg: the quality gate check required to leave this stage
"""

STAGE_TRANSITIONS = {
    "created": {"next": "analysis", "agent": "analyst", "qg": None},
    "analysis": {"next": "architecture", "agent": "architect", "qg": "check_analysis_approved"},
    "architecture": {"next": "development", "agent": "developer", "qg": "check_architecture_done"},
    "development": {"next": "review", "agent": "reviewer", "qg": "check_ci_green"},
    "review": {"next": "testing", "agent": "tester", "qg": "check_reviewer_verdict"},
    "testing":        {"next": "deploy-staging", "agent": "deployer",  "qg": "check_tests_passed"},
    "deploy-staging": {"next": "deploy",         "agent": "deployer",  "qg": "check_staging_status"},
    "deploy":         {"next": "done",            "agent": None,        "qg": "check_deploy_status"},
    "done": {"next": None, "agent": None, "qg": None},
}


def get_next_stage(current_stage: str) -> str | None:
    """Get the next stage after current."""
    transition = STAGE_TRANSITIONS.get(current_stage)
    if not transition:
        return None
    return transition["next"]


def get_agent_for_stage(stage: str) -> str | None:
    """Get the agent to launch when advancing FROM this stage (entering next stage)."""
    transition = STAGE_TRANSITIONS.get(stage)
    if not transition:
        return None
    return transition["agent"]


def get_qg_for_stage(current_stage: str) -> str | None:
    """Get the QG check function name required to leave current stage."""
    transition = STAGE_TRANSITIONS.get(current_stage)
    if not transition:
        return None
    return transition["qg"]


def get_previous_stage(current_stage: str) -> str | None:
    """Get the previous stage (for rollback)."""
    stages = list(STAGE_TRANSITIONS.keys())
    idx = stages.index(current_stage) if current_stage in stages else -1
    if idx <= 0:
        return None
    return stages[idx - 1]
