"""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._orig_resolved_task = srv._preflight_resolved_task
        self._orig_resolved_role = srv._preflight_resolved_role
        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
        # Preflight task/role are module-level; restore so test order cannot
        # leak a resolved task into sibling cases.
        srv._preflight_resolved_task = self._orig_resolved_task
        srv._preflight_resolved_role = self._orig_resolved_role
        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_non_create_issue_still_blocked_on_control_checkout(
        self, _git, _get_all, _role, _ns, _prof, _auth
    ):
        """Author mutations other than create_issue keep the branches-only rule.

        #749/#750 sanctioned ``create_issue`` from a clean control checkout, and
        #757 made the #604 anti-stomp guard honour that same decision — so
        ``create_issue`` is no longer a valid probe for this boundary. This case
        previously asserted create_issue stayed blocked, which only held because
        the bootstrap-blind #604 guard was overriding #750; that is precisely
        the defect #757 fixed. ``lock_issue`` is issue-backed and post-ownership,
        so it still requires a ``branches/`` worktree.
        """
        srv._preflight_resolved_role = "author"
        srv._preflight_resolved_task = "lock_issue"
        with patch.object(srv, "PROJECT_ROOT", CONTROL_CHECKOUT_ROOT):
            try:
                srv.verify_preflight_purity(remote="prgs", task="lock_issue")
            except RuntimeError as exc:
                self.assertIn("control checkout", str(exc).lower())
            else:
                self.fail("lock_issue must stay blocked on the control checkout")


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