import os
import json

from azure_policy_engine import AzurePolicyEngine


def test_file_backend_roundtrip(tmp_path):
    base = tmp_path / "pols"
    base.mkdir()
    engine = AzurePolicyEngine(backend="file", policy_dir=str(base))
    sample = {"name": "testpolicy", "properties": {"displayName": "Test"}}
    engine.deploy_policy("testpolicy", sample)
    got = engine.get_policy("testpolicy")
    assert got["name"] == "testpolicy" or got.get("properties", {}).get("displayName") == "Test"
    listed = engine.list_policies()
    assert any(p.get("name") == "testpolicy" or os.path.basename(p.get("file", "")).startswith("testpolicy") for p in listed)


def test_assignments_and_initiatives(tmp_path):
    base = tmp_path / "pols"
    base.mkdir()
    engine = AzurePolicyEngine(backend="file", policy_dir=str(base))
    assign = {"name": "assign1", "properties": {"displayName": "Assign 1", "scope": "/subscriptions/0000"}}
    assign_path = os.path.join(engine.assignments_dir, "assign1.json")
    with open(assign_path, "w", encoding="utf-8") as f:
        json.dump(assign, f)
    assigns = engine.list_assignments()
    assert any(a.get("name") == "assign1" or os.path.basename(a.get("file", "")).startswith("assign1") for a in assigns)

    init = {"name": "init1", "properties": {"displayName": "Init 1", "policyDefinitions": []}}
    init_path = os.path.join(engine.initiatives_dir, "init1.json")
    with open(init_path, "w", encoding="utf-8") as f:
        json.dump(init, f)
    inits = engine.list_initiatives()
    assert any(i.get("name") == "init1" or os.path.basename(i.get("file", "")).startswith("init1") for i in inits)

