#!/bin/bash

set -euo pipefail

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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMMON_PLAT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
WORKSPACE_DIR="${WORKSPACE_DIR:-$(cd "${COMMON_PLAT_DIR}/.." && pwd)}"
REPOS_TXT="${COMMON_PLAT_DIR}/.windsurf/workflows/repos.txt"

if [[ ! -f "$REPOS_TXT" ]]; then
  echo -e "${RED}❌ repos.txt not found at ${REPOS_TXT}${NC}"
  exit 1
fi

read_repos() {
  local repos=()
  while IFS= read -r line; do
    [[ "$line" =~ ^[[:space:]]*# ]] && continue
    [[ -z "${line// }" ]] && continue
    repos+=("$line")
  done < "$REPOS_TXT"
  printf '%s\n' "${repos[@]}"
}

get_commit_message() {
  local repo="$1"
  local repo_path="${WORKSPACE_DIR}/${repo}"
  local files

  files="$(git -C "$repo_path" diff --name-only 2>/dev/null || true)"
  files+=$'\n'"$(git -C "$repo_path" diff --cached --name-only 2>/dev/null || true)"
  files+=$'\n'"$(git -C "$repo_path" ls-files --others --exclude-standard 2>/dev/null || true)"

  local has_auth has_ci has_docs has_docker has_package has_python has_tests has_config
  has_auth="$(echo "$files" | grep -E '(auth|middleware|jwt)' || true)"
  has_ci="$(echo "$files" | grep -E '\.github|workflow|ci' || true)"
  has_docs="$(echo "$files" | grep -E '\.md$' || true)"
  has_docker="$(echo "$files" | grep -E 'Dockerfile|docker' || true)"
  has_package="$(echo "$files" | grep -E 'package\.json|pnpm-lock|yarn\.lock' || true)"
  has_python="$(echo "$files" | grep -E '\.py$|requirements' || true)"
  has_tests="$(echo "$files" | grep -E 'test|spec' || true)"
  has_config="$(echo "$files" | grep -E '\.env|config|\.toml' || true)"

  if [[ -n "$has_auth" ]]; then
    echo "feat(auth): update authentication and middleware"
  elif [[ -n "$has_ci" ]]; then
    echo "ci: update CI/CD configuration"
  elif [[ -n "$has_docker" ]]; then
    if [[ -n "$has_package" ]]; then
      echo "feat(devops): update docker and package configuration"
    else
      echo "feat(devops): update Docker configuration"
    fi
  elif [[ -n "$has_package" ]]; then
    echo "chore: update dependencies"
  elif [[ -n "$has_docs" ]]; then
    echo "docs: update documentation"
  elif [[ -n "$has_python" ]]; then
    if [[ -n "$has_tests" ]]; then
      echo "test(python): update test suite"
    else
      echo "feat(python): update Python modules"
    fi
  elif [[ -n "$has_tests" ]]; then
    echo "test: add/update tests"
  elif [[ -n "$has_config" ]]; then
    echo "chore: update configuration"
  else
    echo "chore: update project files"
  fi
}

commit_repo() {
  local repo="$1"
  local repo_path="${WORKSPACE_DIR}/${repo}"

  echo -e "${BLUE}📝 Committing ${repo}...${NC}"
  git -C "$repo_path" add -A
  local commit_msg
  commit_msg="$(get_commit_message "$repo")"
  echo -e "  Message: ${YELLOW}${commit_msg}${NC}"
  git -C "$repo_path" commit -m "$commit_msg"
  echo -e "  ${GREEN}✅ Committed${NC}"
  echo
}

echo -e "${BLUE}📋 Scanning workspace for changes...${NC}"
echo

REPOS=()
while IFS= read -r _r; do
  REPOS+=("$_r")
done < <(read_repos)
REPOS_WITH_CHANGES=()

for repo in "${REPOS[@]}"; do
  repo_path="${WORKSPACE_DIR}/${repo}"
  if [[ ! -d "$repo_path/.git" ]]; then
    continue
  fi

  if ! git -C "$repo_path" diff --quiet || ! git -C "$repo_path" diff --cached --quiet || [[ -n "$(git -C "$repo_path" ls-files --others --exclude-standard)" ]]; then
    REPOS_WITH_CHANGES+=("$repo")

    staged=$(git -C "$repo_path" diff --cached --name-only | wc -l | tr -d ' ')
    modified=$(git -C "$repo_path" diff --name-only | wc -l | tr -d ' ')
    untracked=$(git -C "$repo_path" ls-files --others --exclude-standard | wc -l | tr -d ' ')

    echo -e "${YELLOW}📁 ${repo}${NC}:"
    [[ "$staged" -gt 0 ]] && echo "  - ${staged} staged"
    [[ "$modified" -gt 0 ]] && echo "  - ${modified} modified"
    [[ "$untracked" -gt 0 ]] && echo "  - ${untracked} untracked"
    echo
  fi
done

if [[ ${#REPOS_WITH_CHANGES[@]} -eq 0 ]]; then
  echo -e "${GREEN}✅ No changes to commit${NC}"
  exit 0
fi

echo -e "${BLUE}Found changes in ${#REPOS_WITH_CHANGES[@]} repo(s)${NC}"
echo

echo -e "${BLUE}🚀 Committing in dependency order...${NC}"
echo

if [[ " ${REPOS_WITH_CHANGES[*]} " =~ " learning_ai_common_plat " ]]; then
  commit_repo "learning_ai_common_plat"
fi

for repo in "${REPOS_WITH_CHANGES[@]}"; do
  if [[ "$repo" != "learning_ai_common_plat" ]]; then
    commit_repo "$repo"
  fi
done

echo -e "${GREEN}✨ All changes committed locally!${NC}"
echo -e "${BLUE}💡 Use /repo_sync-repos or git push to push to remote${NC}"
