"""ORCH-059 TC-09: the Phase A CTA asks the operator for "Confirm Deploy".

Contract (AC-6): when Phase A advances `deploy-staging` -> `deploy` and requests
manual approval, both the Plane comment and the Telegram notification must
instruct the operator to flip the status to "Confirm Deploy" (the dedicated
prod-deploy trigger) — and must NOT present "Approved" as the deploy trigger.
"""

import os
import tempfile

import pytest

_test_db = os.path.join(tempfile.gettempdir(), "test_orch_phase_a_cta.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


def _pass(*a, **k):
    return (True, "ok")


@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)
    # Pass the staging / merge / freshness sub-gates so the edge reaches Phase A.
    monkeypatch.setattr(
        stage_engine, "QG_CHECKS",
        {**stage_engine.QG_CHECKS,
         "check_staging_status": _pass,
         "check_branch_mergeable": _pass,
         # ORCH-022 integ: security-gate now runs on the deploy-staging->deploy
         # edge; this 059 test exercises the CTA, not the scanner (022 has its
         # own tests), so pass it like the other deploy sub-gates.
         "check_security_gate": _pass,
         "check_staging_image_fresh": _pass},
    )
    yield


def _make_task(stage="deploy-staging", 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 test_tc09_phase_a_cta_requests_confirm_deploy(monkeypatch):
    # Silence everything EXCEPT the two CTA channels we want to inspect.
    for name in (
        "notify_stage_change", "notify_qg_failure", "plane_notify_stage",
        "plane_notify_qg", "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)
    plane_comment = MagicMock()
    telegram = MagicMock()
    monkeypatch.setattr(stage_engine, "plane_add_comment", plane_comment)
    monkeypatch.setattr(stage_engine, "send_telegram", telegram)

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

    assert res.note == "self-deploy-approval-pending"

    # The Plane comment CTA mentions "Confirm Deploy" as the trigger.
    plane_comment.assert_called_once()
    comment_text = plane_comment.call_args.args[1]
    assert "Confirm Deploy" in comment_text
    # The Telegram CTA mentions "Confirm Deploy" too.
    telegram.assert_called_once()
    tg_text = telegram.call_args.args[0]
    assert "Confirm Deploy" in tg_text

    # Neither CTA presents bare "Approved" as the deploy trigger. (The comment may
    # mention Approved only to clarify it does NOT trigger; assert no instruction
    # to "set status to Approved".)
    assert "статус задачи на «Approved»" not in comment_text
    assert "на Approved" not in tg_text
