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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
REPO_ROOT="$(cd "${PROJECT_DIR}/../../.." && pwd)"
FAILURES=0
WARNINGS=0

pass() { printf '[PASS] %s\n' "$1"; }
warn() { printf '[WARN] %s\n' "$1"; WARNINGS=$((WARNINGS + 1)); }
fail() { printf '[FAIL] %s\n' "$1"; FAILURES=$((FAILURES + 1)); }

printf 'Product Group AI Native teammate setup check\n'
printf 'Repository: %s\n\n' "${REPO_ROOT}"

[[ -f "${REPO_ROOT}/AGENTS.md" ]] && pass 'AGENTS.md exists' || fail 'AGENTS.md is missing'
[[ -f "${PROJECT_DIR}/ONBOARDING.md" ]] && pass 'onboarding guide exists' || fail 'onboarding guide is missing'
[[ -f "${PROJECT_DIR}/control/members.csv" ]] && pass 'member registry exists' || fail 'member registry is missing'
[[ -f "${REPO_ROOT}/standards-stack/agent-skills/skills/product-group-ai-native-collaboration/SKILL.md" ]] \
  && pass 'controller skill exists in repository' \
  || fail 'controller skill is missing from repository'

if git -C "${REPO_ROOT}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  pass 'directory is a Git worktree'
else
  fail 'directory is not a Git worktree'
fi

REMOTE_URL="$(git -C "${REPO_ROOT}" remote get-url origin 2>/dev/null || true)"
if [[ "${REMOTE_URL}" == *'codeup.aliyun.com/'*'/zhct/zhctprompt.git' ]]; then
  pass 'Codeup origin points to zhct/zhctprompt'
else
  warn "origin is unexpected or missing: ${REMOTE_URL:-none}"
fi

CONFLICTS="$(git -C "${REPO_ROOT}" diff --name-only --diff-filter=U 2>/dev/null || true)"
if [[ -z "${CONFLICTS}" ]]; then
  pass 'no unresolved Git conflicts'
else
  fail "unresolved Git conflicts exist: ${CONFLICTS//$'\n'/, }"
fi

if [[ -f "${HOME}/.codex/skills/product-group-ai-native-collaboration/SKILL.md" ]]; then
  pass 'controller skill is installed in local Codex registry'
else
  warn 'controller skill is not installed locally; run standards-stack/agent-skills/scripts/install_project_skills_to_codex.sh'
fi

if [[ -f "${REPO_ROOT}/config/local/yunxiao.env" ]]; then
  pass 'local Yunxiao config file exists (contents not inspected)'
else
  warn 'local Yunxiao config is absent; only required before Yunxiao operations'
fi

printf '\nResult: %s failure(s), %s warning(s)\n' "${FAILURES}" "${WARNINGS}"
if [[ "${FAILURES}" -gt 0 ]]; then
  exit 1
fi

printf 'Setup baseline passed. AI Workflow Owner must still verify member and work-item assignments.\n'
