#!/usr/bin/env python3
"""
01_filesystem.py -- build a file system, then take it apart byte by byte.

[Idea]
  Everything a file system does is bookkeeping over a flat array of blocks. This
  demo formats a 4096-byte "disk", creates directories and files, reads them
  back, traces a path lookup step by step, shows the raw bytes of a directory
  and an inode, deletes a file and watches the blocks come back, and finally
  hits the design's file-size ceiling -- which is the motivation for indirect
  blocks in a real file system.

Run:   python3 01_filesystem.py       (identical under Python 3.9 and 3.13)
"""
import course_path  # noqa: F401
from tinyfs import (TinyFS, FSError, BLOCK_SIZE, NBLOCKS, NINODES,
                    INODE_START, BITMAP_BLOCK, DATA_START, NDIRECT,
                    MAX_FILESIZE, DIRENT_SIZE)


def rule(title):
    print(f"\n== {title} ==")


def main():
    fs = TinyFS().format()

    # ---- 1. the layout ----------------------------------------------------
    rule("1. the disk layout (what format() wrote)")
    sb = fs.superblock()
    print(f"  disk = {NBLOCKS} blocks x {BLOCK_SIZE} B = {NBLOCKS * BLOCK_SIZE} B")
    print(f"  superblock magic = 0x{sb['magic']:05x}  (a mount checks this first)")
    print(f"  block 0            superblock")
    print(f"  blocks {INODE_START}-{BITMAP_BLOCK - 1}         inode table "
          f"({NINODES} inodes)")
    print(f"  block {BITMAP_BLOCK}            free-block bitmap")
    print(f"  blocks {DATA_START}-{NBLOCKS - 1}        data ({fs.free_blocks()} free)")

    # ---- 2. create a small tree ------------------------------------------
    rule("2. create directories and files")
    fs.mkdir("/docs")
    fs.mkdir("/docs/notes")
    fs.create("/readme.txt", b"TinyFS: a file system in a byte array.\n")
    fs.create("/docs/notes/lec19.txt",
              b"inodes hold metadata; directories hold names.\n")
    for path in ("/", "/docs", "/docs/notes"):
        listing = ", ".join(f"{n}({t},ino {i},{s}B)"
                            for n, i, t, s in fs.ls(path))
        print(f"  ls {path:<14} -> {listing}")

    # ---- 3. read back ----------------------------------------------------
    rule("3. read a file back through its inode")
    data = fs.read("/docs/notes/lec19.txt")
    st = fs.stat("/docs/notes/lec19.txt")
    print(f"  stat  -> inode {st['inode']}, {st['type']}, {st['size']} B, "
          f"blocks {st['blocks']}")
    print(f"  read  -> {data!r}")
    print(f"  bytes match what was written: "
          f"{data == b'inodes hold metadata; directories hold names.' + chr(10).encode()}")

    # ---- 4. path lookup, step by step ------------------------------------
    rule("4. path lookup is a WALK (and it costs block reads)")
    fs.reset_counters()
    trace = []
    ino = fs.lookup("/docs/notes/lec19.txt", trace=trace)
    for step in trace:
        print(f"  - {step}")
    print(f"  => inode {ino}, costing {fs.reads} block reads "
          f"for a {len('/docs/notes/lec19.txt')}-character path")
    fs.reset_counters()
    fs.lookup("/readme.txt")
    print(f"  (a one-component path '/readme.txt' costs only {fs.reads} reads "
          f"-- deep paths are dearer)")

    # ---- 5. the raw bytes ------------------------------------------------
    rule("5. the same structures as raw bytes")
    root_blocks = fs.stat("/")["blocks"]
    print(f"  root directory's data block {root_blocks[0]} "
          f"({DIRENT_SIZE}-byte records: 1 inode byte + 15 name bytes):")
    print(fs.hexdump(root_blocks[0], limit=48))
    print(f"  inode table block {INODE_START} "
          f"(16-byte inodes: type, 2-byte size, {NDIRECT} block pointers):")
    print(fs.hexdump(INODE_START, limit=48))

    # ---- 6. delete and watch the space return ----------------------------
    rule("6. unlink: free the blocks, free the inode, drop the name")
    before = fs.free_blocks()
    st = fs.stat("/readme.txt")
    fs.unlink("/readme.txt")
    after = fs.free_blocks()
    print(f"  '/readme.txt' used inode {st['inode']} and blocks {st['blocks']}")
    print(f"  free blocks: {before} -> {after} (+{after - before})")
    print(f"  ls / -> " + ", ".join(f"{n}" for n, _, _, _ in fs.ls("/")))
    try:
        fs.read("/readme.txt")
    except FSError as e:
        print(f"  reading it now: {e}")

    # ---- 7. the ceiling of a direct-only design --------------------------
    rule("7. why real inodes need INDIRECT blocks")
    fs.create("/big.bin")
    ok = b"A" * MAX_FILESIZE
    fs.write("/big.bin", ok)
    print(f"  {NDIRECT} direct pointers x {BLOCK_SIZE} B = "
          f"{MAX_FILESIZE} B is the largest file this design can hold")
    print(f"  writing {MAX_FILESIZE} B: ok ({fs.stat('/big.bin')['size']} B stored)")
    try:
        fs.write("/big.bin", b"A" * (MAX_FILESIZE + 1))
    except FSError as e:
        print(f"  writing {MAX_FILESIZE + 1} B: {e}")
    print("  a real inode adds single/double/triple INDIRECT pointers: blocks")
    print("  that hold more block numbers, so a 16-byte-ish inode can describe")
    print("  a multi-gigabyte file while small files still cost one pointer.")

    # ---- 8. filling the disk --------------------------------------------
    rule("8. running out of resources (blocks AND inodes are both finite)")
    n = 0
    try:
        while True:
            fs.create(f"/f{n}", b"x" * BLOCK_SIZE)
            n += 1
    except FSError as e:
        print(f"  created {n} more 1-block files, then: {e}")
    print(f"  free blocks now {fs.free_blocks()}, "
          f"inodes are the other finite resource ({NINODES} total)")

    # ---- observations ----------------------------------------------------
    print("\nObservations")
    print("------------")
    print("- A file has no name: the inode holds type/size/block-pointers, and")
    print("  the NAME lives in a directory, which is just a file of records.")
    print("  That is why one file can have several names (hard links).")
    print("- Path lookup walks component by component, reading a directory at")
    print("  each level: /docs/notes/lec19.txt cost several block reads while")
    print("  /readme.txt cost far fewer. Deep paths are genuinely more work,")
    print("  which is why kernels cache lookups aggressively.")
    print("- Deleting a file returns its data blocks to the bitmap and its inode")
    print("  to the free pool; the name disappears from the parent directory.")
    print("- With only direct pointers the maximum file is NDIRECT*BLOCK_SIZE.")
    print("  Indirect blocks are the standard fix, and the reason a real inode")
    print("  can describe a huge file without being huge itself.")
    print("- Two independent resources run out: data BLOCKS and INODES. A disk")
    print("  full of empty files exhausts inodes with blocks to spare.")


if __name__ == "__main__":
    main()
