import os
import subprocess
import tempfile
import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
REFRESH = ROOT / "semantic_index" / "refresh.sh"


class SemanticIndexShellWrapperTest(unittest.TestCase):
    def test_refresh_wrapper_is_self_locating_when_called_from_another_directory(self):
        with tempfile.TemporaryDirectory() as tmp:
            tmp_path = Path(tmp)
            env = {
                **os.environ,
                "PYTHON": "/bin/echo",
                "SEMANTIC_INDEX_PROJECT_LIMITS": "customer-service=5",
                "SEMANTIC_INDEX_LOG_DIR": str(tmp_path / "logs"),
                "SEMANTIC_INDEX_STATE_PATH": str(tmp_path / "state" / "refresh_state.json"),
            }

            result = subprocess.run(
                [str(REFRESH)],
                cwd=tmp,
                env=env,
                text=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                check=False,
            )

        self.assertEqual(0, result.returncode, result.stderr)
        self.assertIn("-m semantic_index --refresh-redmine-projects", result.stdout)
        self.assertIn("--project-limits customer-service=5", result.stdout)
        self.assertIn("log_file=", result.stdout)


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