"""Run after installing requirements. These checks do not contact Lightspeed."""
import importlib.util
import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch


@unittest.skipUnless(importlib.util.find_spec("fastmcp"), "FastMCP is not installed; runtime checks pending")
class RuntimeTests(unittest.TestCase):
    def test_metadata_and_unauthenticated_denial(self):
        from server import create_server
        from starlette.testclient import TestClient
        with tempfile.TemporaryDirectory() as folder:
            config = Path(folder) / "private-config.json"
            config.write_text(json.dumps({"public_url": "https://reporting.example.com", "account_id": "42",
                "client_id": "fixture-id", "client_secret": "fixture-secret", "signing_key": "a" * 48,
                "cursor_key": "b" * 48, "state_dir": str(Path(folder) / "state"),
                "chatgpt_redirect_uris": ["https://chatgpt.com/connector_platform_oauth_redirect"]}))
            config.chmod(0o600)
            with patch.dict(os.environ, {"PAWBARN_CONFIG": str(config)}):
                mcp, _ = create_server()
                with TestClient(mcp.http_app(stateless_http=True)) as client:
                    metadata = client.get("/.well-known/oauth-authorization-server")
                    self.assertEqual(metadata.status_code, 200)
                    self.assertIn("S256", metadata.json()["code_challenge_methods_supported"])
                    self.assertEqual(set(metadata.json()["scopes_supported"]),
                                     {"employee:inventory_read", "employee:register_read"})
                    denied = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
                                         headers={"Accept": "application/json, text/event-stream"})
                    self.assertEqual(denied.status_code, 401)
                    self.assertIn("resource_metadata", denied.headers["www-authenticate"])
                    rejected = client.post("/register", json={"client_name": "bad-redirect-test",
                        "redirect_uris": ["https://evil.example/callback"],
                        "grant_types": ["authorization_code", "refresh_token"],
                        "response_types": ["code"], "token_endpoint_auth_method": "none"})
                    self.assertGreaterEqual(rejected.status_code, 400)


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