"""Integration tests for AWS infrastructure components."""

import os

import boto3
import pytest
from botocore.exceptions import ClientError
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

AWS_REGION = os.getenv("AWS_REGION", "us-east-1")

# Stack name provided by pipeline or environment
# This removes coupling between pytest and git/infrastructure state
STACK_NAME = os.getenv("STACK_NAME", "augint-library-testing")


@pytest.mark.integration
@pytest.mark.ci_only
@pytest.mark.filterwarnings("ignore::DeprecationWarning:botocore.auth")
def test_infra_stack_exists() -> None:
    """Test that the AWS infrastructure stack exists and is in valid state."""
    stack_name = STACK_NAME
    cfn = boto3.client("cloudformation", region_name=AWS_REGION)

    try:
        response = cfn.describe_stacks(StackName=stack_name)
        stacks = response.get("Stacks", [])
        assert len(stacks) == 1, f"Expected 1 stack, found {len(stacks)}"
        stack_status = stacks[0]["StackStatus"]
        print(f"Stack {stack_name} status: {stack_status}")
        assert stack_status in [
            "CREATE_COMPLETE",
            "UPDATE_COMPLETE",
            "UPDATE_ROLLBACK_COMPLETE",
        ], f"Unexpected stack status: {stack_status}"

    except ClientError as e:
        print(f"CloudFormation error: {e}")
        raise AssertionError(f"Stack {stack_name} does not exist or cannot be described")
