import subprocess
import tempfile
import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
INSTALLER = ROOT / "deploy" / "semantic-index" / "install.sh"


class SemanticIndexInstallerTest(unittest.TestCase):
    def run_installer(self, *args, env=None):
        return subprocess.run(
            [str(INSTALLER), *args],
            cwd=ROOT,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=False,
            env=env,
        )

    def test_default_mode_is_dry_run(self):
        result = self.run_installer()

        self.assertEqual(0, result.returncode, result.stderr)
        self.assertIn("mode=dry-run", result.stdout)
        self.assertIn("would run: sudo mkdir -p /opt/semantic-index", result.stdout)
        self.assertIn("would run: sudo rsync", result.stdout)
        self.assertNotIn("Semantic Index installed, but deployment is not complete.", result.stdout)

    def test_apply_prints_manual_next_step_warning(self):
        with tempfile.TemporaryDirectory() as tmp:
            tmp_path = Path(tmp)
            env = {
                "PATH": "/usr/bin:/bin",
                "SEMANTIC_INDEX_INSTALL_DIR": str(tmp_path / "opt" / "semantic-index"),
                "SEMANTIC_INDEX_ENV_FILE": str(tmp_path / "etc" / "semantic-index.env"),
                "SEMANTIC_INDEX_STATE_DIR": str(tmp_path / "var" / "lib" / "semantic-index"),
                "SEMANTIC_INDEX_LOG_DIR": str(tmp_path / "var" / "log" / "semantic-index"),
                "SEMANTIC_INDEX_SYSTEMD_DIR": str(tmp_path / "etc" / "systemd" / "system"),
            }
            result = self.run_installer("--apply", "--no-system", "--skip-deps", env=env)

        self.assertEqual(0, result.returncode, result.stderr)
        self.assertIn("Semantic Index installed, but deployment is not complete.", result.stdout)
        self.assertIn("The refresh timer was NOT enabled automatically.", result.stdout)
        self.assertIn("Do not use --force-rebuild", result.stdout)

    def test_invalid_argument_fails_with_usage(self):
        result = self.run_installer("--force-rebuild")

        self.assertEqual(2, result.returncode)
        self.assertIn("Usage:", result.stderr)


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