#!/bin/bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
DEFAULT_LIST="$ROOT_DIR/sites.csv"
LIST_PATH="${1:-$DEFAULT_LIST}"

if [ ! -f "$LIST_PATH" ]; then
  echo "Site list not found at $LIST_PATH"
  echo "Please place a CSV-like list (domain,optional theme) at $DEFAULT_LIST and rerun."
  exit 1
fi

entries=()
while IFS= read -r line || [ -n "$line" ]; do
  # Allow broken CSV: domain[,theme]
  domain="$(echo "$line" | awk -F',' '{print $1}' | sed 's/^ *//;s/ *$//')"
  theme="$(echo "$line" | awk -F',' '{print $2}' | sed 's/^ *//;s/ *$//')"
  [ -z "$domain" ] && { echo "Skipping line (no domain): $line" >&2; continue; }
  title="$domain"
  desc="$theme"
  theme_slug="$(echo "$theme" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//' )"
  [ -z "$theme_slug" ] && theme_slug="default"
  entries+=("${domain}:${title}:${desc}:${theme_slug}")
done <"$LIST_PATH"

sites_string="$(IFS=','; echo "${entries[*]}")"
echo "$sites_string"
