
#!/usr/bin/env python3
"""
Westwood CPS Decompressor - Eye of the Beholder II.

Supported compression methods:
    0 : Uncompressed data
    4 : Westwood LCW (Format 80)

Usage:
    python3 uncps.py LEVEL4.INF LEVEL4.BIN

No external dependencies required.
"""

import argparse
import struct
import sys
from pathlib import Path


class CPSDecodeError(ValueError):
    """Raised when CPS data is invalid or decompression fails."""


def decode_lcw(source: bytes, expected_size: int) -> bytes:
    """
    Decompress a Westwood LCW (Format 80) data stream.

    Supported LCW commands:
        - Literal byte copy
        - Short relative back-reference
        - Medium absolute/relative copy
        - Repeated byte fill
        - Long absolute/relative copy

    Back-references support overlapping source and destination
    regions, as required by the LCW compression algorithm.

    Args:
        source: Compressed LCW byte stream.
        expected_size: Expected decompressed data size.

    Returns:
        Decompressed binary data.

    Raises:
        CPSDecodeError: If the compressed stream is malformed
            or the resulting size does not match expectations.
    """
    output = bytearray()
    pos = 0

    # Newer LCW variants may use relative offsets for long
    # copy commands. These streams begin with a 0x00 marker.
    relative_mode = bool(source and source[0] == 0)

    if relative_mode:
        pos = 1

    def read(count: int) -> bytes:
        """Read exactly 'count' bytes from the compressed stream."""
        nonlocal pos

        if pos + count > len(source):
            raise CPSDecodeError(
                f"Truncated LCW stream at offset 0x{pos:X}"
            )

        data = source[pos:pos + count]
        pos += count
        return data

    def read_u16() -> int:
        """Read a little-endian unsigned 16-bit integer."""
        return int.from_bytes(read(2), "little")

    def check_size(count: int) -> None:
        """Ensure the output does not exceed its expected size."""
        if len(output) + count > expected_size:
            raise CPSDecodeError(
                "Decompressed data exceeds the expected size "
                f"({expected_size} bytes)"
            )

    def copy_existing(start: int, count: int) -> None:
        """
        Copy bytes from previously decompressed data.

        Bytes are copied individually to correctly handle
        overlapping source and destination regions.
        """
        check_size(count)

        if count == 0:
            return

        if start < 0 or start >= len(output):
            raise CPSDecodeError(
                f"Invalid LCW back-reference: offset {start}, "
                f"current output size {len(output)}"
            )

        for i in range(count):
            output.append(output[start + i])

    while True:
        command = read(1)[0]

        # Command 0x80: end of LCW stream.
        if command == 0x80:
            break

        if (command & 0x80) == 0:
            # Short relative back-reference.
            # Two bytes: command and low byte of the distance.
            count = (command >> 4) + 3
            distance = ((command & 0x0F) << 8) | read(1)[0]

            copy_existing(len(output) - distance, count)

        elif (command & 0x40) == 0:
            # Literal copy of 1 to 63 bytes.
            count = command & 0x3F

            check_size(count)
            output.extend(read(count))

        elif command == 0xFE:
            # Fill output with a repeated byte value.
            count = read_u16()
            value = read(1)[0]

            check_size(count)
            output.extend(bytes([value]) * count)

        elif command == 0xFF:
            # Long absolute or relative copy.
            count = read_u16()
            offset = read_u16()

            start = (
                len(output) - offset
                if relative_mode else offset
            )

            copy_existing(start, count)

        else:
            # Medium-length absolute or relative copy.
            count = (command & 0x3F) + 3
            offset = read_u16()

            start = (
                len(output) - offset
                if relative_mode else offset
            )

            copy_existing(start, count)

    if len(output) != expected_size:
        raise CPSDecodeError(
            "Incorrect decompressed size: "
            f"got {len(output)} bytes, "
            f"expected {expected_size}"
        )

    return bytes(output)


def decode_cps(data: bytes) -> tuple[bytes, int]:
    """
    Parse a Westwood CPS header and decompress its payload.

    CPS file header (10 bytes):
        Offset  Size  Description
        0x00    2     File size minus 2 (uint16)
        0x02    2     Compression method (uint16)
        0x04    4     Decompressed size (uint32)
        0x08    2     Palette size (uint16)
        0x0A    N     Optional palette followed by payload

    Supported compression methods:
        0 : Uncompressed
        4 : Westwood LCW

    Args:
        data: Complete CPS file contents.

    Returns:
        A tuple containing the decompressed data and
        the compression method identifier.

    Raises:
        CPSDecodeError: If the CPS header or payload is invalid.
    """
    if len(data) < 10:
        raise CPSDecodeError(
            "File is too small to contain a valid CPS header"
        )

    file_size, compression, unpacked_size, palette_size = (
        struct.unpack_from("<HHIH", data, 0)
    )

    if compression not in (0, 4):
        raise CPSDecodeError(
            f"Unsupported CPS compression method: {compression} "
            "(supported methods: 0 and 4)"
        )

    if file_size + 2 != len(data):
        raise CPSDecodeError(
            "CPS file size mismatch: "
            f"header specifies {file_size + 2} bytes, "
            f"actual size is {len(data)} bytes"
        )

    # Skip the CPS header and optional palette data.
    data_offset = 10 + palette_size

    if data_offset > len(data):
        raise CPSDecodeError(
            "CPS palette extends beyond the end of the file"
        )

    payload = data[data_offset:]

    if compression == 0:
        # Payload is already uncompressed.
        result = payload
    else:
        # Decode the Westwood LCW compressed payload.
        result = decode_lcw(payload, unpacked_size)

    if len(result) != unpacked_size:
        raise CPSDecodeError(
            "Decompressed size mismatch: "
            f"got {len(result)} bytes, "
            f"expected {unpacked_size}"
        )

    return result, compression


def main() -> int:
    """Parse command-line arguments and decompress a CPS file."""
    parser = argparse.ArgumentParser(
        description=(
            "Decompress a Westwood CPS file "
            "(Eye of the Beholder II)."
        )
    )

    parser.add_argument(
        "input",
        type=Path,
        help="Input CPS file (e.g. LEVEL4.INF)"
    )

    parser.add_argument(
        "output",
        type=Path,
        help="Output file for decompressed binary data"
    )

    args = parser.parse_args()

    try:
        # Prevent accidental overwriting of the input file.
        if args.input.resolve() == args.output.resolve():
            raise CPSDecodeError(
                "Input and output files must be different"
            )

        # Read and decompress the complete input file.
        compressed = args.input.read_bytes()
        decompressed, method = decode_cps(compressed)

        # Write the output only after successful decompression.
        args.output.write_bytes(decompressed)

    except (OSError, CPSDecodeError) as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1

    # Display a summary of the decompression operation.
    method_name = "LCW" if method == 4 else "Uncompressed"

    print(f"Input file       : {args.input}")
    print(f"Output file      : {args.output}")
    print(f"Compression      : {method} ({method_name})")
    print(f"Compressed size  : {len(compressed)} bytes")
    print(f"Decompressed size: {len(decompressed)} bytes")
    print("Decompression completed successfully.")

    return 0


if __name__ == "__main__":
    sys.exit(main())
