"""Illustrative artifact promotion. Real approvals belong in the CI platform."""
import hashlib

ENVIRONMENTS = ("Dev", "Test", "UAT", "Production")


def digest(artifact):
    return hashlib.sha256(artifact).hexdigest()


def promote(history, target, artifact, expected_digest, approved_environments=()):
    """Return a new promotion history after validating state and artifact identity."""
    if len(history) >= len(ENVIRONMENTS) or target != ENVIRONMENTS[len(history)]:
        raise ValueError("Promotion must follow the declared environment order")
    actual = digest(artifact)
    if actual != expected_digest or any(entry != (env, actual) for entry, env in zip(history, ENVIRONMENTS)):
        raise ValueError("Artifact digest or promotion history has changed")
    if target in {"UAT", "Production"} and target not in approved_environments:
        raise ValueError(f"{target} approval is required")
    return (*history, (target, actual))


def rollback(releases, target):
    """Select the previous app artifact. The caller must check schema compatibility."""
    if target not in ENVIRONMENTS:
        raise ValueError("Unknown environment")
    deployed = [artifact for environment, artifact in releases if environment == target]
    if len(deployed) < 2:
        raise ValueError("No previous deployment")
    return deployed[-2]


if __name__ == "__main__":
    payload = b"synthetic release"
    trail = ()
    for environment in ENVIRONMENTS:
        trail = promote(trail, environment, payload, digest(payload), {"UAT", "Production"})
    for environment, artifact_digest in trail:
        print(environment, artifact_digest)
