#!/usr/bin/env bash
# Seed disseminations data via HTTP API.
# Usage: API_URL=http://localhost:8000 EMAIL=admin@gmail.com PASSWORD=687654 ./seed_disseminations.sh
set -euo pipefail

API="${API_URL:-http://localhost:8000}"
EMAIL="${EMAIL:-admin@gmail.com}"
PASSWORD="${PASSWORD:-687654}"
COOKIES=$(mktemp)
trap 'rm -f "$COOKIES"' EXIT

echo "→ Fetching CSRF cookie"
curl -fsS -c "$COOKIES" "$API/api/auth/csrf/" >/dev/null

CSRF=$(awk '/csrftoken/ {print $7}' "$COOKIES")
if [[ -z "$CSRF" ]]; then
  echo "Failed to obtain CSRF token" >&2
  exit 1
fi

echo "→ Logging in as $EMAIL"
curl -fsS -b "$COOKIES" -c "$COOKIES" \
  -H "Content-Type: application/json" \
  -H "X-CSRFToken: $CSRF" \
  -H "Referer: $API/" \
  -d "{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\"}" \
  "$API/api/auth/login/" >/dev/null

# Refresh CSRF after login (session may have rotated)
CSRF=$(awk '/csrftoken/ {print $7}' "$COOKIES")

post() {
  local path="$1"
  local body="$2"
  curl -fsS -b "$COOKIES" -c "$COOKIES" \
    -H "Content-Type: application/json" \
    -H "X-CSRFToken: $CSRF" \
    -H "Referer: $API/" \
    -d "$body" \
    "$API$path"
  echo
}

extract_id() { python3 -c "import sys,json;print(json.loads(sys.stdin.read())['id'])"; }

echo
echo "─── Channels ───────────────────────────────────"
declare -A CH_IDS
seed_channel() {
  local platform="$1" name="$2" handle="$3" url="$4"
  local body="{\"name\":\"$name\",\"platform\":\"$platform\",\"handle\":\"$handle\",\"profile_url\":\"$url\",\"active\":true}"
  local id; id=$(post "/api/disseminations/channels/" "$body" | extract_id)
  CH_IDS[$platform]="$id"
  echo "  + $platform: $name ($id)"
}
seed_channel twitter   "CSIS Indonesia (X)"     "@csisindonesia"     "https://twitter.com/csisindonesia"
seed_channel linkedin  "CSIS Indonesia LinkedIn" "csis-indonesia"   "https://www.linkedin.com/company/csis-indonesia"
seed_channel instagram "CSIS on Instagram"      "@csisindonesia"     "https://instagram.com/csisindonesia"
seed_channel facebook  "CSIS Facebook Page"     "CSISIndonesia"      "https://facebook.com/CSISIndonesia"
seed_channel youtube   "CSIS YouTube"           "csisindonesia"      "https://youtube.com/@csisindonesia"
seed_channel threads   "CSIS Threads"           "@csisindonesia"     "https://threads.net/@csisindonesia"

echo
echo "─── Campaigns ──────────────────────────────────"
declare -A CAM_IDS
seed_campaign() {
  local name="$1" objective="$2" color="$3" start="$4" end="$5"
  local body="{\"name\":\"$name\",\"objective\":\"$objective\",\"description\":\"\",\"color\":\"$color\",\"start_date\":\"$start\",\"end_date\":\"$end\"}"
  local id; id=$(post "/api/disseminations/campaigns/" "$body" | extract_id)
  CAM_IDS["$name"]="$id"
  echo "  + $name ($id)"
}
seed_campaign "Climate Policy Q2 2026"        "Drive engagement around new climate report" "#10b981" "2026-04-01" "2026-06-30"
seed_campaign "Indonesia Economic Outlook"     "Promote quarterly economic briefings"        "#3b82f6" "2026-01-01" "2026-12-31"
seed_campaign "Capital Market Reform"          "Build awareness on capital market reforms"   "#8b5cf6" "2026-02-01" "2026-05-31"
seed_campaign "Youth Employment"               "Highlight youth unemployment research"        "#f59e0b" "2026-03-01" "2026-06-30"

