"""Reconciler close_pr must not require author branches/ worktree (#468)."""
import os
import sys
import unittest
from pathlib import Path
from unittest.mock import patch

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import gitea_mcp_server as srv

FAKE_AUTH = "token test"
current_file_path = Path(__file__).resolve()
if "branches" in current_file_path.parts:
    CONTROL_CHECKOUT_ROOT = str(current_file_path.parents[3])
else:
    CONTROL_CHECKOUT_ROOT = str(current_file_path.parents[1])
RECONCILER_PROFILE = {
    "profile_name": "prgs-reconciler",
    "allowed_operations": ["gitea.read", "gitea.pr.close", "gitea.pr.comment"],
    "forbidden_operations": [
        "gitea.pr.approve",
        "gitea.pr.merge",
        "gitea.pr.review",
        "gitea.pr.create",
        "gitea.branch.push",
        "gitea.repo.commit",
    ],
    "audit_label": "prgs-reconciler",
}


class TestReconcilerCloseWorkspaceGuard(unittest.TestCase):
    def setUp(self):
        srv._preflight_whoami_called = True
        srv._preflight_capability_called = True
        srv._preflight_whoami_violation = False
        srv._preflight_capability_violation = False
        self._orig_in_test = srv._preflight_in_test_mode
        srv._preflight_in_test_mode = lambda: False
        self._env_patch = patch.dict(os.environ, {"GITEA_MCP_DISABLE_PARITY_GATE": "1"}, clear=False)
        self._env_patch.start()

    def tearDown(self):
        srv._preflight_in_test_mode = self._orig_in_test
        self._env_patch.stop()

    @patch("gitea_mcp_server._auth", return_value=FAKE_AUTH)
    @patch("gitea_mcp_server._namespace_mutation_block", return_value=None)
    @patch("gitea_mcp_server.get_profile", return_value=RECONCILER_PROFILE)
    @patch("gitea_mcp_server.api_request")
    def test_reconciler_close_pr_from_control_checkout_succeeds(
        self, mock_api, _profile, _ns, _auth
    ):
        srv._preflight_resolved_role = "reconciler"
        mock_api.return_value = {
            "number": 414,
            "title": "old",
            "body": "",
            "state": "closed",
            "html_url": "https://gitea.example.com/pulls/414",
        }
        with patch.object(srv, "PROJECT_ROOT", CONTROL_CHECKOUT_ROOT):
            with patch.dict(os.environ, {}, clear=False):
                os.environ.pop("GITEA_AUTHOR_WORKTREE", None)
                os.environ.pop("GITEA_ACTIVE_WORKTREE", None)
                result = srv.gitea_edit_pr(414, state="closed", remote="prgs")
        self.assertTrue(result["success"])
        self.assertEqual(result["state"], "closed")
        mock_api.assert_called_once()

    @patch("gitea_mcp_server._auth", return_value=FAKE_AUTH)
    @patch("gitea_mcp_server._profile_permission_block", return_value=None)
    @patch("gitea_mcp_server._namespace_mutation_block", return_value=None)
    @patch(
        "gitea_mcp_server.role_session_router.check_author_mutation_after_reviewer_stop",
        return_value=(True, []),
    )
    @patch("gitea_mcp_server.api_get_all", return_value=[])
    @patch(
        "gitea_mcp_server.issue_lock_worktree.read_worktree_git_state",
        return_value={"current_branch": "master"},
    )
    def test_author_create_issue_still_blocked_on_control_checkout(
        self, _git, _get_all, _role, _ns, _prof, _auth
    ):
        srv._preflight_resolved_role = "author"
        with patch.object(srv, "PROJECT_ROOT", CONTROL_CHECKOUT_ROOT):
            try:
                res = srv.gitea_create_issue(title="Test", body="body")
            except RuntimeError as exc:
                self.assertIn("stable control checkout", str(exc))
            else:
                # #683 typed blocker at mutation entrypoint
                self.assertFalse(res.get("success"))
                blob = " ".join(res.get("reasons") or []) + str(
                    res.get("blocker_kind") or ""
                )
                self.assertTrue(
                    "stable control checkout" in blob
                    or "missing_issue_worktree" in blob
                    or "control checkout" in blob.lower()
                )


if __name__ == "__main__":
    unittest.main()