import argparse
import datetime
import json
import os
import struct

# --- DEFAULT INPUT BINARY CONFIGURATION ---
DEFAULT_MFT_PATH = r"C:\Temp\projectPreCollection\MFT_C.bin"


# --- BINARY PARSING HELPER FUNCTIONS ---

def filetime_to_dt(filetime):
    """Converts a 64-bit Windows FILETIME integer to a human-readable UTC timestamp string."""
    if not filetime or filetime == 0:
        return "N/A"
    try:
        # FILETIME is 100-nanosecond intervals since January 1, 1601 (UTC)
        us = filetime / 10
        return (datetime.datetime(1601, 1, 1, tzinfo=datetime.timezone.utc) + 
                datetime.timedelta(microseconds=us)).strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        return "Invalid Filetime"


def parse_mft_bin(bin_file_path):
    """Reads raw $MFT binary file in 1024-byte record blocks and extracts metadata."""
    records_dict = {}
    
    if not os.path.exists(bin_file_path):
        print(f"[!] Error: Binary file not found at path:\n    {bin_file_path}")
        return records_dict

    file_size = os.path.getsize(bin_file_path)
    total_records = file_size // 1024
    print(f"[+] Loading MFT Binary: {bin_file_path}")
    print(f"[+] Total file size: {file_size:,} bytes (~{total_records:,} MFT records)")

    with open(bin_file_path, "rb") as f:
        rec_index = 0
        while True:
            raw_rec = f.read(1024)
            if len(raw_rec) < 1024:
                break

            # Verify 'FILE' record signature (0x46494C45)
            signature = raw_rec[:4]
            if signature != b"FILE":
                rec_index += 1
                continue

            # Parse MFT Header
            first_attr_offset = struct.unpack("<H", raw_rec[20:22])[0]
            flags = struct.unpack("<H", raw_rec[22:24])[0]

            is_in_use = bool(flags & 0x01)
            is_dir = bool(flags & 0x02)
            alloc_str = "Allocated" if is_in_use else "Deleted / Unallocated"

            # Parse Attributes starting at offset
            offset = first_attr_offset
            parsed_attr = {
                "id": rec_index,
                "name": f"Record_{rec_index}",
                "parent_id": None,
                "is_dir": is_dir,
                "alloc": alloc_str,
                "created": "N/A",
                "modified": "N/A",
                "mft_modified": "N/A",
                "accessed": "N/A"
            }

            file_name_found = False

            while offset < 1024 - 8:
                attr_type, attr_len = struct.unpack("<II", raw_rec[offset:offset+8])
                if attr_type == 0xFFFFFFFF or attr_len == 0:
                    break  # End of attributes

                # Ensure attribute length stays bounded within record limits
                if offset + attr_len > 1024:
                    break

                non_resident = raw_rec[offset + 8]

                # 0x10: $STANDARD_INFORMATION (MACB Timestamps)
                if attr_type == 0x10 and not non_resident:
                    content_offset = offset + struct.unpack("<H", raw_rec[offset+20:offset+22])[0]
                    if content_offset + 32 <= offset + attr_len:
                        c_time, m_time, b_time, a_time = struct.unpack("<QQQQ", raw_rec[content_offset:content_offset+32])
                        parsed_attr["created"] = filetime_to_dt(c_time)
                        parsed_attr["modified"] = filetime_to_dt(m_time)
                        parsed_attr["mft_modified"] = filetime_to_dt(b_time)
                        parsed_attr["accessed"] = filetime_to_dt(a_time)

                # 0x30: $FILE_NAME (Name and Parent Record Reference)
                elif attr_type == 0x30 and not non_resident:
                    content_offset = offset + struct.unpack("<H", raw_rec[offset+20:offset+22])[0]
                    if content_offset + 66 <= offset + attr_len:
                        parent_ref = struct.unpack("<Q", raw_rec[content_offset:content_offset+8])[0]
                        parent_record_id = parent_ref & 0xFFFFFFFFFFFF  # Lower 48 bits = MFT record index
                        
                        name_len = raw_rec[content_offset + 64]
                        name_namespace = raw_rec[content_offset + 65]
                        
                        # Win32 (1) or Win32 & DOS (3) names take priority over DOS short names (2)
                        if not file_name_found or name_namespace in (1, 3):
                            try:
                                raw_name = raw_rec[content_offset+66 : content_offset+66+(name_len*2)]
                                name_str = raw_name.decode("utf-16le")
                                parsed_attr["name"] = name_str
                                parsed_attr["parent_id"] = parent_record_id
                                file_name_found = True
                            except Exception:
                                pass

                offset += attr_len

            records_dict[rec_index] = parsed_attr
            rec_index += 1

    print(f"[+] Successfully parsed {len(records_dict):,} valid MFT records.")
    return records_dict


