"""ORCH-016 / TC-18 + AC-7: notify_done / set_issue_done not regressed.

The final deploy -> done transition still posts the «✅ Task completed!»
comment under the deployer bot, alongside the new ORCH-016 status comment
the deployer publishes when it finishes the stage. The two comments are
independent — the status comment doesn't replace `notify_done`.
"""

import os

os.environ.setdefault("ORCH_PLANE_API_TOKEN", "test-token")
os.environ.setdefault("ORCH_GITEA_TOKEN", "test-token")

from src import plane_sync as PS  # noqa: E402


def test_notify_done_constants_unchanged():
    # Emoji + message body — pinned to lock the contract.
    assert PS.EMOJI_DONE == "✅"


def test_notify_done_posts_completed_comment(monkeypatch):
    """plane_sync.notify_done still posts the ✅ Task completed! comment
    authored by the deployer."""
    captured = {}

    def _spy_update(work_item_id, state, project_id=None):
        captured["update"] = (work_item_id, state, project_id)

    def _spy_add(work_item_id, body, project_id=None, author=None, **kw):
        captured.setdefault("comments", []).append(
            {"wid": work_item_id, "body": body, "author": author}
        )

    monkeypatch.setattr(PS, "update_issue_state", _spy_update)
    monkeypatch.setattr(PS, "add_comment", _spy_add)
    monkeypatch.setattr(PS, "_resolve_project_id", lambda wid, pid=None: "p-1")

    PS.notify_done("ET-016")

    assert captured["update"] == ("ET-016", "done", "p-1")
    assert len(captured["comments"]) == 1
    c = captured["comments"][0]
    assert c["wid"] == "ET-016"
    assert c["author"] == "deployer"
    # Body untouched: emoji + canonical Russian/English copy.
    assert "✅" in c["body"]
    assert "Task completed" in c["body"]


def test_set_issue_done_still_exported():
    """set_issue_done must remain importable from plane_sync — stage_engine
    line ~269 invokes it on deploy->done. ORCH-016 must not remove or rename it.
    """
    assert callable(getattr(PS, "set_issue_done", None))
    # And stage_engine still imports it at the module level (regression: ORCH-016
    # touches stage_engine to wire the new analyst comment helper).
    from src import stage_engine as SE
    assert getattr(SE, "set_issue_done", None) is PS.set_issue_done


def test_orch016_does_not_steal_done_signal(monkeypatch):
    """build_status_comment is just a comment — it must NOT call set_issue_done
    or notify_done as a side effect (that's stage_engine's job)."""
    from src import usage as U
    called = {"done": 0, "in_review": 0}

    def _fail(*a, **k):
        called["done"] += 1

    monkeypatch.setattr(PS, "set_issue_done", _fail)
    monkeypatch.setattr(PS, "notify_done", _fail)

    html = U.build_status_comment(
        "deployer", repo="enduro-trails", branch="b", work_item_id="ET-016",
        stage="deploy", duration_s=12,
    )
    assert "\U0001f680 Deployer" in html
    assert called["done"] == 0
