#!/usr/bin/env bash

set -euo pipefail

usage() {
  echo "Usage: $0 [--check|--repair]"
  echo "  --check   Validate optional standards associations in four canonical repositories (default)."
  echo "  --repair  Repoint an existing wrong symlink; never create links or replace real paths."
}

mode="check"
case "${1:-}" in
  ""|--check) mode="check" ;;
  --repair) mode="repair" ;;
  -h|--help) usage; exit 0 ;;
  *) usage >&2; exit 64 ;;
esac

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
control_root="$(cd "$script_dir/../.." && pwd -P)"
zhct_root="$(dirname "$control_root")"
repo_root="${ZHCTPROJECT_ROOT:-$zhct_root/zhctproject}"
prompt_root="${ZHCTPROMPT_ROOT:-$control_root}"
standard_root="$prompt_root/standards-stack"

repos=(store ai_api ai_store ai_app)
links=(prompt agent-skills .archon)
failures=0
repairs=0
absent=0
owned=0

for name in "${links[@]}"; do
  if [[ ! -d "$standard_root/$name" ]]; then
    echo "FAIL missing standard source: $standard_root/$name" >&2
    failures=$((failures + 1))
  fi
done

if (( failures > 0 )); then
  exit 1
fi

for repo in "${repos[@]}"; do
  repo_path="$repo_root/$repo"
  if [[ ! -d "$repo_path" ]]; then
    echo "FAIL missing business repository: $repo_path" >&2
    failures=$((failures + 1))
    continue
  fi

  for name in "${links[@]}"; do
    link_path="$repo_path/$name"
    expected="$standard_root/$name"

    if [[ ! -e "$link_path" && ! -L "$link_path" ]]; then
      echo "OK   optional association absent on master: $link_path"
      absent=$((absent + 1))
      continue
    fi

    if [[ ! -L "$link_path" ]]; then
      tracked_count="$(git -C "$repo_path" ls-files -- "$name" | wc -l | tr -d ' ')"
      if [[ "$tracked_count" -gt 0 ]]; then
        echo "INFO repository-owned tracked path retained: $link_path (tracked=$tracked_count)"
        owned=$((owned + 1))
      else
        echo "FAIL untracked real path needs manual review: $link_path" >&2
        failures=$((failures + 1))
      fi
      continue
    fi

    actual="$(readlink "$link_path")"
    if [[ "$actual" != "$expected" && "$mode" == "repair" ]]; then
      ln -sfn "$expected" "$link_path"
      actual="$(readlink "$link_path")"
      repairs=$((repairs + 1))
    fi

    if [[ "$actual" != "$expected" ]]; then
      echo "FAIL wrong target: $link_path -> $actual" >&2
      echo "     expected: $expected" >&2
      failures=$((failures + 1))
    elif [[ ! -e "$link_path" ]]; then
      echo "FAIL unresolved link: $link_path -> $actual" >&2
      failures=$((failures + 1))
    else
      echo "OK   $link_path -> $actual"
    fi
  done

  if grep -RIl --exclude-dir=.git --exclude-dir=node_modules --exclude-dir=vendor 'zhctpromote' "$repo_path" 2>/dev/null | grep -q .; then
    echo "FAIL obsolete zhctpromote reference found under: $repo_path" >&2
    failures=$((failures + 1))
  fi
done

echo "summary mode=$mode repairs=$repairs owned=$owned absent=$absent failures=$failures"
(( failures == 0 ))
