#!/usr/bin/env bash
# ============================================================
# taskmaster-export.sh — Export Taskmaster data to migration bundle
#
# Reads a Taskmaster installation and produces a standardised
# migration bundle directory that migrate-import.sh can consume.
#
# Usage:
#   bash taskmaster-export.sh <config-dir> <workspace-dir> <output-dir>
#
# Arguments:
#   config-dir    — Taskmaster config directory (e.g., ~/.taskmaster)
#   workspace-dir — Taskmaster workspace directory (e.g., ~/taskmaster)
#   output-dir    — Output directory for the migration bundle
#
# Example (run on the Taskmaster Pi via SSH):
#   ssh admin@muvin.local
#   bash /path/to/taskmaster-export.sh ~/.taskmaster ~/taskmaster ~/bundle
# ============================================================

set -euo pipefail

# ------------------------------------------------------------------
# Arguments
# ------------------------------------------------------------------
if [ $# -lt 3 ]; then
  echo "[export] ERROR: Usage: taskmaster-export.sh <config-dir> <workspace-dir> <output-dir>"
  exit 2
fi

CONFIG_DIR="$1"
WORKSPACE_DIR="$2"
OUTPUT_DIR="$3"

TASKMASTER_JSON="$CONFIG_DIR/taskmaster.json"

if [ ! -f "$TASKMASTER_JSON" ]; then
  echo "[export] ERROR: taskmaster.json not found at $TASKMASTER_JSON"
  echo "[export] ERROR: Is $CONFIG_DIR a Taskmaster config directory?"
  exit 1
fi

if [ ! -d "$WORKSPACE_DIR" ]; then
  echo "[export] ERROR: Workspace directory not found at $WORKSPACE_DIR"
  exit 1
fi

echo "[export] Source config:    $CONFIG_DIR"
echo "[export] Source workspace: $WORKSPACE_DIR"
echo "[export] Output bundle:    $OUTPUT_DIR"

# ------------------------------------------------------------------
# Create bundle directory structure
# ------------------------------------------------------------------
mkdir -p "$OUTPUT_DIR"/{identity,contacts,memory/shared,memory/admin,conversations/admin,conversations/users,conversations/groups,media/admin,media/public,automations}

# ------------------------------------------------------------------
# 1. Manifest
# ------------------------------------------------------------------
HOSTNAME_VAL=$(hostname 2>/dev/null || echo "unknown")
VERSION=$(python3 -c "import json; print(json.load(open('$TASKMASTER_JSON'))['meta']['lastTouchedVersion'])" 2>/dev/null || echo "unknown")
EXPORT_TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)

# Extract customer name from USER.md if it exists
USER_MD="$WORKSPACE_DIR/agents/admin/USER.md"
CUSTOMER_NAME="unknown"
if [ -f "$USER_MD" ]; then
  # Parse "**Name:** Adam Mackay" from USER.md
  CUSTOMER_NAME=$(grep -oP '\*\*Name:\*\*\s*\K.*' "$USER_MD" 2>/dev/null || \
                  sed -n 's/.*\*\*Name:\*\* *//p' "$USER_MD" | head -1)
  [ -z "$CUSTOMER_NAME" ] && CUSTOMER_NAME="unknown"
fi

cat > "$OUTPUT_DIR/manifest.json" << MANIFEST_EOF
{
  "source": "taskmaster",
  "version": "$VERSION",
  "hostname": "$HOSTNAME_VAL",
  "customer": "$CUSTOMER_NAME",
  "exportedAt": "$EXPORT_TS"
}
MANIFEST_EOF
echo "[export] manifest.json written (version=$VERSION, customer=$CUSTOMER_NAME)"

# ------------------------------------------------------------------
# 2. Identity — owner, agents, PINs
# ------------------------------------------------------------------

