"""
tinyfs.py -- a complete, tiny file system living in a byte array.

[Idea]
  A disk is an array of fixed-size BLOCKS and nothing else. A file system is the
  set of conventions that turns that flat array into named files in directories.
  This module implements the classic Unix layout on a 4096-byte "disk":

      block 0        superblock   (magic, geometry: where everything lives)
      blocks 1-4     inode table  (16 inodes x 16 bytes: type, size, block ptrs)
      block 5        free bitmap  (one bit per block: used or not)
      blocks 6-63    data blocks  (file contents and directory contents)

  An INODE is a file's identity: its type, its size, and the numbers of the
  blocks holding its bytes. A file has NO name of its own -- names live in
  DIRECTORIES, which are ordinary files whose contents are (name -> inode)
  records. Path lookup is therefore a walk: read the root directory, find the
  next component's inode, read that directory, and so on.

[Why a simulator]
  A real disk cannot be inspected byte by byte in a lecture. Here the whole
  "disk" is a bytearray you can hexdump, so every structure is visible, and
  every operation counts its block reads and writes -- which is how you see
  WHY path lookup is expensive and why inodes are worth their indirection.

[NOT the lab]
  CMU's file-system lab (sfslab) has you build a file system in C against the
  lab's own interface. This is a Python teaching model with a different design
  and no lab I/O interface: it is for understanding the structures, not a
  deliverable.

[Python tip]
  All state is bytes in `self.disk`, and every lookup sorts or scans in a fixed
  order, so output is identical on Python 3.9 and 3.13.
"""
import struct

# ---- geometry (all sizes in bytes) -----------------------------------------
BLOCK_SIZE   = 64
NBLOCKS      = 64                   # -> a 4096-byte disk
INODE_SIZE   = 16
NINODES      = 16
SUPER_BLOCK  = 0
INODE_START  = 1                    # blocks 1..4 hold the inode table
INODE_BLOCKS = (NINODES * INODE_SIZE) // BLOCK_SIZE          # = 4
BITMAP_BLOCK = INODE_START + INODE_BLOCKS                    # = 5
DATA_START   = BITMAP_BLOCK + 1                              # = 6

NDIRECT      = 8                    # direct block pointers per inode
MAX_FILESIZE = NDIRECT * BLOCK_SIZE # = 512 bytes: the limit of this design

# inode types
T_FREE, T_FILE, T_DIR = 0, 1, 2

# A directory entry is 16 bytes: 1-byte inode number + 15-byte NUL-padded name.
DIRENT_SIZE = 16
NAME_MAX    = DIRENT_SIZE - 1

MAGIC = 0x15213                     # a file system's "is this really mine?" tag


class FSError(Exception):
    """Raised for the ordinary failures a file system reports (ENOENT, ENOSPC...)."""


