"""REQ-103: contract interpolation (variable expansion from environment
onboarding). ${env.<field>} + ${contract.<field>} tokens are expanded by
the resolver post-schema-validation, pre-IR-resolution. Unknown tokens
raise ValueError (fail loud, D-081).
"""
import sys
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from core.contract_resolver import _expand_vars, resolve


def test_expand_env_region():
    ctx = {"env": {"region": "us-east-1"}, "contract": {}}
    assert _expand_vars("${env.region}", ctx) == "us-east-1"


def test_expand_env_dotted_path():
    ctx = {"env": {"state_backend": {"bucket": "acdl-dev-state"}}, "contract": {}}
    assert _expand_vars("${env.state_backend.bucket}", ctx) == "acdl-dev-state"


def test_expand_contract_id():
    ctx = {"env": {}, "contract": {"id": "assets"}}
    assert _expand_vars("${contract.id}", ctx) == "assets"


def test_expand_contract_dotted_path():
    ctx = {"env": {}, "contract": {"infrastructure": {"s3": {"inputs": {"bucket_name": "acdl-x"}}}}}
    assert _expand_vars("${contract.infrastructure.s3.inputs.bucket_name}", ctx) == "acdl-x"


def test_expand_nested_in_string():
    ctx = {"env": {"environment": "dev", "account_id": "000000000000", "region": "us-east-1"},
           "contract": {"id": "assets"}}
    result = _expand_vars("acdl-${env.environment}-${contract.id}-${env.account_id}-${env.region}", ctx)
    assert result == "acdl-dev-assets-000000000000-us-east-1"


def test_expand_recursive_in_dict():
    ctx = {"env": {"environment": "dev"}, "contract": {}}
    result = _expand_vars({"DB_URL": "acdl-${env.environment}-db", "port": 5432}, ctx)
    assert result == {"DB_URL": "acdl-dev-db", "port": 5432}


def test_expand_recursive_in_list():
    ctx = {"env": {"region": "us-east-1"}, "contract": {}}
    result = _expand_vars(["${env.region}", "literal"], ctx)
    assert result == ["us-east-1", "literal"]


def test_expand_recursive_in_nested_map():
    """D-087: nested map values expand recursively."""
    ctx = {"env": {"environment": "qa"}, "contract": {}}
    result = _expand_vars({"env": {"DB_URL": "acdl-${env.environment}-db"}}, ctx)
    assert result == {"env": {"DB_URL": "acdl-qa-db"}}


def test_expand_unknown_token_raises():
    ctx = {"env": {"region": "us-east-1"}, "contract": {}}
    with pytest.raises(ValueError, match="unresolved interpolation token"):
        _expand_vars("${env.unknown_field}", ctx)


def test_expand_unknown_namespace_raises():
    ctx = {"env": {}, "contract": {}}
    with pytest.raises(ValueError, match="unresolved interpolation token"):
        _expand_vars("${unknown.x}", ctx)


def test_expand_non_string_passthrough():
    ctx = {"env": {}, "contract": {}}
    assert _expand_vars(42, ctx) == 42
    assert _expand_vars(True, ctx) is True
    assert _expand_vars(None, ctx) is None


def test_resolve_static_assets_expands_bucket_name():
    """Resolving the sample contract produces the interpolated bucket name."""
    stack = resolve(str(ROOT / "contracts" / "static-assets.yml"))
    s3 = [r for r in stack["resources"] if r["type"] == "aws:s3:bucket"][0]
    assert s3["inputs"]["bucket_name"] == "acdl-dev-assets-000000000000-us-east-1"
    assert s3["inputs"]["region"] == "us-east-1"


def test_resolve_microservice_expands_bucket_name():
    stack = resolve(str(ROOT / "contracts" / "microservice.yml"))
    # The microservice L2 wires bucket_name to vpc.inputs.cidr (legacy wire);
    # the interpolated value is a valid CIDR-like string. The key assertion
    # is that resolution succeeds with interpolation (no unresolved tokens).
    assert stack["stack"]["name"] == "msvc"


def test_resolve_with_environment_override_uses_overridden_env():
    """D-088: environment_override changes the interpolation context."""
    stack = resolve(str(ROOT / "contracts" / "static-assets.yml"),
                    environment_override="qa")
    s3 = [r for r in stack["resources"] if r["type"] == "aws:s3:bucket"][0]
    # qa env: environment=qa, account_id=000000000000, region=us-east-1
    assert s3["inputs"]["bucket_name"] == "acdl-qa-assets-000000000000-us-east-1"