#!/usr/bin/env bash
set -euo pipefail

CONFIG_FILE="${CCS_CONFIG:-$HOME/.ccs.json}"
PROFILE="${1:-}"

# Validate usage
if [[ -z "$PROFILE" ]]; then
  echo "Usage: ccs <profile> [claude-args...]"
  echo "Example: ccs glm --verbose"
  echo ""
  echo "Available profiles are defined in: $CONFIG_FILE"
  exit 1
fi

# Check config exists
if [[ ! -f "$CONFIG_FILE" ]]; then
  echo "Error: Config file not found: $CONFIG_FILE"
  echo ""
  echo "Create ~/.ccs.json with your profile mappings."
  echo "See .ccs.example.json for template."
  exit 1
fi

# Check jq installed
if ! command -v jq &> /dev/null; then
  echo "Error: jq is required but not installed"
  echo ""
  echo "Install jq:"
  echo "  macOS:   brew install jq"
  echo "  Ubuntu:  sudo apt install jq"
  echo "  Fedora:  sudo dnf install jq"
  exit 1
fi

# Validate profile name (alphanumeric, dash, underscore only)
if [[ "$PROFILE" =~ [^a-zA-Z0-9_-] ]]; then
  echo "Error: Invalid profile name. Use only alphanumeric characters, dash, or underscore."
  exit 1
fi

# Validate JSON syntax
if ! jq -e . "$CONFIG_FILE" &>/dev/null; then
  echo "Error: Invalid JSON in $CONFIG_FILE"
  exit 1
fi

# Validate config has profiles object
if ! jq -e '.profiles' "$CONFIG_FILE" &>/dev/null; then
  echo "Error: Config must have 'profiles' object"
  echo "See .ccs.example.json for correct format"
  exit 1
fi

# Get settings path for profile (using --arg to prevent injection)
SETTINGS_PATH=$(jq -r --arg profile "$PROFILE" '.profiles[$profile] // empty' "$CONFIG_FILE")

if [[ -z "$SETTINGS_PATH" ]]; then
  echo "Error: Profile '$PROFILE' not found in $CONFIG_FILE"
  echo ""
  echo "Available profiles:"
  jq -r '.profiles | keys[]' "$CONFIG_FILE" 2>/dev/null | sed 's/^/  - /'
  exit 1
fi

# Expand ~ in path
SETTINGS_PATH="${SETTINGS_PATH/#\~/$HOME}"

# Validate settings file exists
if [[ ! -f "$SETTINGS_PATH" ]]; then
  echo "Error: Settings file not found: $SETTINGS_PATH"
  echo ""
  echo "Create the settings file or update the path in $CONFIG_FILE"
  exit 1
fi

# Shift profile arg, pass rest to claude
shift

# Execute claude with settings
exec claude --settings "$SETTINGS_PATH" "$@"
