import pytest
from armorer.installers.dynamic import DynamicInstaller, _extract_json
from armorer.profiles import RiskProfile, NetworkPolicy, FilesystemPolicy

def get_test_profile():
    return RiskProfile(
        name="test",
        description="test",
        network_policy=NetworkPolicy.OPEN,
        filesystem_policy=FilesystemPolicy.ISOLATED,
        human_in_loop=False
    )

def test_normalize_compose_yaml():
    installer = DynamicInstaller("test", get_test_profile(), [])
    
    legacy_yaml = """
services:
  app:
    image: alpine
    env_file:
      - path: .env
        required: false
      - .env.prod
"""
    normalized = installer._normalize_compose_yaml(legacy_yaml)
    assert "- .env" in normalized
    assert "- .env.prod" in normalized
    assert "path:" not in normalized
    assert "required:" not in normalized

def test_ensure_env_files_exist(tmp_path):
    installer = DynamicInstaller("test", get_test_profile(), [])
    installer.install_path = tmp_path
    installer._compose_dir = tmp_path  # Force it to use tmp_path
    
    config = """
services:
  app:
    env_file:
      - .env.missing
"""
    installer._ensure_env_files_exist(config)
    assert (tmp_path / ".env.missing").exists()

def test_extract_json_outermost_fallback():
    messy_text = """
Some random rambling before the JSON...
{
  "key": "value",
  "nested": { "a": 1 }
}
And some truncation or garbage at the end...
"""
    data = _extract_json(messy_text)
    assert data is not None
    assert data["key"] == "value"
    assert data["nested"]["a"] == 1
