"""Minimal, safe reader for PHP-serialized scalars and arrays.

WordPress stores array-valued post meta (e.g. Houzez ``additional_features``)
as PHP-serialized strings and the REST API returns them verbatim. Only plain
data is supported (null, bool, int, float, string, array); objects are
rejected on purpose so untrusted input can never instantiate anything.
"""
from __future__ import annotations

from typing import Any


class PhpSerializedError(ValueError):
    pass


def php_unserialize(data: str) -> Any:
    if not isinstance(data, str):
        raise PhpSerializedError("Expected a string.")
    raw = data.encode("utf-8")
    value, position = _parse(raw, 0)
    if position != len(raw):
        raise PhpSerializedError("Trailing data after serialized value.")
    return value


def _read_until(raw: bytes, position: int, terminator: bytes) -> tuple[bytes, int]:
    end = raw.find(terminator, position)
    if end == -1:
        raise PhpSerializedError("Unterminated token.")
    return raw[position:end], end + len(terminator)


def _parse(raw: bytes, position: int) -> tuple[Any, int]:
    if position >= len(raw):
        raise PhpSerializedError("Unexpected end of data.")
    kind = raw[position:position + 1]

    if kind == b"N":
        if raw[position:position + 2] != b"N;":
            raise PhpSerializedError("Malformed null.")
        return None, position + 2

    if kind in (b"b", b"i", b"d"):
        if raw[position + 1:position + 2] != b":":
            raise PhpSerializedError("Malformed scalar.")
        token, next_position = _read_until(raw, position + 2, b";")
        try:
            if kind == b"b":
                return token == b"1", next_position
            if kind == b"i":
                return int(token), next_position
            return float(token), next_position
        except ValueError as exc:
            raise PhpSerializedError("Malformed scalar value.") from exc

    if kind == b"s":
        if raw[position + 1:position + 2] != b":":
            raise PhpSerializedError("Malformed string.")
        length_token, cursor = _read_until(raw, position + 2, b":")
        try:
            length = int(length_token)
        except ValueError as exc:
            raise PhpSerializedError("Malformed string length.") from exc
        if length < 0 or raw[cursor:cursor + 1] != b'"':
            raise PhpSerializedError("Malformed string.")
        start = cursor + 1
        end = start + length
        if raw[end:end + 2] != b'";':
            raise PhpSerializedError("String length mismatch.")
        try:
            return raw[start:end].decode("utf-8"), end + 2
        except UnicodeDecodeError as exc:
            raise PhpSerializedError("Invalid UTF-8 in string.") from exc

    if kind == b"a":
        if raw[position + 1:position + 2] != b":":
            raise PhpSerializedError("Malformed array.")
        count_token, cursor = _read_until(raw, position + 2, b":")
        try:
            count = int(count_token)
        except ValueError as exc:
            raise PhpSerializedError("Malformed array size.") from exc
        if count < 0 or raw[cursor:cursor + 1] != b"{":
            raise PhpSerializedError("Malformed array.")
        cursor += 1
        result: dict[Any, Any] = {}
        for _ in range(count):
            key, cursor = _parse(raw, cursor)
            if not isinstance(key, (int, str)):
                raise PhpSerializedError("Unsupported array key.")
            value, cursor = _parse(raw, cursor)
            result[key] = value
        if raw[cursor:cursor + 1] != b"}":
            raise PhpSerializedError("Unterminated array.")
        return result, cursor + 1

    raise PhpSerializedError(f"Unsupported PHP type: {kind!r}")