# Owner identity from USER.md
if [ -f "$USER_MD" ]; then
  # Parse structured fields from USER.md markdown
  OWNER_NAME="$CUSTOMER_NAME"
  OWNER_PHONE=$(sed -n 's/.*\*\*Phone:\*\* *//p' "$USER_MD" | head -1)
  OWNER_BUSINESS=$(sed -n 's/.*\*\*Business:\*\* *//p' "$USER_MD" | head -1)
  OWNER_LOCATION=$(sed -n 's/.*\*\*Location:\*\* *//p' "$USER_MD" | head -1)
  OWNER_HOURS=$(sed -n 's/.*\*\*Working hours:\*\* *//p' "$USER_MD" | head -1)

  python3 - "$OWNER_NAME" "$OWNER_PHONE" "$OWNER_BUSINESS" "$OWNER_LOCATION" "$OWNER_HOURS" "$OUTPUT_DIR" <<'PYEOF'
import json, sys
name, phone, business, location, hours, out = sys.argv[1:7]
d = {}
for k, v in [('name',name),('phone',phone),('business',business),('location',location),('hours',hours)]:
    if v: d[k] = v
json.dump(d, open(f'{out}/identity/owner.json','w'), indent=2)
print(f'[export] identity/owner.json written ({d.get("name","unknown")})')
PYEOF
else
  echo "[export] WARN: USER.md not found at $USER_MD — owner identity skipped"
fi

# Agent names from IDENTITY.md files
ADMIN_IDENTITY="$WORKSPACE_DIR/agents/admin/IDENTITY.md"
PUBLIC_IDENTITY="$WORKSPACE_DIR/agents/public/IDENTITY.md"
ADMIN_NAME=$(sed -n 's/.*\*\*Name:\*\* *//p' "$ADMIN_IDENTITY" 2>/dev/null | head -1 || echo "")
PUBLIC_NAME=$(sed -n 's/.*\*\*Name:\*\* *//p' "$PUBLIC_IDENTITY" 2>/dev/null | head -1 || echo "")

python3 -c "
import json
d = {'admin': '${ADMIN_NAME:-unknown}', 'public': '${PUBLIC_NAME:-unknown}'}
json.dump(d, open('$OUTPUT_DIR/identity/agents.json','w'), indent=2)
print(f'[export] identity/agents.json written (admin={d[\"admin\"]}, public={d[\"public\"]})')
"

# PINs from taskmaster.json access section
python3 -c "
import json
try:
    d = json.load(open('$TASKMASTER_JSON'))
    access = d.get('access', {})
    pins = {
        'masterPin': access.get('masterPin'),
        'workspacePins': access.get('pins', {})
    }
    # Only write if there are actual PINs
    if pins['masterPin'] or pins['workspacePins']:
        json.dump(pins, open('$OUTPUT_DIR/identity/pins.json','w'), indent=2)
        print(f'[export] identity/pins.json written (masterPin={\"set\" if pins[\"masterPin\"] else \"none\"})')
    else:
        print('[export] identity/pins.json skipped (no PINs configured)')
except Exception as e:
    print(f'[export] WARN: could not extract PINs: {e}')
"

# ------------------------------------------------------------------
# 3. Contacts — from memory/users/{phone}/ directories
# ------------------------------------------------------------------
USERS_DIR="$WORKSPACE_DIR/memory/users"
CONTACT_COUNT=0
ANON_SKIP_COUNT=0

