#!/usr/bin/env bash
# create-speaker-profile -- Create ICM nested folder profile for a new speaker
#
# Usage: create-speaker-profile <room_dir> <speaker-slug> <speaker-role> <display-name>
# Example: create-speaker-profile room/ tyler-chen researcher "Tyler Chen"
#
# Creates the ICM nested folder structure under room/team/{role-plural}/{speaker-slug}/
# with PROFILE.md, insights/, advice/, connections/, concerns/ subdirectories.
#
# Exit 0 on success, exit 1 on failure (e.g., directory already exists, invalid args)

set -euo pipefail

# --help flag
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
  cat <<'USAGE'
create-speaker-profile -- Create ICM nested folder profile for a new speaker

USAGE:
  create-speaker-profile <room_dir> <speaker-slug> <speaker-role> <display-name>

ARGUMENTS:
  room_dir      Path to the room directory (e.g., room/)
  speaker-slug  Lowercase hyphenated name (e.g., tyler-chen)
  speaker-role  One of: mentor, researcher, team-member, investor, advisor,
                customer, founder, partner, domain-expert, government,
                competitor, unknown
  display-name  Full display name in quotes (e.g., "Tyler Chen")

EXAMPLES:
  create-speaker-profile room/ tyler-chen researcher "Tyler Chen"
  create-speaker-profile room/ lawrence-aronhime mentor "Prof. Lawrence Aronhime"

OUTPUT:
  Prints the created profile directory path to stdout.
  Exit 0 on success, exit 1 on failure.
USAGE
  exit 0
fi

# ---------------------------------------------------------------------------
# Phase 80 extension: --layout=import --role-bucket=<bucket>
#
# When --layout=import is passed, materialize the COMPLETE team profile tree
# per Decision 15 (ROOM.md everywhere) + Decision 16 (nested artifact layout):
#   team/{role-bucket}/{slug}/{slug}.md
#   team/{role-bucket}/{slug}/ROOM.md
#   team/{role-bucket}/{slug}/mentions.md
#   team/{role-bucket}/{slug}/responsibilities.md
#   team/{role-bucket}/{slug}/contracts/ROOM.md
#
# Usage: create-speaker-profile <room_dir> --layout=import --role-bucket=core-team <slug> <display-name>
#
# Legacy 4-arg invocations are unchanged.
# ---------------------------------------------------------------------------

LAYOUT=""
ROLE_BUCKET=""
POSITIONAL=()
for arg in "$@"; do
  case "$arg" in
    --layout=*)      LAYOUT="${arg#--layout=}" ;;
    --role-bucket=*) ROLE_BUCKET="${arg#--role-bucket=}" ;;
    *)               POSITIONAL+=("$arg") ;;
  esac
done

if [[ "$LAYOUT" == "import" ]]; then
  if [[ -z "$ROLE_BUCKET" ]]; then
    echo "ERROR: --layout=import requires --role-bucket=<bucket>" >&2
    exit 1
  fi
  if [[ ${#POSITIONAL[@]} -lt 3 ]]; then
    echo "ERROR: --layout=import requires: <room_dir> <slug> <display-name>" >&2
    exit 1
  fi
  ROOM_DIR="${POSITIONAL[0]}"
  IMPORT_SLUG="${POSITIONAL[1]}"
  IMPORT_DISPLAY="${POSITIONAL[2]}"

  if [[ ! -d "$ROOM_DIR" ]]; then
    echo "ERROR: Room directory does not exist: $ROOM_DIR" >&2
    exit 1
  fi

  PROFILE_DIR="${ROOM_DIR}/team/${ROLE_BUCKET}/${IMPORT_SLUG}"
  mkdir -p "${PROFILE_DIR}/contracts"

  TODAY=$(date +%Y-%m-%d)

  cat > "${PROFILE_DIR}/ROOM.md" <<ROOMEOF
---
icm_layer: 0
type: speaker-profile
speaker: ${IMPORT_DISPLAY}
role_bucket: ${ROLE_BUCKET}
generated_by: phase-80-vault-import
---
# ${IMPORT_DISPLAY}

${ROLE_BUCKET} member. ICM Layer 0 identity for this person folder.

## Contents
- [[${IMPORT_SLUG}.md]] main profile
- [[mentions.md]] all wikilinked mentions across the room
- [[responsibilities.md]] responsibilities
- [[contracts/]] contracts and agreements
ROOMEOF

  cat > "${PROFILE_DIR}/${IMPORT_SLUG}.md" <<PROFEOF
---
name: ${IMPORT_DISPLAY}
slug: ${IMPORT_SLUG}
role_bucket: ${ROLE_BUCKET}
status: active
created_by: phase-80-vault-import
last_updated: ${TODAY}
---

# ${IMPORT_DISPLAY}

**Role bucket:** ${ROLE_BUCKET}

## Context

(populated from manifest + mentions during enrichment)

## Responsibilities

See [[responsibilities.md]].

## Mentions

See [[mentions.md]].
PROFEOF

  cat > "${PROFILE_DIR}/mentions.md" <<MENTEOF
---
type: mentions-index
person: ${IMPORT_DISPLAY}
---
# Mentions of ${IMPORT_DISPLAY}

(empty stub -- enricher populates this with wikilinked references across the room)
MENTEOF

  cat > "${PROFILE_DIR}/responsibilities.md" <<RESPEOF
---
type: responsibilities
person: ${IMPORT_DISPLAY}
---
# Responsibilities -- ${IMPORT_DISPLAY}

(empty stub)
RESPEOF

  cat > "${PROFILE_DIR}/contracts/ROOM.md" <<CROOMEOF
---
icm_layer: 0
type: contracts-folder
person: ${IMPORT_DISPLAY}
---
# Contracts -- ${IMPORT_DISPLAY}

Contracts and agreements involving this person.
CROOMEOF

  echo "$PROFILE_DIR"
  exit 0
fi

# ---------------------------------------------------------------------------
# Legacy path (unchanged): positional 4-arg invocation
# ---------------------------------------------------------------------------

# Validate arguments
if [[ $# -lt 4 ]]; then
  echo "ERROR: 4 arguments required: room_dir, speaker-slug, speaker-role, display-name" >&2
  echo "Run with --help for usage." >&2
  exit 1
fi

ROOM_DIR="$1"
SPEAKER_SLUG="$2"
SPEAKER_ROLE="$3"
DISPLAY_NAME="$4"

# Validate room_dir exists
if [[ ! -d "$ROOM_DIR" ]]; then
  echo "ERROR: Room directory does not exist: $ROOM_DIR" >&2
  exit 1
fi

# Map role to plural directory name
case "$SPEAKER_ROLE" in
  mentor)        ROLE_PLURAL="mentors" ;;
  researcher)    ROLE_PLURAL="researchers" ;;
  team-member)   ROLE_PLURAL="members" ;;
  investor)      ROLE_PLURAL="investors" ;;
  advisor)       ROLE_PLURAL="advisors" ;;
  customer)      ROLE_PLURAL="customers" ;;
  founder)       ROLE_PLURAL="founders" ;;
  partner)       ROLE_PLURAL="partners" ;;
  domain-expert) ROLE_PLURAL="domain-experts" ;;
  government)    ROLE_PLURAL="government" ;;
  competitor)    ROLE_PLURAL="competitors" ;;
  unknown)       ROLE_PLURAL="contacts" ;;
  *)
    echo "ERROR: Invalid role '$SPEAKER_ROLE'. Must be one of: mentor, researcher, team-member, investor, advisor, customer, founder, partner, domain-expert, government, competitor, unknown" >&2
    exit 1
    ;;
