"""ORCH-059 TC-07/08: the Phase B block in stage_engine.advance_stage initiates
the prod deploy ONLY on the confirm-deploy signal.

Contract (AC-2, AC-3, AC-5):
  * TC-07 — on (current_stage=="deploy", finished_agent is None) for the
    self-hosting repo: confirm_deploy=True -> Phase B initiates; confirm_deploy
    omitted/False (a plain Approved) -> a no-op that neither initiates the deploy
    nor runs check_deploy_status (no false БАГ-8 rollback).
  * TC-08 — idempotency: with the `initiated` marker already present, a repeated
    confirm-deploy does NOT initiate again.
"""

import os
import tempfile

import pytest

_test_db = os.path.join(tempfile.gettempdir(), "test_orch_phase_b.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))
    monkeypatch.setattr(stage_engine.settings, "deploy_require_manual_approve", True)
    yield


@pytest.fixture(autouse=True)
def silence_side_effects(monkeypatch):
    for name in (
        "notify_stage_change", "notify_qg_failure", "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(), raising=False)


def _make_task(stage, repo="orchestrator", branch="feature/ORCH-059-x", wi="ORCH-059"):
    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]


# ---------------------------------------------------------------------------
# TC-07: confirm-deploy initiates; plain Approved is a no-op
# ---------------------------------------------------------------------------
def test_tc07_confirm_deploy_initiates(monkeypatch):
    initiate = MagicMock(return_value=(True, "ok"))
    monkeypatch.setattr(stage_engine.self_deploy, "initiate_deploy", initiate)

    task_id = _make_task("deploy")
    res = advance_stage(
        task_id, "deploy", "orchestrator", "ORCH-059",
        "feature/ORCH-059-x", finished_agent=None, confirm_deploy=True,
    )

    assert res.note == "self-deploy-initiated"
    initiate.assert_called_once()
    assert self_deploy.has_marker("orchestrator", "ORCH-059", self_deploy.INITIATED)
    # Did NOT advance off deploy — the finalizer records the verdict later.
    assert _stage(task_id) == "deploy"


def test_tc07_approved_without_confirm_is_noop(monkeypatch):
    """A plain Approved on `deploy` (confirm_deploy defaults to False): no
    initiate_deploy, no rollback, no advance — a deterministic no-op (AC-3)."""
    initiate = MagicMock(return_value=(True, "ok"))
    monkeypatch.setattr(stage_engine.self_deploy, "initiate_deploy", initiate)
    # If check_deploy_status were (wrongly) run, it would intervene; spy to prove
    # it is never invoked on this no-op path.
    gate = MagicMock(return_value=(False, "FAILED"))
    monkeypatch.setattr(
        stage_engine, "QG_CHECKS",
        {**stage_engine.QG_CHECKS, "check_deploy_status": gate},
    )

    task_id = _make_task("deploy")
    res = advance_stage(
        task_id, "deploy", "orchestrator", "ORCH-059",
        "feature/ORCH-059-x", finished_agent=None,  # confirm_deploy omitted -> False
    )

    assert res.note == "approved-on-deploy-noop"
    initiate.assert_not_called()
    gate.assert_not_called()                 # check_deploy_status NOT run -> no false БАГ-8
    assert res.advanced is False
    assert res.rolled_back_to is None
    assert _stage(task_id) == "deploy"       # stays put, no rollback to development
    assert not self_deploy.has_marker("orchestrator", "ORCH-059", self_deploy.INITIATED)


# ---------------------------------------------------------------------------
# TC-08: idempotency — existing `initiated` marker -> repeat is a no-op
# ---------------------------------------------------------------------------
def test_tc08_idempotent_repeat_confirm_deploy(monkeypatch):
    initiate = MagicMock(return_value=(True, "ok"))
    monkeypatch.setattr(stage_engine.self_deploy, "initiate_deploy", initiate)

    task_id = _make_task("deploy")
    # Pre-seed the initiated marker (a deploy already in flight).
    self_deploy.write_marker("orchestrator", "ORCH-059", self_deploy.INITIATED, content="1")

    res = advance_stage(
        task_id, "deploy", "orchestrator", "ORCH-059",
        "feature/ORCH-059-x", finished_agent=None, confirm_deploy=True,
    )

    assert res.note == "self-deploy-already-initiated"
    initiate.assert_not_called()