if [ -d "$USERS_DIR" ]; then
  for USER_DIR in "$USERS_DIR"/*/; do
    [ -d "$USER_DIR" ] || continue
    USER_KEY=$(basename "$USER_DIR")

    # Skip anonymous users — no phone number, no useful identity
    if [[ "$USER_KEY" == anon-* ]]; then
      ANON_SKIP_COUNT=$((ANON_SKIP_COUNT + 1))
      continue
    fi

    PROFILE="$USER_DIR/profile.md"
    if [ -f "$PROFILE" ]; then
      # Extract name from first markdown heading or first bold field
      python3 -c "
import json, re, sys

profile_path = '$PROFILE'
user_key = '$USER_KEY'

with open(profile_path, 'r') as f:
    content = f.read()

# Extract givenName from first heading (# Name)
heading = re.search(r'^#\s+(.+)', content, re.MULTILINE)
given_name = heading.group(1).strip() if heading else None

# If heading is generic like 'Customer Profile', try **Name:** field
if given_name and given_name.lower() in ('customer profile', 'profile', 'user profile'):
    name_field = re.search(r'\*\*(?:Name|First name):\*\*\s*(.+)', content)
    given_name = name_field.group(1).strip() if name_field else None

# Extract phone from profile or use directory name
phone_field = re.search(r'\*\*Phone:\*\*\s*(.+)', content)
phone = phone_field.group(1).strip() if phone_field else user_key

# Extract role
role_field = re.search(r'\*\*Role:\*\*\s*(.+)', content)
role = role_field.group(1).strip() if role_field else None

# Extract location
loc_field = re.search(r'\*\*Location:\*\*\s*(.+)', content)
location = loc_field.group(1).strip() if loc_field else None

contact = {
    'telephone': phone,
    'source': 'taskmaster-migration'
}

if given_name and given_name != 'Customer Profile':
    # Split name into given/family if it contains a space
    parts = given_name.split(' ', 1)
    contact['givenName'] = parts[0]
    if len(parts) > 1:
        contact['familyName'] = parts[1]
else:
    # No name — use phone as identifier, skip givenName
    # (import will skip contacts without givenName)
    pass

if role:
    contact['jobTitle'] = role
if location:
    contact['location'] = location

# Include raw profile for reference
contact['_profileContent'] = content

# Write contact JSON
safe_key = user_key.replace('+', 'plus-')
json.dump(contact, open(f'$OUTPUT_DIR/contacts/{safe_key}.json', 'w'), indent=2)
has_name = 'givenName' in contact
print(f'[export] contact: {user_key} ({contact.get(\"givenName\", \"NO NAME\")})', file=sys.stderr)
sys.exit(0 if has_name else 0)
" 2>&1
    else
      # No profile.md — create minimal contact from directory name
      python3 -c "
import json
contact = {'telephone': '$USER_KEY', 'source': 'taskmaster-migration'}
safe_key = '$USER_KEY'.replace('+', 'plus-')
json.dump(contact, open(f'$OUTPUT_DIR/contacts/{safe_key}.json', 'w'), indent=2)
print(f'[export] contact: $USER_KEY (no profile.md — phone only)')
"
    fi
    CONTACT_COUNT=$((CONTACT_COUNT + 1))
  done
fi
echo "[export] contacts: $CONTACT_COUNT exported, $ANON_SKIP_COUNT anonymous skipped"

# ------------------------------------------------------------------
# 4. Memory — shared and admin knowledge files
# ------------------------------------------------------------------
SHARED_DIR="$WORKSPACE_DIR/memory/shared"
SHARED_COUNT=0
if [ -d "$SHARED_DIR" ]; then
  # Copy all files except cron-activity and media (media goes to media/public)
  find "$SHARED_DIR" -maxdepth 1 -type f | while read -r f; do
    cp "$f" "$OUTPUT_DIR/memory/shared/"
    echo "[export] memory/shared: $(basename "$f")"
  done
  SHARED_COUNT=$(find "$OUTPUT_DIR/memory/shared" -type f | wc -l | tr -d ' ')
fi
echo "[export] memory/shared: $SHARED_COUNT files"

ADMIN_MEMORY="$WORKSPACE_DIR/agents/admin/memory/admin"
ADMIN_MEM_COUNT=0
if [ -d "$ADMIN_MEMORY" ]; then
  # Copy recursively, excluding cron-activity (Loop diary logs) and media (goes to media/)
  rsync -a --exclude='cron-activity' --exclude='media' "$ADMIN_MEMORY/" "$OUTPUT_DIR/memory/admin/" 2>/dev/null || \
    find "$ADMIN_MEMORY" -type f -not -path '*/cron-activity/*' -not -path '*/media/*' | while read -r f; do
      REL="${f#$ADMIN_MEMORY/}"
      mkdir -p "$OUTPUT_DIR/memory/admin/$(dirname "$REL")"
      cp "$f" "$OUTPUT_DIR/memory/admin/$REL"
    done
  ADMIN_MEM_COUNT=$(find "$OUTPUT_DIR/memory/admin" -type f 2>/dev/null | wc -l | tr -d ' ')
fi
echo "[export] memory/admin: $ADMIN_MEM_COUNT files"

# Public agent memory
PUBLIC_MEMORY="$WORKSPACE_DIR/agents/admin/memory/public"
if [ -d "$PUBLIC_MEMORY" ]; then
  mkdir -p "$OUTPUT_DIR/memory/public"
  cp -r "$PUBLIC_MEMORY"/* "$OUTPUT_DIR/memory/public/" 2>/dev/null || true
  PUB_COUNT=$(find "$OUTPUT_DIR/memory/public" -type f 2>/dev/null | wc -l | tr -d ' ')
  echo "[export] memory/public: $PUB_COUNT files"
fi

# ------------------------------------------------------------------
# 5. Conversations — admin, per-user, per-group
# ------------------------------------------------------------------

# Admin conversations
ADMIN_CONVOS="$ADMIN_MEMORY/conversations"
ADMIN_CONVO_COUNT=0
if [ -d "$ADMIN_CONVOS" ]; then
  cp "$ADMIN_CONVOS"/*.md "$OUTPUT_DIR/conversations/admin/" 2>/dev/null || true
  ADMIN_CONVO_COUNT=$(find "$OUTPUT_DIR/conversations/admin" -type f 2>/dev/null | wc -l | tr -d ' ')
fi
echo "[export] conversations/admin: $ADMIN_CONVO_COUNT files"

# Per-user conversations
USER_CONVO_COUNT=0
if [ -d "$USERS_DIR" ]; then
  for USER_DIR in "$USERS_DIR"/*/; do
    [ -d "$USER_DIR" ] || continue
    USER_KEY=$(basename "$USER_DIR")
    CONVO_DIR="$USER_DIR/conversations"
    if [ -d "$CONVO_DIR" ] && [ "$(ls -A "$CONVO_DIR" 2>/dev/null)" ]; then
      SAFE_KEY=$(echo "$USER_KEY" | sed 's/+/plus-/g')
      mkdir -p "$OUTPUT_DIR/conversations/users/$SAFE_KEY"
      cp "$CONVO_DIR"/*.md "$OUTPUT_DIR/conversations/users/$SAFE_KEY/" 2>/dev/null || true
      USER_CONVO_COUNT=$((USER_CONVO_COUNT + 1))
    fi
  done
fi
echo "[export] conversations/users: $USER_CONVO_COUNT directories"

# Group conversations
GROUP_DIR="$WORKSPACE_DIR/memory/groups"
GROUP_CONVO_COUNT=0
if [ -d "$GROUP_DIR" ]; then
  for GRP in "$GROUP_DIR"/*/; do
    [ -d "$GRP" ] || continue
    GRP_ID=$(basename "$GRP")
    CONVO_DIR="$GRP/conversations"
    if [ -d "$CONVO_DIR" ] && [ "$(ls -A "$CONVO_DIR" 2>/dev/null)" ]; then
      mkdir -p "$OUTPUT_DIR/conversations/groups/$GRP_ID"
      cp "$CONVO_DIR"/*.md "$OUTPUT_DIR/conversations/groups/$GRP_ID/" 2>/dev/null || true
      GROUP_CONVO_COUNT=$((GROUP_CONVO_COUNT + 1))
    fi
    # Group member files
    MEMBERS_DIR="$GRP/members"
    if [ -d "$MEMBERS_DIR" ] && [ "$(ls -A "$MEMBERS_DIR" 2>/dev/null)" ]; then
      mkdir -p "$OUTPUT_DIR/conversations/groups/$GRP_ID/members"
      cp "$MEMBERS_DIR"/* "$OUTPUT_DIR/conversations/groups/$GRP_ID/members/" 2>/dev/null || true
    fi
  done
fi
echo "[export] conversations/groups: $GROUP_CONVO_COUNT directories"

# ------------------------------------------------------------------
# 6. Media — admin uploads and shared media
# ------------------------------------------------------------------
ADMIN_UPLOADS="$WORKSPACE_DIR/agents/admin/uploads"
ADMIN_MEDIA_COUNT=0
if [ -d "$ADMIN_UPLOADS" ] && [ "$(ls -A "$ADMIN_UPLOADS" 2>/dev/null)" ]; then
  cp "$ADMIN_UPLOADS"/* "$OUTPUT_DIR/media/admin/" 2>/dev/null || true
  ADMIN_MEDIA_COUNT=$(find "$OUTPUT_DIR/media/admin" -type f 2>/dev/null | wc -l | tr -d ' ')
fi
echo "[export] media/admin: $ADMIN_MEDIA_COUNT files"

# Shared media (e.g., PDFs in memory/shared/media/)
SHARED_MEDIA="$WORKSPACE_DIR/memory/shared/media"
PUBLIC_MEDIA_COUNT=0
if [ -d "$SHARED_MEDIA" ] && [ "$(ls -A "$SHARED_MEDIA" 2>/dev/null)" ]; then
  cp "$SHARED_MEDIA"/* "$OUTPUT_DIR/media/public/" 2>/dev/null || true
  PUBLIC_MEDIA_COUNT=$(find "$OUTPUT_DIR/media/public" -type f 2>/dev/null | wc -l | tr -d ' ')
fi
echo "[export] media/public: $PUBLIC_MEDIA_COUNT files"

# Admin memory media
ADMIN_MEDIA_DIR="$ADMIN_MEMORY/media"
if [ -d "$ADMIN_MEDIA_DIR" ] && [ "$(ls -A "$ADMIN_MEDIA_DIR" 2>/dev/null)" ]; then
  cp "$ADMIN_MEDIA_DIR"/* "$OUTPUT_DIR/media/admin/" 2>/dev/null || true
  # Recount after adding
  ADMIN_MEDIA_COUNT=$(find "$OUTPUT_DIR/media/admin" -type f 2>/dev/null | wc -l | tr -d ' ')
  echo "[export] media/admin (updated with memory/admin/media): $ADMIN_MEDIA_COUNT files"
fi

# ------------------------------------------------------------------
# 7. Automations — workflow definitions (not cron-activity logs)
# ------------------------------------------------------------------
WORKFLOWS_DIR="$ADMIN_MEMORY/workflows"
AUTOMATION_COUNT=0
if [ -d "$WORKFLOWS_DIR" ] && [ "$(ls -A "$WORKFLOWS_DIR" 2>/dev/null)" ]; then
  cp "$WORKFLOWS_DIR"/* "$OUTPUT_DIR/automations/" 2>/dev/null || true
  AUTOMATION_COUNT=$(find "$OUTPUT_DIR/automations" -type f 2>/dev/null | wc -l | tr -d ' ')
fi
echo "[export] automations: $AUTOMATION_COUNT workflow definitions"

# ------------------------------------------------------------------
# Summary
# ------------------------------------------------------------------
TOTAL_CONTACTS=$CONTACT_COUNT
TOTAL_MEMORY=$((SHARED_COUNT + ADMIN_MEM_COUNT))
TOTAL_MEDIA=$((ADMIN_MEDIA_COUNT + PUBLIC_MEDIA_COUNT))
TOTAL_CONVOS=$((ADMIN_CONVO_COUNT + USER_CONVO_COUNT + GROUP_CONVO_COUNT))

echo ""
echo "[export] =================================================="
echo "[export] Bundle complete: $OUTPUT_DIR"
echo "[export]   Contacts:      $TOTAL_CONTACTS (+ $ANON_SKIP_COUNT anonymous skipped)"
echo "[export]   Memory files:  $TOTAL_MEMORY"
echo "[export]   Media files:   $TOTAL_MEDIA"
echo "[export]   Conversations: $TOTAL_CONVOS directories"
echo "[export]   Automations:   $AUTOMATION_COUNT"
echo "[export] =================================================="
