# 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))
@click.option('-i', '--inode', is_flag=True, help="Print only POSIX inode metadata (without EXIF data).")
@click.option('-e', '--exif', is_flag=True, help="Print only EXIF metadata (without POSIX inode metadata).")
def inspect(path, inode, exif):
    """Lists all basic inode metadata and EXIF data about a file"""
    if inode and exif:
        raise click.UsageError("Cannot specify both -i/--inode and -e/--exif.")
        
    meta = get_metadata(Path(path))
    
    # Present using Rich Table
    from rich.console import Console
    from rich.table import Table
    
    console = Console()
    
    if not exif:
        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)
        
    exif_displayed = False
    if not inode:
        if meta.exif_data:
            exif_table = Table(title=f"EXIF Metadata: {meta.filename}", show_header=True)
            exif_table.add_column("Tag", style="bold green")
            exif_table.add_column("Value")
            
            for tag, val in sorted(meta.exif_data.items()):
                if isinstance(val, bytes):
                    val_str = val.hex().upper()
                    if len(val_str) > 60:
                        val_str = val_str[:57] + "..."
                else:
                    val_str = str(val)
                exif_table.add_row(tag, val_str)
                
            console.print(exif_table)
            exif_displayed = True
            
        if meta.comment:
            from rich.panel import Panel
            console.print(Panel(
                meta.comment,
                title=f"[bold green]Comment: {meta.filename}[/bold green]",
                border_style="green"
            ))
            exif_displayed = True
            
        if exif and not exif_displayed:
            console.print("[bold yellow]No EXIF or comment metadata found.[/bold yellow]")
        
    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)
# }}}

