"""ORCH-036 TC-11: the staging precondition is preserved (AC-8).

A red staging gate (``staging_status: FAILED``) must roll the task back to
development and NEVER let it reach the ``deploy`` stage — so the executable
prod self-deploy can never be initiated off a failed staging run. ORCH-036 adds
its Phase A interception AFTER ``check_staging_status``, so a staging failure
short-circuits before any self-deploy logic runs.
"""

import os
import tempfile

import pytest

_test_db = os.path.join(tempfile.gettempdir(), "test_orch_staging_precond.db")
os.environ["ORCH_DB_PATH"] = _test_db
os.environ["ORCH_REPOS_DIR"] = tempfile.gettempdir()
os.environ.setdefault("ORCH_GITEA_TOKEN", "test-token")
os.environ.setdefault("ORCH_PLANE_API_TOKEN", "test-token")

from unittest.mock import MagicMock  # noqa: E402

import src.db as _db  # noqa: E402
from src.db import init_db, get_db  # noqa: E402
from src import stage_engine  # noqa: E402
from src import self_deploy  # noqa: E402
from src.stage_engine import advance_stage  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_db(monkeypatch, tmp_path):
    monkeypatch.setattr(_db.settings, "db_path", _test_db)
    if os.path.exists(_test_db):
        os.unlink(_test_db)
    init_db()
    monkeypatch.setattr(self_deploy.settings, "repos_dir", str(tmp_path))
    monkeypatch.setattr(self_deploy.settings, "host_repos_dir", str(tmp_path))
    yield


@pytest.fixture(autouse=True)
def silence_side_effects(monkeypatch):
    for name in (
        "notify_stage_change", "notify_qg_failure", "notify_approve_requested",
        "send_telegram", "plane_notify_stage", "plane_notify_qg", "plane_add_comment",
        "set_issue_in_review", "set_issue_needs_input", "set_issue_in_progress",
        "set_issue_blocked", "set_issue_done",
    ):
        monkeypatch.setattr(stage_engine, name, MagicMock())


def _make_task(stage, repo="orchestrator", branch="feature/ORCH-036-x", wi="ORCH-036"):
    conn = get_db()
    cur = conn.execute(
        "INSERT INTO tasks (plane_id, work_item_id, repo, branch, stage) "
        "VALUES (?, ?, ?, ?, ?)",
        (f"plane-{wi}", wi, repo, branch, stage),
    )
    task_id = cur.lastrowid
    conn.commit()
    conn.close()
    return task_id


def _stage(task_id):
    conn = get_db()
    row = conn.execute("SELECT stage FROM tasks WHERE id=?", (task_id,)).fetchone()
    conn.close()
    return row[0]


def _fail(reason):
    def _f(*a, **k):
        return (False, reason)
    return _f


def test_tc11_staging_failed_never_reaches_deploy(monkeypatch):
    monkeypatch.setattr(stage_engine.settings, "deploy_require_manual_approve", True)
    monkeypatch.setattr(
        stage_engine, "QG_CHECKS",
        {**stage_engine.QG_CHECKS,
         "check_staging_status": _fail("Staging status: FAILED")},
    )
    # Guard: a failed staging run must not trigger any self-deploy logic.
    initiate = MagicMock()
    monkeypatch.setattr(stage_engine.self_deploy, "initiate_deploy", initiate)

    task_id = _make_task("deploy-staging")
    res = advance_stage(
        task_id, "deploy-staging", "orchestrator", "ORCH-036",
        "feature/ORCH-036-x", finished_agent="deployer",
    )

    assert res.advanced is False
    assert res.rolled_back_to == "development"
    assert _stage(task_id) == "development"   # NEVER reached deploy
    initiate.assert_not_called()
    assert not self_deploy.has_marker("orchestrator", "ORCH-036", self_deploy.APPROVE_REQUESTED)
