import importlib.util
import json
import os
import tempfile
import unittest

PATH = os.path.join(os.path.dirname(__file__), "repo-authorization-guard.py")
SPEC = importlib.util.spec_from_file_location("repo_auth_guard", PATH)
MOD = importlib.util.module_from_spec(SPEC); SPEC.loader.exec_module(MOD)

class RepoAuthorizationGuardTests(unittest.TestCase):
    def test_missing_expired_and_wrong_target_grants_fail_closed(self):
        with tempfile.TemporaryDirectory() as directory:
            old = MOD.GRANT_DIR; MOD.GRANT_DIR = directory
            try:
                self.assertEqual(MOD.check("bingshuo/fifth-domain", 100)[1], "repo_push_approval_required")
                file = os.path.join(directory, "bingshuo__fifth-domain.json")
                with open(file,"w") as handle: json.dump({"repo":"bingshuo/fifth-domain","target":"JD-FD-PRIMARY","expires_at":99}, handle)
                self.assertEqual(MOD.check("bingshuo/fifth-domain", 100)[1], "repo_push_grant_expired")
                with open(file,"w") as handle: json.dump({"repo":"bingshuo/fifth-domain","target":"OTHER","expires_at":200}, handle)
                self.assertEqual(MOD.check("bingshuo/fifth-domain", 100)[1], "repo_push_grant_binding_mismatch")
            finally: MOD.GRANT_DIR = old
    def test_current_bound_grant_passes(self):
        with tempfile.TemporaryDirectory() as directory:
            old = MOD.GRANT_DIR; MOD.GRANT_DIR = directory
            try:
                with open(os.path.join(directory,"bingshuo__fifth-domain.json"),"w") as handle: json.dump({"repo":"bingshuo/fifth-domain","target":"JD-FD-PRIMARY","expires_at":200}, handle)
                self.assertEqual(MOD.check("/var/lib/gitea/repositories/bingshuo/fifth-domain.git",100),(True,"ok"))
                self.assertEqual(MOD.check("fifth-domain",100),(True,"ok"))
            finally: MOD.GRANT_DIR = old

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