# src/ctf/cli_forensics.py
# CLI wrapper and rendering layer for forensics commands

# vim foldmethod=marker
import click
from pathlib import Path
from ctf.forensics import get_metadata, COMMON_SIGNATURES

# {{{ forensics_group
@click.group(name="forensics")
def forensics_group():
    """ A collection of forensics tools """
    pass
# }}}

# {{{ tf
@forensics_group.command()
def tf():
    click.echo("hello from forensics")
# }}}

# {{{ inspect
@forensics_group.command()
@click.argument('path', type=click.Path(exists=True))
def inspect(path):
    """Lists all basic inode metadata about a file"""
    meta = get_metadata(Path(path))
    
    # Present using Rich Table
    from rich.console import Console
    from rich.table import Table
    
    console = Console()
    table = Table(title=f"Metadata: {meta.filename}", show_header=False)
    table.add_column("Key", style="bold cyan")
    table.add_column("Value")
    
    table.add_row("Filename", meta.filename)
    table.add_row("Size", f"{meta.size} bytes")
    table.add_row("Magic Bytes (Hex)", meta.magic)
    table.add_row("Detected Type", meta.detected_type)
    table.add_row("Extension", meta.extension)
    table.add_row("Permissions", f"{meta.permissions_symbolic} ({meta.permissions_octal})")
    table.add_row("Owner", f"{meta.owner_username} (UID: {meta.owner_uid})")
    table.add_row("Group", f"{meta.owner_groupname} (GID: {meta.owner_gid})")
    table.add_row("Allocated Space", f"{meta.allocated_size} bytes")
    table.add_row("Hard Links", str(meta.hard_links))
    table.add_row("Inode", str(meta.inode))
    table.add_row("Device", str(meta.device))
    
    if meta.extended_attributes:
        xattr_str = ", ".join(f"{k}={v}" for k, v in meta.extended_attributes.items())
        table.add_row("Extended Attributes", xattr_str)
        
    console.print(table)
    return meta
# }}}

# {{{ list_signatures
@forensics_group.command(name="signatures")
def list_signatures():
    """List all supported file magic signatures and expected extensions."""
    from rich.console import Console
    from rich.table import Table

    console = Console()
    table = Table(title="Supported Magic Signatures", show_header=True)
    table.add_column("Magic Bytes (Hex)", style="bold cyan")
    table.add_column("File Type", style="bold green")
    table.add_column("Expected Exts")

    for signature, (type_name, exts) in COMMON_SIGNATURES.items():
        hex_str = signature.hex().upper()
        exts_str = ", ".join(exts) if exts else "Any / None"
        table.add_row(hex_str, type_name, exts_str)

    console.print(table)
# }}}

