"""Actual retained-leader cleanup, including a stubborn surviving descendant and unrelated sibling."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest

import native_pods_process as process


class ProcessTests(unittest.TestCase):
    def test_exited_leader_does_not_leave_its_term_resistant_child(self):
        with tempfile.TemporaryDirectory(prefix="app-robot-native-process-") as temporary:
            root = Path(temporary)
            worker = root / "worker.py"
            worker.write_text('import os,signal,time\nfrom pathlib import Path\n'
                              'signal.signal(signal.SIGTERM, signal.SIG_IGN)\n'
                              'Path("pid").write_text(str(os.getpid()))\ntime.sleep(30)\n')
            leader = ('import subprocess,sys,time\nfrom pathlib import Path\n'
                      'subprocess.Popen([sys.executable,"worker.py"])\n'
                      'while not Path("pid").exists(): time.sleep(.01)\nraise SystemExit(7)\n')
            sibling = subprocess.Popen([sys.executable, "-c", "import time;time.sleep(30)"], start_new_session=True)
            try:
                with tempfile.TemporaryFile() as log:
                    code = process.command([sys.executable, "-c", leader], root, log, timeout=5)
                self.assertEqual(code, 7)
                self.assertIsNone(sibling.poll())
                child_pid = int((root / "pid").read_text())
                found = subprocess.run(["ps", "-p", str(child_pid), "-o", "stat="], capture_output=True, text=True)
                self.assertTrue(found.returncode or found.stdout.strip().startswith("Z"))
            finally:
                sibling.terminate()
                sibling.wait(timeout=5)

    def test_timeout_has_no_success_verdict(self):
        with tempfile.TemporaryDirectory(prefix="app-robot-native-timeout-") as temporary:
            with tempfile.TemporaryFile() as log:
                with self.assertRaises(process.Interrupted):
                    process.command([sys.executable, "-c", "import time;time.sleep(30)"],
                                    Path(temporary), log, timeout=0.05)