echo
echo "─── Posts ──────────────────────────────────────"
seed_post() {
  local title="$1" body_text="$2" status="$3" sched="$4" campaign_id="$5" tags="$6" link="$7"
  shift 7
  local channels_json="["
  local first=1
  for cid in "$@"; do
    if [[ $first -eq 1 ]]; then channels_json+="\"$cid\""; first=0
    else channels_json+=",\"$cid\""; fi
  done
  channels_json+="]"
  local camp="null"; [[ -n "$campaign_id" ]] && camp="\"$campaign_id\""
  local sched_json="null"; [[ -n "$sched" ]] && sched_json="\"$sched\""
  local body="{\"title\":\"$title\",\"body\":\"$body_text\",\"status\":\"$status\",\"scheduled_at\":$sched_json,\"campaign\":$camp,\"channels\":$channels_json,\"tags\":$tags,\"link_url\":\"$link\"}"
  local id; id=$(post "/api/disseminations/posts/" "$body" | extract_id)
  echo "  + [$status] $title ($id)"
}

# Helper: future ISO timestamp at hour offset
future_iso() { python3 -c "import datetime,sys; print((datetime.datetime.utcnow()+datetime.timedelta(hours=int(sys.argv[1]))).strftime('%Y-%m-%dT%H:%M:%SZ'))" "$1"; }
past_iso()   { python3 -c "import datetime,sys; print((datetime.datetime.utcnow()-datetime.timedelta(days=int(sys.argv[1]))).strftime('%Y-%m-%dT%H:%M:%SZ'))" "$1"; }

CLIMATE_ID="${CAM_IDS["Climate Policy Q2 2026"]}"
ECON_ID="${CAM_IDS["Indonesia Economic Outlook"]}"
CAPITAL_ID="${CAM_IDS["Capital Market Reform"]}"
YOUTH_ID="${CAM_IDS["Youth Employment"]}"

T=${CH_IDS[twitter]}
L=${CH_IDS[linkedin]}
I=${CH_IDS[instagram]}
F=${CH_IDS[facebook]}
Y=${CH_IDS[youtube]}

seed_post "New Climate Report Released" "Our 2026 climate policy landscape report is out. Read it now." "published" "$(past_iso 5)" "$CLIMATE_ID" '["climate","policy","report"]' "https://csis.or.id/publications/climate-2026" "$T" "$L" "$I"
seed_post "Climate Webinar This Friday"  "Join our experts to discuss Indonesia's climate roadmap." "scheduled" "$(future_iso 48)" "$CLIMATE_ID" '["webinar","climate"]' "" "$T" "$L"
seed_post "Capital Market Reform Brief" "Read our latest brief on Indonesia's capital market reforms." "published" "$(past_iso 2)" "$CAPITAL_ID" '["economy","capital-market"]' "https://csis.or.id/publications/capital-market" "$T" "$L"
seed_post "Quarterly Economic Outlook Q1" "Watch the Q1 2026 economic briefing replay on YouTube." "published" "$(past_iso 10)" "$ECON_ID" '["economy","quarterly"]' "https://youtube.com/watch?v=demo" "$Y" "$F"
seed_post "Youth Unemployment Stats"    "Indonesia's youth unemployment trends — key findings." "scheduled" "$(future_iso 72)" "$YOUTH_ID" '["youth","employment"]' "" "$T" "$I"
seed_post "Draft: Mid-Year Economic Update" "Outline for upcoming H1 economic review." "draft" "" "$ECON_ID" '["economy","draft"]' "" "$L"
seed_post "Failed Post Example"         "This one failed to publish — placeholder for testing." "failed" "$(past_iso 1)" "" '["test"]' "" "$T"
seed_post "Archived Announcement"       "Old promo post moved to archive." "archived" "$(past_iso 30)" "" '["promo"]' "" "$F"
seed_post "Capital Market Reform Thread" "Thread breaking down the four pillars of capital market reform." "scheduled" "$(future_iso 24)" "$CAPITAL_ID" '["thread","capital-market"]' "" "$T"
seed_post "Climate Op-Ed: The Road Ahead" "Op-ed by our senior researchers on the climate roadmap." "draft" "" "$CLIMATE_ID" '["op-ed","climate"]' "" "$L" "$F"

echo
echo "✓ Seed complete."