class TinyFS:
    """A file system over a bytearray. Create one, call format(), then use it."""

    def __init__(self):
        self.disk = bytearray(BLOCK_SIZE * NBLOCKS)
        self.reads = 0      # block reads  -- the cost metric we teach with
        self.writes = 0     # block writes

    # ---- the only two operations a real disk offers -----------------------
    def _read_block(self, bno):
        """[Idea] Everything above this line is a convention; this is the disk."""
        if not 0 <= bno < NBLOCKS:
            raise FSError(f"block {bno} out of range")
        self.reads += 1
        off = bno * BLOCK_SIZE
        return self.disk[off:off + BLOCK_SIZE]

    def _write_block(self, bno, data):
        if len(data) != BLOCK_SIZE:
            raise FSError("a block write must be exactly one block")
        self.writes += 1
        off = bno * BLOCK_SIZE
        self.disk[off:off + BLOCK_SIZE] = data

    def reset_counters(self):
        self.reads = self.writes = 0

    # ---- superblock -------------------------------------------------------
    def format(self):
        """Lay down a fresh file system: superblock, empty inodes, bitmap, root dir."""
        self.disk = bytearray(BLOCK_SIZE * NBLOCKS)

        # Superblock: magic, block size, block count, inode count, and where the
        # inode table / bitmap / data area start. A real superblock is the same
        # idea: the map you need before you can read anything else.
        sb = struct.pack("<IHHHHHH", MAGIC, BLOCK_SIZE, NBLOCKS, NINODES,
                         INODE_START, BITMAP_BLOCK, DATA_START)
        self._write_block(SUPER_BLOCK, bytes(sb).ljust(BLOCK_SIZE, b"\x00"))

        # Mark the metadata blocks (0..DATA_START-1) as used in the bitmap.
        bitmap = bytearray(BLOCK_SIZE)
        for b in range(DATA_START):
            bitmap[b // 8] |= 1 << (b % 8)
        self._write_block(BITMAP_BLOCK, bytes(bitmap))

        # Zero the inode table.
        for b in range(INODE_START, INODE_START + INODE_BLOCKS):
            self._write_block(b, bytes(BLOCK_SIZE))

        # Create the root directory as inode 0, with "." pointing at itself.
        self._write_inode(0, T_DIR, 0, [0] * NDIRECT)
        self._dir_add(0, ".", 0)
        return self

    def superblock(self):
        """Read the superblock back as a dict (what a mount does first)."""
        raw = self._read_block(SUPER_BLOCK)
        magic, bs, nb, ni, istart, bmap, dstart = struct.unpack_from("<IHHHHHH", raw)
        if magic != MAGIC:
            raise FSError("bad magic: not a TinyFS disk")
        return {"magic": magic, "block_size": bs, "nblocks": nb, "ninodes": ni,
                "inode_start": istart, "bitmap": bmap, "data_start": dstart}

    # ---- the free-block bitmap -------------------------------------------
    def _alloc_block(self):
        """Find the first free block, mark it used, return its number."""
        bitmap = bytearray(self._read_block(BITMAP_BLOCK))
        for b in range(NBLOCKS):
            if not (bitmap[b // 8] >> (b % 8)) & 1:
                bitmap[b // 8] |= 1 << (b % 8)
                self._write_block(BITMAP_BLOCK, bytes(bitmap))
                self._write_block(b, bytes(BLOCK_SIZE))   # hand out a clean block
                return b
        raise FSError("no free blocks (ENOSPC)")

    def _free_block(self, b):
        bitmap = bytearray(self._read_block(BITMAP_BLOCK))
        bitmap[b // 8] &= ~(1 << (b % 8)) & 0xFF
        self._write_block(BITMAP_BLOCK, bytes(bitmap))

    def free_blocks(self):
        """How many data blocks are still free."""
        bitmap = self._read_block(BITMAP_BLOCK)
        return sum(1 for b in range(NBLOCKS)
                   if not (bitmap[b // 8] >> (b % 8)) & 1)

    # ---- inodes -----------------------------------------------------------
    def _inode_location(self, ino):
        """Which block holds inode `ino`, and at what offset inside it."""
        if not 0 <= ino < NINODES:
            raise FSError(f"inode {ino} out of range")
        byte = ino * INODE_SIZE
        return INODE_START + byte // BLOCK_SIZE, byte % BLOCK_SIZE

    def _read_inode(self, ino):
        """Return (type, size, [block pointers])."""
        bno, off = self._inode_location(ino)
        raw = self._read_block(bno)
        itype, size = struct.unpack_from("<BH", raw, off)
        ptrs = list(struct.unpack_from("<%dB" % NDIRECT, raw, off + 3))
        return itype, size, ptrs

    def _write_inode(self, ino, itype, size, ptrs):
        bno, off = self._inode_location(ino)
        raw = bytearray(self._read_block(bno))
        struct.pack_into("<BH", raw, off, itype, size)
        struct.pack_into("<%dB" % NDIRECT, raw, off + 3, *ptrs)
        self._write_block(bno, bytes(raw))

    def _alloc_inode(self, itype):
        for ino in range(NINODES):
            if self._read_inode(ino)[0] == T_FREE:
                self._write_inode(ino, itype, 0, [0] * NDIRECT)
                return ino
        raise FSError("no free inodes")

    # ---- reading and writing a file's bytes -------------------------------
    def _read_file(self, ino):
        itype, size, ptrs = self._read_inode(ino)
        out = bytearray()
        for p in ptrs:
            if len(out) >= size:
                break
            if p == 0:
                break
            out += self._read_block(p)
        return bytes(out[:size])

    def _write_file(self, ino, data):
        """Replace a file's contents, (re)allocating blocks as needed."""
        if len(data) > MAX_FILESIZE:
            raise FSError(f"file too large: {len(data)} > {MAX_FILESIZE} "
                          f"({NDIRECT} direct blocks x {BLOCK_SIZE}B)")
        itype, _, ptrs = self._read_inode(ino)
        need = (len(data) + BLOCK_SIZE - 1) // BLOCK_SIZE

        # free blocks we no longer need, allocate ones we do
        for i in range(need, NDIRECT):
            if ptrs[i]:
                self._free_block(ptrs[i])
                ptrs[i] = 0
        for i in range(need):
            if not ptrs[i]:
                ptrs[i] = self._alloc_block()

        for i in range(need):
            chunk = data[i * BLOCK_SIZE:(i + 1) * BLOCK_SIZE]
            self._write_block(ptrs[i], bytes(chunk).ljust(BLOCK_SIZE, b"\x00"))
        self._write_inode(ino, itype, len(data), ptrs)

    # ---- directories ------------------------------------------------------
    def _dir_entries(self, dino):
        """List a directory as [(name, inode), ...] in on-disk order."""
        raw = self._read_file(dino)
        out = []
        for off in range(0, len(raw), DIRENT_SIZE):
            rec = raw[off:off + DIRENT_SIZE]
            if len(rec) < DIRENT_SIZE or rec[0] == 0xFF:
                continue
            name = rec[1:].split(b"\x00")[0].decode()
            if name:
                out.append((name, rec[0]))
        return out

    def _dir_add(self, dino, name, ino):
        if len(name) > NAME_MAX:
            raise FSError(f"name too long (max {NAME_MAX})")
        if any(n == name for n, _ in self._dir_entries(dino)):
            raise FSError(f"'{name}' already exists (EEXIST)")
        raw = bytearray(self._read_file(dino))
        raw += bytes([ino]) + name.encode().ljust(NAME_MAX, b"\x00")
        self._write_file(dino, bytes(raw))

    def _dir_remove(self, dino, name):
        entries = self._dir_entries(dino)
        if not any(n == name for n, _ in entries):
            raise FSError(f"'{name}' not found (ENOENT)")
        raw = bytearray()
        for n, i in entries:
            if n == name:
                continue
            raw += bytes([i]) + n.encode().ljust(NAME_MAX, b"\x00")
        self._write_file(dino, bytes(raw))

    # ---- path lookup: the heart of a file system --------------------------
    def lookup(self, path, trace=None):
        """Resolve an absolute path to an inode number.

        [Idea] Start at the root inode (0) and consume one component at a time.
        For each component: read the current directory's contents, find the name,
        and move to the inode it names. If `trace` is a list, append a
        human-readable step for each stage -- this is what makes the cost visible.
        """
        if not path.startswith("/"):
            raise FSError("only absolute paths are supported")
        ino = 0
        if trace is not None:
            trace.append("start at root inode 0")
        for comp in [c for c in path.split("/") if c]:
            itype, _, _ = self._read_inode(ino)
            if itype != T_DIR:
                raise FSError(f"'{comp}': parent is not a directory (ENOTDIR)")
            entries = self._dir_entries(ino)
            match = [i for n, i in entries if n == comp]
            if trace is not None:
                trace.append(f"read dir inode {ino} ({len(entries)} entries), "
                             f"look for '{comp}' -> "
                             + (f"inode {match[0]}" if match else "NOT FOUND"))
            if not match:
                raise FSError(f"'{path}': no such file or directory (ENOENT)")
            ino = match[0]
        return ino

    def _split(self, path):
        """Split '/a/b/c' into (inode of '/a/b', 'c')."""
        if path == "/" or not path.startswith("/"):
            raise FSError("bad path")
        parent, _, name = path.rpartition("/")
        return self.lookup(parent if parent else "/"), name

    # ---- the public file-system API ---------------------------------------
    def create(self, path, data=b""):
        dino, name = self._split(path)
        ino = self._alloc_inode(T_FILE)
        self._dir_add(dino, name, ino)
        if data:
            self._write_file(ino, data)
        return ino

    def mkdir(self, path):
        dino, name = self._split(path)
        ino = self._alloc_inode(T_DIR)
        self._dir_add(dino, name, ino)
        self._dir_add(ino, ".", ino)
        return ino

    def write(self, path, data):
        self._write_file(self.lookup(path), data)

    def read(self, path):
        ino = self.lookup(path)
        itype, _, _ = self._read_inode(ino)
        if itype == T_DIR:
            raise FSError("is a directory (EISDIR)")
        return self._read_file(ino)

    def unlink(self, path):
        """Delete a file: free its data blocks, free its inode, drop the name."""
        dino, name = self._split(path)
        ino = self.lookup(path)
        itype, _, ptrs = self._read_inode(ino)
        if itype == T_DIR:
            raise FSError("is a directory (use rmdir)")
        for p in ptrs:
            if p:
                self._free_block(p)
        self._write_inode(ino, T_FREE, 0, [0] * NDIRECT)
        self._dir_remove(dino, name)

    def ls(self, path="/"):
        """List a directory: [(name, inode, type, size), ...], excluding '.'."""
        ino = self.lookup(path)
        out = []
        for name, i in self._dir_entries(ino):
            if name == ".":
                continue
            itype, size, _ = self._read_inode(i)
            out.append((name, i, "dir" if itype == T_DIR else "file", size))
        return out

    def stat(self, path):
        ino = self.lookup(path)
        itype, size, ptrs = self._read_inode(ino)
        return {"inode": ino, "type": "dir" if itype == T_DIR else "file",
                "size": size, "blocks": [p for p in ptrs if p]}

    # ---- inspection helpers (for the demo) --------------------------------
    def hexdump(self, bno, width=16, limit=BLOCK_SIZE):
        """Render a block as hex + printable ASCII, the way a disk editor would."""
        raw = self._read_block(bno)[:limit]
        lines = []
        for off in range(0, len(raw), width):
            chunk = raw[off:off + width]
            hx = " ".join(f"{b:02x}" for b in chunk)
            txt = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
            lines.append(f"    {off:04x}  {hx:<{width * 3}} |{txt}|")
        return "\n".join(lines)
