#!/usr/bin/env python3
"""Buildbox disk admission helpers (stdlib unittest — no pytest required)."""

from __future__ import annotations

import os
import sys
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))

from disk_admission import (  # noqa: E402
    RED_FLOOR_BYTES,
    admit_new_work,
    resolve_floor_bytes,
    unique_filesystem_probe_paths,
)


class DiskAdmissionTest(unittest.TestCase):
    def test_override_cannot_lower_floor(self) -> None:
        env = os.environ.copy()
        env["BUILDBOX_DISK_MIN_FREE_BYTES"] = "1"
        self.assertEqual(resolve_floor_bytes(env), RED_FLOOR_BYTES)

    def test_nonexistent_destination_probes_nearest_parent(self) -> None:
        with tempfile_dir() as tmp:
            parent = tmp / "parent"
            parent.mkdir()
            nested = parent / "child" / "sessions"
            probe, ok = unique_filesystem_probe_paths([str(nested)])
            self.assertTrue(ok)
            self.assertEqual(probe, [str(parent.resolve())])

    def test_multiple_filesystems_all_must_meet_floor(self) -> None:
        import disk_admission as mod

        readings = {"/fs-a": RED_FLOOR_BYTES + 1, "/fs-b": RED_FLOOR_BYTES - 1}
        original = mod.unique_filesystem_probe_paths
        mod.unique_filesystem_probe_paths = lambda _dests: (list(readings), True)
        try:
            verdict = admit_new_work(
                destinations=["/ignored-a", "/ignored-b"],
                free_bytes_fn=lambda path: readings[path],
            )
        finally:
            mod.unique_filesystem_probe_paths = original
        self.assertFalse(verdict.admit)
        self.assertEqual(verdict.reason, "below-floor")

    def test_unknown_probe_refuses(self) -> None:
        import disk_admission as mod

        original = mod.unique_filesystem_probe_paths
        mod.unique_filesystem_probe_paths = lambda _dests: ([], False)
        try:
            verdict = admit_new_work(destinations=["/missing/leaf"])
        finally:
            mod.unique_filesystem_probe_paths = original
        self.assertFalse(verdict.admit)
        self.assertEqual(verdict.reason, "unknown")


class tempfile_dir:
    def __enter__(self) -> Path:
        import tempfile

        self._path = Path(tempfile.mkdtemp())
        return self._path

    def __exit__(self, *_args: object) -> None:
        import shutil

        shutil.rmtree(self._path, ignore_errors=True)


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