from pkglite.unpack import parse_packed_file, unpack


def test_unpack_text_files(tmp_path):
    """Test unpacking text files from a packed file."""
    packed_content = """# Generated by py-pkglite
Package: testpkg
File: test.py
Format: text
Content:
  print('hello')
  print('world')
"""
    packed_file = tmp_path / "packed.txt"
    packed_file.write_text(packed_content)

    output_dir = tmp_path / "output"

    unpack(str(packed_file), output_dir=str(output_dir))

    unpacked_file = output_dir / "testpkg" / "test.py"
    assert unpacked_file.exists()
    content = unpacked_file.read_text()
    assert "print('hello')" in content
    assert "print('world')" in content


def test_unpack_binary_files(tmp_path):
    """Test unpacking binary files from a packed file."""
    packed_content = """# Generated by py-pkglite
Package: testpkg
File: data.bin
Format: binary
Content:
  0001020304
"""
    packed_file = tmp_path / "packed.txt"
    packed_file.write_text(packed_content)

    output_dir = tmp_path / "output"

    unpack(str(packed_file), output_dir=str(output_dir))

    unpacked_file = output_dir / "testpkg" / "data.bin"
    assert unpacked_file.exists()
    content = unpacked_file.read_bytes()
    assert content == bytes([0x00, 0x01, 0x02, 0x03, 0x04])


def test_parse_packed_file(tmp_path):
    """Test parsing of packed file format."""
    packed_content = """# Generated by py-pkglite
Package: pkg1
File: a.txt
Format: text
Content:
  hello
  world

Package: pkg2
File: b.bin
Format: binary
Content:
  0001020304
"""
    packed_file = tmp_path / "packed.txt"
    packed_file.write_text(packed_content)

    files = parse_packed_file(str(packed_file))

    assert len(files) == 2
    assert files[0].package == "pkg1"
    assert files[0].path == "a.txt"
    assert files[0].format == "text"
    assert "hello\nworld" in files[0].content

    assert files[1].package == "pkg2"
    assert files[1].path == "b.bin"
    assert files[1].format == "binary"
    assert files[1].content == "0001020304"
