import pytest

from debputy.architecture_support import faked_arch_table
from debputy.dh_migration.models import (
    DHMigrationSubstitution,
    AcceptableMigrationIssues,
)
from debputy.substitution import SubstitutionImpl

MOCK_ENV = {
    # This conflicts with the dpkg arch table intentionally (to ensure we can tell which one is being resolved)
    "DEB_HOST_ARCHITECTURE": "i386",
}
MOCK_DPKG_ARCH_TABLE = faked_arch_table("amd64", build_arch="i386")


@pytest.mark.parametrize(
    "value,expected",
    [
        (
            "unchanged",
            "unchanged",
        ),
        (
            "unchanged\\{{\n}}",
            "unchanged\\{{\n}}",
        ),  # Newline is not an allowed part of a substitution
        (
            "{{DOUBLE_OPEN_CURLY_BRACE}}{{NL}}{{DOUBLE_CLOSE_CURLY_BRACE}}",
            "{{\n}}",
        ),
        (
            "{{DOUBLE_OPEN_CURLY_BRACE}}TAB}}{{TAB{{DOUBLE_CLOSE_CURLY_BRACE}}",
            "{{TAB}}{{TAB}}",
        ),
        (
            "/usr/lib/{{DEB_HOST_MULTIARCH}}",
            f'/usr/lib/{MOCK_DPKG_ARCH_TABLE["DEB_HOST_MULTIARCH"]}',
        ),
    ],
)
def test_substitution_match(value, expected) -> None:
    subst = SubstitutionImpl(dpkg_arch_table=MOCK_DPKG_ARCH_TABLE, environment=MOCK_ENV)
    replacement = subst.substitute(value, "test def")
    assert replacement == expected


def test_migrate_substitution() -> None:
    subst = DHMigrationSubstitution(
        MOCK_DPKG_ARCH_TABLE, AcceptableMigrationIssues(frozenset()), []
    )
    replacement = subst.substitute("usr/lib/${DEB_HOST_MULTIARCH}/foo", "test def")
    assert replacement == "usr/lib/{{DEB_HOST_MULTIARCH}}/foo"