# --- CONSOLE OUTPUT HELPER ---

def print_first_50_records(records_dict, limit=50):
    """Prints a formatted summary table of the first N records in records_dict."""
    print(f"\n{'='*110}")
    print(f"{'RECORD ID':<10} | {'TYPE':<6} | {'STATE':<12} | {'NAME':<40} | {'PARENT ID':<10} | {'CREATED (UTC)':<19}")
    print(f"{'='*110}")

    count = 0
    for rec_id, rec in records_dict.items():
        if count >= limit:
            break

        obj_type = "DIR" if rec.get("is_dir") else "FILE"
        alloc_state = rec.get("alloc", "N/A")
        name = rec.get("name", "N/A")
        
        if len(name) > 37:
            name = name[:34] + "..."

        parent = str(rec.get("parent_id", "N/A"))
        created = str(rec.get("created", "N/A"))

        print(f"{str(rec_id):<10} | {obj_type:<6} | {alloc_state:<12} | {name:<40} | {parent:<10} | {created:<19}")
        count += 1

    print(f"{'='*110}")
    print(f"[+] Displayed {count} of {len(records_dict):,} total parsed records in console.\n")


# --- HTML GENERATOR ---

def generate_explorer_html(records_dict, output_path="mft_explorer_view.html"):
    """Generates an interactive Windows Explorer HTML view."""
    
    print("[+] Building Explorer Hierarchy tree...")
    children_map = {}
    node_data = {}

    for rec_id, rec in records_dict.items():
        node_data[rec_id] = rec
        parent_id = rec.get("parent_id")
        
        if parent_id == rec_id or parent_id not in records_dict:
            parent_id = "ROOT_ORPHANS" if rec_id != 5 else "ROOT_DRIVE"

        if parent_id not in children_map:
            children_map[parent_id] = []
        children_map[parent_id].append(rec_id)

    html_template = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MFT Windows Explorer View</title>