esac

# Build profile directory path
PROFILE_DIR="${ROOM_DIR}/team/${ROLE_PLURAL}/${SPEAKER_SLUG}"

# Check if profile already exists
if [[ -d "$PROFILE_DIR" ]]; then
  echo "ERROR: Profile already exists at $PROFILE_DIR" >&2
  exit 1
fi

# Create directory structure (Phase 6 legacy compat -- subfolders kept for backward compat)
mkdir -p "${PROFILE_DIR}/insights"
mkdir -p "${PROFILE_DIR}/advice"
mkdir -p "${PROFILE_DIR}/connections"
mkdir -p "${PROFILE_DIR}/concerns"

# ICM Layer 0 -- every directory gets identity (Key Decision #15)
cat > "${PROFILE_DIR}/ROOM.md" <<ROOMEOF
---
icm_layer: 0
type: speaker-profile
speaker: ${DISPLAY_NAME}
role: ${SPEAKER_ROLE}
---
# ${DISPLAY_NAME} -- Speaker Profile Directory

${SPEAKER_ROLE} in the venture. Profile and contribution tracking.

## Contents
| File | Purpose |
|------|---------|
| PROFILE.md | Full profile with expertise, relationships, role |
| insights/ | Insights attributed to this speaker |
| advice/ | Advice given by this speaker |
| connections/ | Relationship map for this speaker |
| concerns/ | Concerns raised by this speaker |

## Note
Contributions are tracked via computed backlinks in PROFILE.md (run by compute-team).
Do not manually file artifacts here -- use the meeting filing pipeline.
ROOMEOF

# Get today's date
TODAY=$(date +%Y-%m-%d)

# Create PROFILE.md with Phase 7 extended schema
cat > "${PROFILE_DIR}/PROFILE.md" <<EOF
---
name: ${DISPLAY_NAME}
roles:
  - ${SPEAKER_ROLE}
primary_role: ${SPEAKER_ROLE}
role: ${SPEAKER_ROLE}
status: active
last_active: ${TODAY}
affiliation: (unknown -- pending research)
first_meeting: ${TODAY}
meetings_attended: 1
created_by: file-meeting
research_status: pending
last_updated: ${TODAY}
---

# ${DISPLAY_NAME} (${SPEAKER_ROLE})

**Role:** ${SPEAKER_ROLE} | **Affiliation:** Unknown

## Context

[To be filled after proactive research]

## Expertise

[To be inferred from meeting contributions]

## Contributions

*(no contributions filed yet)*

<!-- Computed by compute-team. Rows are wikilinked at file-meeting time. -->
EOF

# NATIVE-04: post-process the freshly-written PROFILE.md through wikilink-file.cjs
# so any team name mentions, section references, and meeting links arrive
# pre-wikilinked. Self-links to this profile are suppressed via ownProfilePath
# inside wikilink-builder. Soft-fails: a wikilink error must never break profile
# creation -- the file is still valid Markdown without the [[...]] decorations.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WIKILINK_SCRIPT="${SCRIPT_DIR}/wikilink-file.cjs"
PROFILE_FILE="${PROFILE_DIR}/PROFILE.md"
if [[ -f "$WIKILINK_SCRIPT" ]]; then
  if ! node "$WIKILINK_SCRIPT" "$ROOM_DIR" "$PROFILE_FILE" >/dev/null 2>&1; then
    echo "[create-speaker-profile] wikilink-file pass failed (non-fatal) for $PROFILE_FILE" >&2
  fi
fi

# Output the created path
echo "$PROFILE_DIR"
exit 0
