"""
Copyright (C) 2023  Michael Ablassmeier <abi@grinser.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

import os
import bisect
import builtins
import threading
from collections import OrderedDict
import json
import pprint
from typing import Any, Dict, List, Optional
import nbdkit

try:
    import lz4.frame
except ImportError:
    lz4 = None  # type: ignore[assignment]

API_VERSION = 2

blockMap: Optional[List[Dict[str, Any]]] = None
fullBlocks: List[Dict[str, Any]] = []
fullStarts: List[int] = []
# cache of recently decompressed lz4 frames, keyed by file offset
frameCache: "OrderedDict[int, bytes]" = OrderedDict()
# limit cache by total size, single frames can be up to 32 MiB
frameCacheMaxBytes = 128 * 1024 * 1024
frameCacheBytes = 0
frameCacheLock = threading.Lock()
blockMapFile: Optional[str] = None
image: Optional[str] = None
debug = "0"
hexdump = "0"

# pylint: disable=global-statement,global-variable-not-assigned,redefined-builtin,too-many-statements,too-many-branches


def config(key: str, value: str) -> None:
    """Read parameter values, needs to use open function via
    builtins as the python plugin itself defines it again"""
    global blockMap
    global blockMapFile
    global image
    global debug
    global hexdump
    if key == "blockmap":
        blockMapFile = value
        with builtins.open(blockMapFile, "rb") as fh:
            blockMap = json.loads(fh.read())
        return
    if key == "disk":
        image = value
        return
    if key == "debug":
        debug = value
        return
    if key == "hexdump":
        hexdump = value
        return

    raise RuntimeError(f"Unsupported parameter: {key}")


def log(msg: str) -> None:
    """Debug logging"""
    global debug
    if debug == "1":
        nbdkit.debug(msg)


def config_complete() -> None:
    """Check if we have all required parameters"""
    global image
    global blockMap
    global blockMapFile
    if image is None or blockMap is None or blockMapFile is None:
        raise RuntimeError(
            "Missing parameter: path to blockmap and disk files required."
        )

    if not os.path.exists(image):
        raise RuntimeError(f"Specified image file: [{image}] does not exist.")
    if not os.path.exists(blockMapFile):
        raise RuntimeError(f"Specified blockmap file: [{blockMapFile}] does not exit.")

    global fullBlocks
    global fullStarts
    fullBlocks = sorted(
        (b for b in blockMap if not b["inc"]), key=lambda b: b["originalOffset"]
    )
    if not fullBlocks:
        raise RuntimeError("Blockmap contains no blocks from a full backup.")
    fullStarts = [b["originalOffset"] for b in fullBlocks]
    if lz4 is None and any(b.get("compressed") for b in blockMap):
        raise RuntimeError("Compressed backup requires python lz4 module.")

    pprint.pprint(blockMap)


def thread_model() -> int:
    """nbdkit threading model"""
    return nbdkit.THREAD_MODEL_PARALLEL


def open(_: bool) -> int:
    """Open backup files and return FD for each"""
    assert image is not None
    fd = os.open(image, os.O_RDONLY)
    log(f"File descriptors: {fd}")
    return fd


def close(h: int) -> None:
    """Close file descriptor opened for the connection"""
    os.close(h)


def get_size(_: int) -> int:
    """Loop through the metadata and calculate the complete
    virtual disk size"""
    last = fullBlocks[-1]
    size = last["originalOffset"] + last["length"]
    log(f"DISK SIZE: {size}")
    return size


def _hexdump(data: bytearray, width: int = 16) -> None:
    """Hexdump for debugging, dumps requested blocks in an
    hexdump -C compatible format"""
    zero_count = 0
    skip_mode = False

    for i in range(0, len(data), width):
        chunk = data[i : i + width]

        if all(byte == 0 for byte in chunk):
            zero_count += len(chunk)
            skip_mode = True
            continue  # Skip this block

        if skip_mode:
            log(f"... ({zero_count} zero bytes skipped)")
            zero_count = 0  # Reset counter
            skip_mode = False

        hex_part = " ".join(f"{byte:02X}" for byte in chunk)
        ascii_part = "".join(chr(byte) if 32 <= byte < 127 else "." for byte in chunk)
        log(f"{i:08X}  {hex_part:<{width * 3}}  |{ascii_part}|")

    if zero_count > 0:
        log(f"... ({zero_count} zero bytes skipped)")


def _readFrame(h: int, block: Dict[str, Any]) -> bytes:
    """Return decompressed data of an lz4 frame, frames are cached as
    consecutive reads usually hit the same frame."""
    global frameCacheBytes
    key = block["offset"]
    with frameCacheLock:
        data = frameCache.get(key)
        if data is not None:
            frameCache.move_to_end(key)
            return data

    compressed = os.pread(h, block["compressedLength"], block["offset"])
    data = lz4.frame.decompress(compressed)
    if len(data) != block["length"]:
        raise RuntimeError(
            f"Decompressed frame at {key} has size {len(data)}, "
            f"expected {block['length']}"
        )

    with frameCacheLock:
        if key not in frameCache:
            frameCache[key] = data
            frameCacheBytes += len(data)
        while frameCacheBytes > frameCacheMaxBytes and len(frameCache) > 1:
            _, evicted = frameCache.popitem(last=False)
            frameCacheBytes -= len(evicted)
    return data


def pread(h: int, buf: bytearray, offset: int, _: int) -> None:
    """Return the right data during read operation.

    Uses the block map of the full backup to locate every extent
    covered by the requested range [offset, offset + len(buf)) and
    reads the matching part of each: payload from the stream file
    for data extents, zeroes for zero extents. Reads may start at
    any position within an extent and span any number of extents.
    """
    end = offset + len(buf)
    pos = offset
    data = bytearray()

    log(f"Handle: {h}, read offset: {offset}, length: {len(buf)}")
    while pos < end:
        idx = bisect.bisect_right(fullStarts, pos) - 1
        if idx < 0:
            raise RuntimeError(f"Unable to locate block for offset {pos}")
        block = fullBlocks[idx]
        blockEnd = block["originalOffset"] + block["length"]
        if pos >= blockEnd:
            raise RuntimeError(f"Offset {pos} beyond end of block map")

        toRead = min(end, blockEnd) - pos
        log(f"Processing block: {block}, reading {toRead} at disk offset {pos}")
        if block["data"] and block.get("compressed"):
            start = pos - block["originalOffset"]
            data += _readFrame(h, block)[start : start + toRead]
        elif block["data"]:
            fileOffset = block["offset"] + (pos - block["originalOffset"])
            chunk = os.pread(h, toRead, fileOffset)
            if len(chunk) != toRead:
                raise RuntimeError(
                    f"Short read from file at {fileOffset}: "
                    f"{len(chunk)} requested: {toRead}"
                )
            data += chunk
        else:
            data += b"\0" * toRead
        pos += toRead

    if hexdump == "1":
        _hexdump(data)
    buf[:] = data
