#!/bin/bash

MEMORY_DIR="/home/amr/.openclaw/workspace/memory"
MEMEX_DAILY_DIR="/home/amr/.openclaw/workspace/memex/1_daily"

mkdir -p "$MEMEX_DAILY_DIR"

for md_file in "$MEMORY_DIR"/*.md; do
    if [ -f "$md_file" ]; then
        filename=$(basename -- "$md_file")
        base="${filename%.*}" # e.g., 2026-03-18
        org_file="$MEMEX_DAILY_DIR/$base.org"

        echo "Processing $filename..."

        # Read the full content of the MD file
        full_md_content=$(cat "$md_file")

        # Convert ## Heading to * Heading and capture the first line as the main heading
        first_line_org_heading=$(echo "$full_md_content" | head -n 1 | sed -E 's/^## (.*)$/* \1/g')
        rest_of_content=$(echo "$full_md_content" | tail -n +2) # Get all lines after the first heading

        # Generate a formal Org-mode timestamp for :CREATED: property
        current_date_day=$(date "+%Y-%m-%d %a %H:%M") # e.g., 2026-03-19 Thu 08:45
        created_property="\n:PROPERTIES:\n:CREATED: [${current_date_day}]\n:END:\n"

        # Combine the new Org-mode heading, properties, and original content
        # Also add the "Captured from" header as a visible marker before the main content
        append_header="* Captured from memory/${filename} on $(date "+%Y-%m-%d %H:%M")\n"

        final_org_content="${first_line_org_heading}${created_property}${append_header}${rest_of_content}"


        if [ ! -f "$org_file" ]; then
            echo "Creating new Org file $org_file and adding content."
            echo -e "${final_org_content}" > "$org_file"
        else
            echo "Appending content from $filename to existing Org file $org_file."
            # When appending, we don't want to re-add the main heading (e.g., * 2026-03-18)
            # Instead, we append the "Captured from" header, properties, and the rest of the content
            echo -e "\n${append_header}${created_property}${rest_of_content}" >> "$org_file"
        fi
    fi
done
