import unittest
from unittest import mock
import json

from flask import Flask
from oslo_context import context
from oslo_policy import policy as oslo_policy
from oslo_policy import _checks

from vmms.policy import rules
from vmms import api


class VMMSBaseTestCase(unittest.TestCase):
    """Base test case for VMMS tests."""
    pass


class VMMSTestCase(VMMSBaseTestCase):
    """Base test case for VMMS API tests."""

    def setUp(self):
        super(VMMSTestCase, self).setUp()
        
        # Create test Flask app
        self.app = api.app
        self.app.config['TESTING'] = True
        self.client = self.app.test_client()
        
        # Parse and register our rules manually for testing
        self.parsed_rules = {}
        for rule_def in rules.list_rules():
            self.parsed_rules[rule_def.name] = rule_def.check

    def _create_test_headers(self, roles=None, user_id='test_user', project_id='test_project'):
        """Create headers that simulate Keystone authentication."""
        roles = roles or []
        return {
            'X-Identity-Status': 'Confirmed',
            'X-User-Id': user_id,
            'X-Project-Id': project_id,
            'X-Roles': ','.join(roles)
        }

    def _create_unauthenticated_headers(self):
        """Create headers for unauthenticated requests."""
        return {
            'X-Identity-Status': 'Invalid'
        }


class VMMSPolicyTestCase(VMMSBaseTestCase):
    """Base test case for policy rule testing."""

    def setUp(self):
        super(VMMSPolicyTestCase, self).setUp()
        
        # Parse and register our rules manually for testing
        self.parsed_rules = {}
        for rule_def in rules.list_rules():
            self.parsed_rules[rule_def.name] = rule_def.check

    def _create_creds(self, roles=None, user_id='test_user', project_id='test_project'):
        """Create credentials dict for testing."""
        roles = roles or []
        return {
            'roles': roles,
            'user_id': user_id,
            'project_id': project_id
        }

    def _create_target(self, project_id='test_project', user_id='test_user'):
        """Create a target for policy enforcement."""
        return {
            'project_id': project_id,
            'user_id': user_id
        }

    def assertRuleIsEnforced(self, rule_name, creds, target, should_pass=True):
        """Assert that a rule is enforced correctly."""
        self.assertIn(rule_name, self.parsed_rules)
        rule = self.parsed_rules[rule_name]  # FIXED: was rule_def.name, should be rule_name
        
        # Create a minimal mock enforcer
        class MockEnforcer:
            def __init__(self, parsed_rules):
                self.rules = parsed_rules
        
        mock_enforcer = MockEnforcer(self.parsed_rules)
        
        result = _checks._check(rule, target, creds, mock_enforcer, rule_name)
        if should_pass:
            self.assertTrue(result, f"Rule {rule_name} should have passed")
        else:
            self.assertFalse(result, f"Rule {rule_name} should have failed")
