"""ORCH-059 TC-04/05/06: webhook routing for the dedicated "Confirm Deploy"
status vs. the overloaded "Approved".

Contract (AC-2, AC-3, AC-4):
  * TC-04 — handle_issue_updated routes a "Confirm Deploy" status on a `deploy`
    task to the Phase B path (handle_confirm_deploy -> advance_stage with
    confirm_deploy=True), NOT the plain approve/advance path.
  * TC-05 — an "Approved" status on a `deploy` task does NOT initiate the prod
    deploy (self_deploy.initiate_deploy is never called).
  * TC-06 — an "Approved" status on an `analysis` task still advances
    analysis -> architecture (the approved-via-status human gate is intact).
"""

import os
import tempfile

import pytest

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

from unittest.mock import AsyncMock, 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
import src.plane_sync as plane_sync  # noqa: E402
import src.webhooks.plane as wh  # noqa: E402

IN_PROGRESS = "11111111-1111-1111-1111-111111111111"
APPROVED = "22222222-2222-2222-2222-222222222222"
REJECTED = "33333333-3333-3333-3333-333333333333"
CONFIRM = "44444444-4444-4444-4444-444444444444"

_STATES = {
    "in_progress": IN_PROGRESS,
    # ORCH-066 integ: real get_project_states always exposes to_analyse
    # (aliased to in_progress on projects without the dedicated status).
    "to_analyse": IN_PROGRESS,
    # ORCH-066 integ: full status-model keys alias to base UUIDs,
    # mirroring get_project_states() _STATE_ALIAS_FALLBACK in production.
    "analysis": IN_PROGRESS,
    "code_review": APPROVED,
    "awaiting_deploy": IN_PROGRESS,
    "deploying": IN_PROGRESS,
    "monitoring": APPROVED,
    "approved": APPROVED,
    "rejected": REJECTED,
    "confirm_deploy": CONFIRM,
}


@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()
    # Deterministic per-project states (no network). handle_issue_updated imports
    # get_project_states locally from ..plane_sync, so patch it at the source.
    monkeypatch.setattr(plane_sync, "get_project_states", lambda pid: _STATES)
    # Isolate sentinel dirs.
    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_engine(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", plane_id="plane-ORCH-059"):
    conn = get_db()
    cur = conn.execute(
        "INSERT INTO tasks (plane_id, work_item_id, repo, branch, stage) "
        "VALUES (?, ?, ?, ?, ?)",
        (plane_id, wi, repo, branch, stage),
    )
    task_id = cur.lastrowid
    conn.commit()
    conn.close()
    return task_id


def _payload(state_uuid, plane_id="plane-ORCH-059"):
    return {"id": plane_id, "state": {"id": state_uuid}}


# ---------------------------------------------------------------------------
# TC-04: "Confirm Deploy" routes to the Phase B path with confirm_deploy=True
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_tc04_confirm_deploy_routes_phase_b(monkeypatch):
    _make_task("deploy")
    spy = AsyncMock()
    monkeypatch.setattr(wh, "_try_advance_stage", spy)
    # handle_verdict must NOT be taken for the confirm-deploy status.
    verdict_spy = AsyncMock()
    monkeypatch.setattr(wh, "handle_verdict", verdict_spy)

    await wh.handle_issue_updated(_payload(CONFIRM), "proj")

    spy.assert_awaited_once()
    # confirm_deploy=True must be threaded through.
    assert spy.await_args.kwargs.get("confirm_deploy") is True
    verdict_spy.assert_not_awaited()


@pytest.mark.asyncio
async def test_tc04b_confirm_deploy_off_deploy_stage_is_noop(monkeypatch):
    """Guard: a stray "Confirm Deploy" on a non-deploy stage is a no-op (no advance)."""
    _make_task("analysis")
    spy = AsyncMock()
    monkeypatch.setattr(wh, "_try_advance_stage", spy)

    await wh.handle_confirm_deploy(_payload(CONFIRM), "proj")

    spy.assert_not_awaited()


# ---------------------------------------------------------------------------
# TC-05: "Approved" on `deploy` does NOT initiate the prod deploy
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_tc05_approved_on_deploy_does_not_initiate(monkeypatch):
    monkeypatch.setattr(stage_engine.settings, "deploy_require_manual_approve", True)
    _make_task("deploy")
    initiate = MagicMock()
    monkeypatch.setattr(stage_engine.self_deploy, "initiate_deploy", initiate)

    # Real routing: Approved -> handle_verdict -> _try_advance_stage(confirm_deploy=False)
    # -> advance_stage -> the deploy block no-ops (does not initiate).
    await wh.handle_issue_updated(_payload(APPROVED), "proj")

    initiate.assert_not_called()


# ---------------------------------------------------------------------------
# TC-06: "Approved" on `analysis` still advances analysis -> architecture
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_tc06_approved_on_analysis_still_advances(monkeypatch):
    task_id = _make_task("analysis")

    await wh.handle_issue_updated(_payload(APPROVED), "proj")

    conn = get_db()
    stage = conn.execute("SELECT stage FROM tasks WHERE id=?", (task_id,)).fetchone()[0]
    conn.close()
    assert stage == "architecture"
