#!/bin/bash

PROJECT_ROOT="."
OUTPUT_FILE="code.txt"
TMP_TOC="toc.tmp"
TMP_META="meta.tmp"

cd "$(dirname "$0")"

# Create or clear output files
: >"$OUTPUT_FILE"
: >"$TMP_TOC"
: >"$TMP_META"

# Collect .rs files and important documentation/config files from entire project, skipping 'target' directories
FILES=()
while IFS= read -r file; do
    FILES+=("$file")
done < <(find "$PROJECT_ROOT" -type d -name target -prune -o -type f \( -name "*.rs" -o -name "*.md" -o -name "*.toml" -o -name "*.lock" -o -name "*.sh" \) ! -path "*/target/*" -print | sort)

# Build Table of Contents and metadata
for file in "${FILES[@]}"; do
    rel_path="${file#./}"
    # Use platform-appropriate stat command
    if [[ "$OSTYPE" == "darwin"* ]]; then
        size=$(stat -f%z "$file")
        mtime=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$file")
    else
        size=$(stat -c%s "$file")
        mtime=$(stat -c%y "$file" | cut -d'.' -f1)
    fi
    echo "  - $rel_path (size: $size bytes, modified: $mtime)" >>"$TMP_TOC"
    echo "$rel_path|$size|$mtime" >>"$TMP_META"
done

FILE_COUNT=${#FILES[@]}
TOTAL_SIZE=$(awk -F'|' '{s+=$2} END {print s}' "$TMP_META")

# Output instructions, summary, and TOC
cat <<EOF >"$OUTPUT_FILE"
# ignis CODE BASE: USAGE INSTRUCTIONS
#
# This file is a single-file snapshot of the entire ignis codebase.
# It includes Rust source files, documentation, configuration files, and scripts.
# It is structured to allow both humans and AI models to efficiently locate, parse, and analyze individual source files.
#
# STRUCTURE:
# - TABLE OF CONTENTS: Lists all files, with section markers for fast lookup.
# - FILE SECTIONS: Each file begins with "==== FILE: <relative path> ====".
#   Each file includes metadata: file size and last modified date.
# - All content is plain text; syntax highlighting is not included.
#
# INSTRUCTIONS FOR AI (AND HUMANS):
# - Use the TABLE OF CONTENTS at the top to find file locations and jump to "==== FILE: <path> ====" markers.
# - Each file section is clearly delimited for safe splitting and parsing.
# - Ignore directory tree structure unless needed for navigation/context.
# - No part of this file should be executed directly; it is for reference and analysis only.
#
# CODEBASE SNAPSHOT
#
# Each file begins with:    ==== FILE: <relative/path> ====
# Each file ends with:      ==== END FILE: <relative/path> ====
# The table of contents below lists every file, size, and modified date.
# Use the TOC to locate files, then search for the matching section marker.
# This file is for reference, indexing, or programmatic parsing—do not execute.
#
# Summary, table of contents, and full codebase sections follow.
#
# SUMMARY
#   - Project Root: $PROJECT_ROOT
#   - File Count: $FILE_COUNT
#   - Total Code Size: $TOTAL_SIZE bytes
#
# TABLE OF CONTENTS
$(cat "$TMP_TOC")
# END TABLE OF CONTENTS

EOF

# Optionally, output the directory tree
echo -e "# DIRECTORY STRUCTURE\n" >>"$OUTPUT_FILE"
if command -v tree >/dev/null 2>&1; then
    tree "$PROJECT_ROOT" -I 'target' >>"$OUTPUT_FILE"
else
    find "$PROJECT_ROOT" -type d -name target -prune -o -print | sed 's/[^-][^\/]*\//   |/g;s/|\([^ ]\)/|-- \1/' >>"$OUTPUT_FILE"
fi

echo -e "\n# FILES BEGIN BELOW\n" >>"$OUTPUT_FILE"

# Output files with section markers and metadata
for file in "${FILES[@]}"; do
    rel_path="${file#./}"
    # Use platform-appropriate stat command
    if [[ "$OSTYPE" == "darwin"* ]]; then
        size=$(stat -f%z "$file")
        mtime=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$file")
    else
        size=$(stat -c%s "$file")
        mtime=$(stat -c%y "$file" | cut -d'.' -f1)
    fi
    echo "==== FILE: $rel_path ====" >>"$OUTPUT_FILE"
    echo "# size: $size bytes | modified: $mtime" >>"$OUTPUT_FILE"
    echo "" >>"$OUTPUT_FILE"
    cat "$file" >>"$OUTPUT_FILE"
    echo -e "\n==== END FILE: $rel_path ====\n" >>"$OUTPUT_FILE"
done

rm -f "$TMP_TOC" "$TMP_META"

echo "Code collection complete. Output saved to $OUTPUT_FILE"