<style>
    * { box-sizing: border-box; }
    body { background: #191919; color: #e0e0e0; font-family: 'Segoe UI', Tahoma, sans-serif; margin: 0; padding: 0; display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
    header { background: #2d2d2d; border-bottom: 1px solid #3c3c3c; padding: 10px 20px; display: flex; align-items: center; justify-content: space-between; }
    h1 { font-size: 1.1rem; margin: 0; color: #0078d4; font-weight: 600; display: flex; align-items: center; gap: 8px; }
    .app-container { display: flex; flex: 1; overflow: hidden; }
    .tree-pane { width: 45%; background: #202020; border-right: 1px solid #333333; overflow-y: auto; padding: 10px; font-size: 0.88rem; }
    ul { list-style: none; padding-left: 18px; margin: 2px 0; }
    .tree-pane > ul { padding-left: 0; }
    li { margin: 2px 0; user-select: none; }
    .tree-item { display: flex; align-items: center; padding: 3px 6px; border-radius: 4px; cursor: pointer; gap: 6px; white-space: nowrap; }
    .tree-item:hover { background: #2a2a2a; }
    .tree-item.selected { background: #005a9e !important; color: #ffffff; }
    .toggler { width: 12px; height: 12px; display: inline-flex; align-items: center; justify-content: center; font-size: 0.7rem; color: #888; cursor: pointer; }
    .icon { font-size: 1rem; }
    .folder-icon { color: #e3a857; }
    .file-icon { color: #9da5b4; }
    .details-pane { flex: 1; background: #181818; padding: 20px; overflow-y: auto; font-size: 0.9rem; }
    .details-card { background: #252525; border: 1px solid #383838; border-radius: 6px; padding: 20px; max-width: 650px; }
    .details-card h2 { font-size: 1.2rem; color: #0078d4; margin-top: 0; border-bottom: 1px solid #383838; padding-bottom: 8px; word-break: break-all; }
    .prop-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #2d2d2d; }
    .prop-row:last-child { border-bottom: none; }
    .prop-key { font-weight: bold; color: #a0a0a0; }
    .prop-val { color: #ffffff; font-family: monospace; }
    .badge-alloc { color: #4caf50; font-weight: bold; }
    .badge-del { color: #f44336; font-weight: bold; }
</style>
</head>
<body>
<header>
    <h1>📁 MFT Windows Explorer Hierarchy Viewer</h1>
    <div style="font-size: 0.85rem; color: #888;">Total Records: __TOTAL_RECORDS__</div>
</header>

<div class="app-container">
    <div class="tree-pane" id="treePane">
        <ul>
            <li>
                <div class="tree-item" onclick="selectNode(5)">
                    <span class="toggler" onclick="toggleTree(event, this)">▼</span>
                    <span class="icon folder-icon">💻</span>
                    <span><strong>C:\\ Root Drive</strong></span>
                </div>
                <ul id="children_ROOT_DRIVE"></ul>
            </li>
            <li style="margin-top: 15px;">
                <div class="tree-item" onclick="selectNode(null)">
                    <span class="toggler" onclick="toggleTree(event, this)">▶</span>
                    <span class="icon folder-icon">📦</span>
                    <span><strong>[Orphaned / Unlinked Records]</strong></span>
                </div>
                <ul id="children_ROOT_ORPHANS" style="display:none;"></ul>
            </li>
        </ul>
    </div>

    <div class="details-pane">
        <div class="details-card" id="detailsCard">
            <h2>Select a File or Directory</h2>
            <p style="color: #888;">Click any node in the left tree to inspect metadata and MACB timestamps.</p>
        </div>
    </div>
</div>

<script>
const nodeData = __NODE_DATA__;
const childrenMap = __CHILDREN_MAP__;

function renderBranch(parentId, containerEl) {
    const childIds = childrenMap[parentId] || [];
    childIds.forEach(id => {
        const node = nodeData[id];
        if (!node) return;

        const li = document.createElement('li');
        const hasChildren = childrenMap[id] && childrenMap[id].length > 0;
        
        const itemDiv = document.createElement('div');
        itemDiv.className = 'tree-item';
        itemDiv.onclick = (e) => { selectNode(id); e.stopPropagation(); };
        
        const toggler = document.createElement('span');
        toggler.className = 'toggler';
        toggler.innerText = hasChildren ? '▶' : '';
        toggler.onclick = (e) => toggleTree(e, toggler);
        
        const icon = document.createElement('span');
        icon.className = 'icon ' + (node.is_dir ? 'folder-icon' : 'file-icon');
        icon.innerText = node.is_dir ? '📁' : '📄';

        const nameSpan = document.createElement('span');
        nameSpan.innerText = node.name;

        itemDiv.appendChild(toggler);
        itemDiv.appendChild(icon);
        itemDiv.appendChild(nameSpan);
        li.appendChild(itemDiv);

        if (hasChildren) {
            const childUl = document.createElement('ul');
            childUl.style.display = 'none';
            childUl.id = 'children_' + id;
            li.appendChild(childUl);
        }

        containerEl.appendChild(li);
    });
}

function toggleTree(e, togglerEl) {
    e.stopPropagation();
    const parentLi = togglerEl.closest('li');
    const childUl = parentLi.querySelector('ul');
    if (!childUl) return;

    if (childUl.style.display === 'none') {
        if (childUl.children.length === 0) {
            const parentId = childUl.id.replace('children_', '');
            renderBranch(parentId, childUl);
        }
        childUl.style.display = 'block';
        togglerEl.innerText = '▼';
    } else {
        childUl.style.display = 'none';
        togglerEl.innerText = '▶';
    }
}

function selectNode(id) {
    document.querySelectorAll('.tree-item').forEach(el => el.classList.remove('selected'));
    if (window.event && window.event.currentTarget) {
        window.event.currentTarget.classList.add('selected');
    }

    const card = document.getElementById('detailsCard');
    if (!id || !nodeData[id]) {
        card.innerHTML = '<h2>Unlinked / System Node</h2><p>Select a valid MFT record entry.</p>';
        return;
    }

    const n = nodeData[id];
    const allocBadge = n.alloc === 'Allocated' ? 
        '<span class="badge-alloc">Allocated</span>' : 
        '<span class="badge-del">Deleted / Unallocated</span>';

    card.innerHTML = `
        <h2>${n.is_dir ? '📁' : '📄'} ${escapeHtml(n.name)}</h2>
        <div class="prop-row"><span class="prop-key">MFT Record Index:</span><span class="prop-val">${n.id}</span></div>
        <div class="prop-row"><span class="prop-key">Parent Record Reference:</span><span class="prop-val">${n.parent_id !== null ? n.parent_id : 'N/A'}</span></div>
        <div class="prop-row"><span class="prop-key">Object Type:</span><span class="prop-val">${n.is_dir ? 'Directory' : 'File'}</span></div>
        <div class="prop-row"><span class="prop-key">Allocation State:</span><span class="prop-val">${allocBadge}</span></div>
        <div class="prop-row"><span class="prop-key">Created Time (C):</span><span class="prop-val">${n.created}</span></div>
        <div class="prop-row"><span class="prop-key">Modified Time (M):</span><span class="prop-val">${n.modified}</span></div>
        <div class="prop-row"><span class="prop-key">MFT Changed Time (B):</span><span class="prop-val">${n.mft_modified}</span></div>
        <div class="prop-row"><span class="prop-key">Accessed Time (A):</span><span class="prop-val">${n.accessed}</span></div>
    `;
}

function escapeHtml(text) {
    return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

window.onload = () => {
    renderBranch('ROOT_DRIVE', document.getElementById('children_ROOT_DRIVE'));
    renderBranch('ROOT_ORPHANS', document.getElementById('children_ROOT_ORPHANS'));
};
</script>
</body>
</html>"""

    html_content = html_template.replace("__NODE_DATA__", json.dumps(node_data)) \
                                .replace("__CHILDREN_MAP__", json.dumps(children_map)) \
                                .replace("__TOTAL_RECORDS__", f"{len(records_dict):,}")

    with open(output_path, "w", encoding="utf-8") as f:
        f.write(html_content)
    
    print(f"[+] Output HTML written to: {os.path.abspath(output_path)}")


# --- MAIN EXECUTION HARNESS ---

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Parse binary $MFT dump file and generate interactive Explorer HTML.")
    parser.add_argument("-f", "--file", default=DEFAULT_MFT_PATH, help=f"Path to raw binary $MFT file (default: {DEFAULT_MFT_PATH})")
    parser.add_argument("-o", "--output", default="mft_explorer_view.html", help="Path for HTML report output")
    
    args = parser.parse_args()

    # 1. Parse raw MFT binary
    records = parse_mft_bin(args.file)

    if records:
        # 2. Print first 50 parsed records to terminal
        print_first_50_records(records, limit=50)

        # 3. Generate HTML GUI report
        generate_explorer_html(records, output_path=args.output)
    else:
        print("[!] No records parsed. Ensure the path is valid or pass a different file with -f.")