"""Tests for V8 z-machine version support."""

import pytest

from mudlib.zmachine.zmemory import ZMemory, ZMemoryUnsupportedVersion


def make_minimal_story(version: int, size: int) -> bytes:
    """Create a minimal z-machine story file of the specified version and size."""
    story = bytearray(size)
    story[0] = version  # version byte
    # Set static memory base (0x0E) to a reasonable value
    story[0x0E] = 0x04
    story[0x0F] = 0x00
    # Set high memory base (0x04) to end of file
    story[0x04] = (size >> 8) & 0xFF
    story[0x05] = size & 0xFF
    # Set global variables base (0x0C)
    story[0x0C] = 0x03
    story[0x0D] = 0x00
    return bytes(story)


def test_v3_accepts_128kb_story():
    """V3 stories can be up to 128KB (131072 bytes)."""
    story = make_minimal_story(3, 131072)
    mem = ZMemory(story)
    assert mem.version == 3


def test_v5_accepts_256kb_story():
    """V5 stories can be up to 256KB (262144 bytes)."""
    story = make_minimal_story(5, 262144)
    mem = ZMemory(story)
    assert mem.version == 5


def test_v8_accepts_512kb_story():
    """V8 stories can be up to 512KB (524288 bytes)."""
    story = make_minimal_story(8, 524288)
    mem = ZMemory(story)
    assert mem.version == 8


def test_v8_packed_address_scaling():
    """V8 uses ×8 scaling for packed addresses (not ×4 like V5)."""
    story = make_minimal_story(8, 10000)
    mem = ZMemory(story)
    # V8 packed address 100 should map to byte address 800
    assert mem.packed_address(100) == 800


def test_v6_unsupported():
    """V6 should still be unsupported (different packed address format)."""
    story = make_minimal_story(6, 10000)
    with pytest.raises(ZMemoryUnsupportedVersion):
        ZMemory(story)


def test_v7_unsupported():
    """V7 should still be unsupported (different packed address format)."""
    story = make_minimal_story(7, 10000)
    with pytest.raises(ZMemoryUnsupportedVersion):
        ZMemory(story)
