"""Tests for StackSet manager."""

from unittest.mock import MagicMock, patch

import pytest

from ai_org.core.stackset_manager import StackSetManager


@pytest.fixture
def mock_cfn():
    """Create a StackSetManager with mocked CloudFormation client."""
    with patch.object(StackSetManager, "__init__", lambda self, **kw: None):
        manager = StackSetManager.__new__(StackSetManager)
        manager.aws = MagicMock()
        manager.aws.region = "us-east-1"
        manager.cfn_client = MagicMock()
        return manager


@pytest.mark.unit
class TestStackSetManager:
    def test_init(self):
        with patch("ai_org.core.aws_client.AWSClient"):
            manager = StackSetManager(profile=None, region="us-east-1")
            assert manager is not None

    def test_list_all_stacksets(self, mock_cfn):
        paginator = MagicMock()
        paginator.paginate.return_value = [
            {
                "Summaries": [
                    {"StackSetName": "org-pipeline-bootstrap", "Status": "ACTIVE"},
                    {"StackSetName": "org-github-oidc", "Status": "ACTIVE"},
                ]
            }
        ]
        mock_cfn.cfn_client.get_paginator.return_value = paginator
        result = mock_cfn._list_all_stacksets()
        assert "org-pipeline-bootstrap" in result
        assert "org-github-oidc" in result

    def test_get_deployment_status_specific_stackset(self, mock_cfn):
        mock_cfn.cfn_client.describe_stack_instance.return_value = {
            "StackInstance": {
                "StackSetId": "org-test",
                "Account": "123456789012",
                "Region": "us-east-1",
                "Status": "CURRENT",
                "StackInstanceStatus": {"DetailedStatus": "SUCCEEDED"},
            }
        }
        result = mock_cfn.get_deployment_status("123456789012", stackset_name="org-test")
        assert len(result) >= 1

    def test_list_stacksets(self, mock_cfn):
        paginator = MagicMock()
        paginator.paginate.return_value = [
            {
                "Summaries": [
                    {
                        "StackSetName": "org-pipeline-bootstrap",
                        "Status": "ACTIVE",
                        "Description": "Pipeline bootstrap",
                        "PermissionModel": "SERVICE_MANAGED",
                    },
                ]
            }
        ]
        mock_cfn.cfn_client.get_paginator.return_value = paginator
        mock_cfn.cfn_client.describe_stack_set.return_value = {
            "StackSet": {"AutoDeployment": {"Enabled": False}}
        }
        result = mock_cfn.list_stacksets()
        assert len(result) >= 1

    def test_get_deployment_status_handles_not_found(self, mock_cfn):
        from botocore.exceptions import ClientError

        mock_cfn.cfn_client.describe_stack_instance.side_effect = ClientError(
            {"Error": {"Code": "StackInstanceNotFoundException", "Message": "not found"}},
            "DescribeStackInstance",
        )
        mock_cfn.cfn_client.list_stack_sets.return_value = {
            "Summaries": [{"StackSetName": "org-test", "Status": "ACTIVE"}]
        }
        result = mock_cfn.get_deployment_status("123456789012", stackset_name="org-test")
        # Should handle gracefully, returning status with NOT_FOUND or empty
        assert isinstance(result, list)
