#!/usr/bin/env bash
#
# hy -- Harnyard: unified launcher for AI coding agent harnesses
#
# Usage:
#   hy <harness> [args...]     Start a harness
#   hy setup <harness|--all>   Create symlinks for a harness
#   hy status                  Show config mapping for all harnesses
#   hy list                    List available harnesses
#
set -euo pipefail

HARNYARD_ROOT="${HARNYARD_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
PROFILES_DIR="${HARNYARD_ROOT}/profiles"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

usage() {
  cat <<'EOF'
hy -- Harnyard: unified launcher for AI coding agent harnesses

Usage:
  hy <harness> [args...]     Start a harness (claude, copilot, kiro, pi)
  hy setup <harness|--all>   Create symlinks for a harness
  hy status                  Show config mapping for all harnesses
  hy list                    List available harnesses
  hy help                    Show this help

Examples:
  hy claude                  Start Claude Code
  hy kiro                    Start Kiro CLI (creates symlinks if needed)
  hy setup --all             Setup all non-native harnesses
  hy status                  Show what each harness sees
EOF
}

# Simple YAML value reader (no dependencies)
yaml_get() {
  local file="$1" key="$2"
  grep "^${key}:" "$file" 2>/dev/null | sed "s/^${key}:[[:space:]]*//" | sed 's/[[:space:]]*#.*//'
}

# Find profile for a harness name or alias
find_profile() {
  local name="$1"
  for profile in "${PROFILES_DIR}"/*.yaml; do
    local pname
    pname=$(yaml_get "$profile" "binary")
    if [[ "$pname" == "$name" ]]; then
      echo "$profile"
      return 0
    fi
    # Check aliases
    if grep -q "aliases:.*${name}" "$profile" 2>/dev/null; then
      echo "$profile"
      return 0
    fi
  done
  return 1
}

# Check if a harness binary is installed
check_binary() {
  local binary="$1"
  if command -v "$binary" &>/dev/null; then
    return 0
  fi
  return 1
}

# Create symlinks for a harness
setup_harness() {
  local profile="$1"
  local name config_dir native

  name=$(yaml_get "$profile" "name")
  config_dir=$(yaml_get "$profile" "config_dir")
  native=$(yaml_get "$profile" "native")

  if [[ "$native" == "true" ]]; then
    echo -e "${GREEN}${name}${NC} reads .claude/ natively -- no setup needed"
    return 0
  fi

  echo -e "${BOLD}Setting up ${name}${NC} (${config_dir}/)"

  # Ensure .claude/ exists
  if [[ ! -d ".claude" ]]; then
    echo -e "${RED}Error: .claude/ directory not found in current project${NC}"
    echo "Run this from a project with a .claude/ directory."
    return 1
  fi

  # Create config dir
  mkdir -p "${config_dir}"

  # Skills symlink
  if [[ -d ".claude/skills" ]]; then
    local skills_dir
    skills_dir=$(yaml_get "$profile" "  dir" 2>/dev/null || echo "skills")
    # For skills, symlink each skill individually
    local target_skills="${config_dir}/${skills_dir}"
    mkdir -p "$target_skills"
    for skill in .claude/skills/*/; do
      if [[ -d "$skill" ]]; then
        local skill_name
        skill_name=$(basename "$skill")
        local link_target="${target_skills}/${skill_name}"
        if [[ ! -e "$link_target" ]]; then
          ln -sf "../../.claude/skills/${skill_name}" "$link_target"
          echo -e "  ${GREEN}+${NC} ${config_dir}/${skills_dir}/${skill_name} -> .claude/skills/${skill_name}"
        else
          echo -e "  ${YELLOW}=${NC} ${config_dir}/${skills_dir}/${skill_name} (already exists)"
        fi
      fi
    done
  fi

  # Context file symlink
  if [[ -f ".claude/CLAUDE.md" ]]; then
    local context_target
    # Kiro uses steering.md
    if [[ "$config_dir" == ".kiro" ]]; then
      context_target="${config_dir}/steering.md"
      if [[ ! -e "$context_target" ]]; then
        ln -sf "../.claude/CLAUDE.md" "$context_target"
        echo -e "  ${GREEN}+${NC} ${context_target} -> .claude/CLAUDE.md"
      fi
    fi
  fi

  # MCP config symlink
  if [[ -f ".mcp.json" || -f ".claude/.mcp.json" ]]; then
    local mcp_source
    if [[ -f ".mcp.json" ]]; then
      mcp_source="../.mcp.json"
    else
      mcp_source="../.claude/.mcp.json"
    fi
    local mcp_target="${config_dir}/mcp.json"
    if [[ ! -e "$mcp_target" ]]; then
      ln -sf "$mcp_source" "$mcp_target"
      echo -e "  ${GREEN}+${NC} ${mcp_target} -> ${mcp_source}"
    fi
  fi

  echo -e "${GREEN}Done${NC}"
}

