from __future__ import annotations

import importlib.util
import unittest
from datetime import UTC, datetime
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location(
    "audit_core_whitehat_e2_credentials",
    ROOT / "scripts" / "audit-core-whitehat-e2-credentials.py",
)
assert SPEC and SPEC.loader
module = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(module)


class CredentialProcedureTests(unittest.TestCase):
    def test_add_and_remove_only_named_temporary_identities(self) -> None:
        original = [{"name": "user-engine", "tokens": ["existing"]}]
        updated = module.add_temporary_identities(original, {"token-a": "a", "token-b": "b"})
        self.assertEqual(3, len(updated))
        cleaned, removed = module.remove_temporary_identities(updated)
        self.assertEqual(2, removed)
        self.assertEqual(original, cleaned)

    def test_temporary_identities_are_exactly_scoped_and_expiring(self) -> None:
        updated = module.add_temporary_identities(
            [{"name": "existing"}], {"token-a": "a", "token-b": "b"}
        )
        temporary = updated[1:]
        self.assertEqual({"whitehat-security"}, {item["sources"][0] for item in temporary})
        self.assertTrue(all(item["may_read"] and item["may_write"] for item in temporary))
        self.assertTrue(all(item["expires_at"] == module.EXPIRES_TEXT for item in temporary))
        self.assertEqual(2, len({item["tenants"][0] for item in temporary}))

    def test_projection_window_is_fail_closed(self) -> None:
        self.assertEqual("before-window", module.time_state(datetime(2026, 8, 22, 17, 59, tzinfo=UTC)))
        self.assertEqual("projection-window-open", module.time_state(datetime(2026, 8, 22, 18, 1, tzinfo=UTC)))
        self.assertEqual("projection-cutoff-passed", module.time_state(datetime(2026, 8, 22, 18, 4, tzinfo=UTC)))

    def test_manifest_projects_only_two_exact_keys(self) -> None:
        manifest = module.projection_manifest()
        self.assertEqual(2, manifest.count("secretKey: token-"))
        self.assertNotIn("workloads/audit-core/senders", manifest)
        self.assertIn("conditions:\n    - namespaces:\n        - whitehat", manifest)


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