"""Tests for the license gating module."""

from unittest.mock import patch

from finagent_pro.license import check_license, require_license


class TestCheckLicense:
    @patch("finagent_pro.license.verify_license")
    def test_no_license_key(self, mock_verify, monkeypatch):
        monkeypatch.delenv("MCP_LICENSE_KEY", raising=False)
        monkeypatch.delenv("FINAGENT_LICENSE_KEY", raising=False)
        mock_verify.return_value = {"valid": False, "reason": "missing_key"}
        result = check_license()
        assert result["valid"] is False
        mock_verify.assert_called_once_with(slug="finagent-pro")

    @patch("finagent_pro.license.verify_license")
    def test_valid_license(self, mock_verify, monkeypatch):
        monkeypatch.setenv("MCP_LICENSE_KEY", "mcp_live_abc123")
        mock_verify.return_value = {"valid": True}
        result = check_license()
        assert result["valid"] is True

    @patch("finagent_pro.license.verify_license")
    def test_legacy_env_var_fallback(self, mock_verify, monkeypatch):
        monkeypatch.delenv("MCP_LICENSE_KEY", raising=False)
        monkeypatch.setenv("FINAGENT_LICENSE_KEY", "mcp_live_legacy123")
        mock_verify.return_value = {"valid": True}
        result = check_license()
        assert result["valid"] is True

    @patch("finagent_pro.license.verify_license")
    def test_expired_license(self, mock_verify, monkeypatch):
        monkeypatch.setenv("MCP_LICENSE_KEY", "mcp_live_expired")
        mock_verify.return_value = {"valid": False, "reason": "expired"}
        result = check_license()
        assert result["valid"] is False
        assert result["reason"] == "expired"


class TestRequireLicense:
    @patch("finagent_pro.license.verify_license")
    def test_require_returns_error_without_key(self, mock_verify, monkeypatch):
        monkeypatch.delenv("MCP_LICENSE_KEY", raising=False)
        monkeypatch.delenv("FINAGENT_LICENSE_KEY", raising=False)
        mock_verify.return_value = {"valid": False, "reason": "missing_key"}
        result = require_license("sec_filings")
        assert result is not None
        assert "premium_required" in result
        assert "missing_key" in result

    @patch("finagent_pro.license.verify_license")
    def test_require_returns_none_with_valid_key(self, mock_verify, monkeypatch):
        monkeypatch.setenv("MCP_LICENSE_KEY", "mcp_live_valid123")
        mock_verify.return_value = {"valid": True}
        result = require_license("sec_filings")
        assert result is None

    @patch("finagent_pro.license.verify_license")
    def test_require_returns_error_on_revoked(self, mock_verify, monkeypatch):
        monkeypatch.setenv("MCP_LICENSE_KEY", "mcp_live_revoked")
        mock_verify.return_value = {"valid": False, "reason": "revoked"}
        result = require_license("stock_screener")
        assert result is not None
        assert "premium_required" in result
        assert "revoked" in result