# Show status of all harnesses
show_status() {
  echo -e "${BOLD}Harnyard Status${NC}"
  echo -e "Project: $(pwd)"
  echo ""

  for profile in "${PROFILES_DIR}"/*.yaml; do
    local name binary config_dir native

    name=$(yaml_get "$profile" "name")
    binary=$(yaml_get "$profile" "binary")
    config_dir=$(yaml_get "$profile" "config_dir")
    native=$(yaml_get "$profile" "native")

    # Check if binary is installed
    local installed
    if check_binary "$binary"; then
      installed="${GREEN}installed${NC}"
    else
      installed="${RED}not found${NC}"
    fi

    # Check if config exists
    local config_status
    if [[ "$native" == "true" ]]; then
      if [[ -d ".claude" ]]; then
        config_status="${GREEN}native (.claude/)${NC}"
      else
        config_status="${YELLOW}no .claude/ dir${NC}"
      fi
    else
      if [[ -d "$config_dir" ]]; then
        config_status="${GREEN}configured (${config_dir}/)${NC}"
      else
        config_status="${YELLOW}needs setup${NC}"
      fi
    fi

    echo -e "  ${BOLD}${name}${NC} (${binary})"
    echo -e "    Binary: ${installed}"
    echo -e "    Config: ${config_status}"
    echo ""
  done
}

# List available harnesses
list_harnesses() {
  echo -e "${BOLD}Available Harnesses${NC}"
  echo ""
  for profile in "${PROFILES_DIR}"/*.yaml; do
    local name binary aliases native
    name=$(yaml_get "$profile" "name")
    binary=$(yaml_get "$profile" "binary")
    native=$(yaml_get "$profile" "native")

    local native_tag=""
    if [[ "$native" == "true" ]]; then
      native_tag=" ${GREEN}(native)${NC}"
    fi

    local installed_tag=""
    if check_binary "$binary"; then
      installed_tag=" ${GREEN}✓${NC}"
    else
      installed_tag=" ${RED}✗${NC}"
    fi

    echo -e "  ${BOLD}${binary}${NC}${installed_tag}${native_tag} -- ${name}"
  done
}

# Start a harness
start_harness() {
  local harness="$1"
  shift

  local profile
  if ! profile=$(find_profile "$harness"); then
    echo -e "${RED}Unknown harness: ${harness}${NC}"
    echo "Run 'hy list' to see available harnesses."
    return 1
  fi

  local binary native config_dir
  binary=$(yaml_get "$profile" "binary")
  native=$(yaml_get "$profile" "native")
  config_dir=$(yaml_get "$profile" "config_dir")

  # Check binary exists
  if ! check_binary "$binary"; then
    echo -e "${RED}${binary} not found in PATH${NC}"
    echo "Install it first, then try again."
    return 1
  fi

  # Auto-setup if needed
  if [[ "$native" != "true" && ! -d "$config_dir" && -d ".claude" ]]; then
    echo -e "${YELLOW}Auto-setting up ${config_dir}/ from .claude/${NC}"
    setup_harness "$profile"
    echo ""
  fi

  # Launch
  echo -e "${BLUE}Starting ${binary}...${NC}"
  exec "$binary" "$@"
}

# Main
case "${1:-help}" in
  help|--help|-h)
    usage
    ;;
  setup)
    shift
    if [[ "${1:-}" == "--all" ]]; then
      for profile in "${PROFILES_DIR}"/*.yaml; do
        setup_harness "$profile"
        echo ""
      done
    elif [[ -n "${1:-}" ]]; then
      profile=$(find_profile "$1") || { echo "Unknown harness: $1"; exit 1; }
      setup_harness "$profile"
    else
      echo "Usage: hy setup <harness|--all>"
      exit 1
    fi
    ;;
  status)
    show_status
    ;;
  list|ls)
    list_harnesses
    ;;
  *)
    start_harness "$@"
    ;;
esac
