"""Keep a real timed-out Pod child's sanitized evidence after its private log closes."""
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch

import native_dependency_guard as guard
import native_pods_retry


@unittest.skipUnless(os.name == "posix", "owned POSIX process groups")
class TimeoutTests(unittest.TestCase):
    def test_timeout_retains_bounded_diagnostic_without_retrying_or_leaving_child(self):
        with tempfile.TemporaryDirectory(prefix="native-pods-timeout-") as folder:
            root = Path(folder)
            script = ('import os,time; from pathlib import Path; '
                      'Path("attempts").open("a").write("attempt\\n"); '
                      'print("x" * 20000, flush=True); '
                      'print("Downloading dependencies\\nRead timed out\\nPRIVATE_SENTINEL", flush=True); '
                      'Path("child").write_text(str(os.getpid())); time.sleep(30)')
            with tempfile.TemporaryFile() as log, patch.dict(os.environ, {"TEST_TOKEN": "PRIVATE_SENTINEL"}):
                with self.assertRaisesRegex(guard.Refused, "native_pods_operation_interrupted") as caught:
                    native_pods_retry.install([sys.executable, "-c", script], root, log, {}, timeout=1)
            self.assertEqual((root / "attempts").read_text(), "attempt\n")
            with self.assertRaises(ProcessLookupError):
                os.kill(int((root / "child").read_text()), 0)
            body = getattr(caught.exception, "diagnostic", "")
            self.assertIn("Downloading dependencies", body)
            self.assertIn("Read timed out", body)
            self.assertNotIn("PRIVATE_SENTINEL", body)
            self.assertLessEqual(len(body), 4000)
            self.assertLessEqual(len(body.splitlines()), 30)
