#!/usr/bin/env python3
from __future__ import annotations

import importlib.util
import os
import tempfile
import unittest
from contextlib import redirect_stderr
from io import StringIO
from pathlib import Path
from unittest.mock import patch

_HELPER = Path(__file__).resolve().parents[1] / "bin" / "_agent-session-reap-close.py"
_SPEC = importlib.util.spec_from_file_location("agent_session_reap_close", _HELPER)
helper = importlib.util.module_from_spec(_SPEC)
assert _SPEC.loader is not None
_SPEC.loader.exec_module(helper)


class OrphanScopeBatchTests(unittest.TestCase):
    @staticmethod
    def units(count: int) -> list[str]:
        return [
            f"tmux-spawn-00000000-0000-4000-8000-{index:012x}.scope"
            for index in range(count)
        ]

    def test_batch_is_bounded_and_cursor_rotates(self) -> None:
        units = self.units(helper.ORPHAN_SCOPE_LIMIT + 8)
        with tempfile.TemporaryDirectory() as root, patch.dict(
            os.environ, {"AGENT_SESSIONS_DIR": root}
        ):
            first = helper.bounded_orphan_scopes(units)
            second = helper.bounded_orphan_scopes(units)
        self.assertEqual(len(first), helper.ORPHAN_SCOPE_LIMIT)
        self.assertEqual(second[:8], units[helper.ORPHAN_SCOPE_LIMIT:])
        self.assertEqual(second[8:], units[: helper.ORPHAN_SCOPE_LIMIT - 8])

    def test_cursor_write_failure_does_not_drop_batch(self) -> None:
        units = self.units(3)
        with tempfile.TemporaryDirectory() as tmp:
            root_file = os.path.join(tmp, "not-a-directory")
            Path(root_file).write_text("occupied\n", encoding="utf-8")
            with patch.dict(os.environ, {"AGENT_SESSIONS_DIR": root_file}), redirect_stderr(StringIO()):
                selected = helper.bounded_orphan_scopes(units)
        self.assertEqual(selected, units)


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