import os
import pytest

from py_azpe import AzurePolicyEngine


@pytest.mark.skipif(
    os.environ.get("AZPE_RUN_AZURE_INTEGRATION", "false").lower() != "true",
    reason="Integration tests disabled by default",
)
def test_deploy_policy_and_assignment_live():
    # This test runs only when AZPE_RUN_AZURE_INTEGRATION=true and valid credentials are available.
    subscription = os.environ.get("AZURE_SUBSCRIPTION_ID")
    assert subscription, "AZURE_SUBSCRIPTION_ID required for integration test"

    cred = None
    try:
        from azure.identity import DefaultAzureCredential

        cred = DefaultAzureCredential()
    except Exception:
        pytest.skip("azure-identity not available or configured")

    engine = AzurePolicyEngine(
        backend="sdk", subscription_id=subscription, credential=cred
    )

    # create a policy definition (name is arbitrary)
    pol = {
        "properties": {
            "displayName": "IT test policy",
            "policyRule": {
                "if": {"field": "location", "equals": ""},
                "then": {"effect": "audit"},
            },
        }
    }
    res = engine.deploy_policy("it_test_policy", pol)
    assert isinstance(res, dict)

    # prepare an assignment payload as a dry-run
    assign = {
        "properties": {
            "displayName": "IT test assign",
            "policyDefinitionId": res.get("id") or res.get("name"),
        }
    }
    payload = engine.prepare_assignment_payload(
        "it_test_assign", assign, scope=f"/subscriptions/{subscription}"
    )
    assert payload["name"] == "it_test_assign"
