"""Checks for tenant-aware OpenAI credential resolution."""
from __future__ import annotations
import sys, unittest
from pathlib import Path
from unittest.mock import patch

PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT))
loaded_platform = sys.modules.get("platform")
if loaded_platform is not None and not hasattr(loaded_platform, "__path__"):
    del sys.modules["platform"]

from bridge_platform.ai import openai_client


class AiClientChecks(unittest.TestCase):
    @patch.dict("os.environ", {}, clear=True)
    @patch("platform.ai.openai_client._read_key_file")
    def test_tenant_app_key_has_priority_over_development_key(self, read):
        def value(path):
            text = str(path)
            if text.endswith("tenants/absolutems/wp_invoices.key"): return "tenant-key"
            if text.endswith("dev.key"): return "development-key"
            return None
        read.side_effect = value
        key = openai_client._resolve_api_key("wp_invoices", tenant_id="absolutems")
        self.assertEqual("tenant-key", key)

    @patch.dict("os.environ", {}, clear=True)
    @patch("platform.ai.openai_client._read_key_file")
    def test_development_key_remains_fallback(self, read):
        read.side_effect = lambda path: "development-key" if str(path).endswith("dev.key") else None
        self.assertEqual("development-key", openai_client._resolve_api_key("wp_invoices"))

    def test_visual_request_reserves_conservative_capacity(self):
        self.assertEqual(50000, openai_client._estimated_capacity({"file_bytes": b"image"}))
        self.assertEqual(5000, openai_client._estimated_capacity({}))


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