#!/usr/bin/env bash

set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
control_root="$(cd "$script_dir/../.." && pwd -P)"
zhct_root="$(dirname "$control_root")"
manifest="$control_root/control/zhctproject-repositories.csv"

failures=0
checked=0
ahead_total=0

if [[ ! -f "$manifest" ]]; then
  echo "FAIL missing repository manifest: $manifest" >&2
  exit 1
fi

while IFS=, read -r name local_path remote_url default_action notes; do
  remote_url="${remote_url%$'\r'}"
  default_action="${default_action%$'\r'}"
  [[ "$name" == "name" ]] && continue
  [[ "$default_action" != "pull_or_clone" && "$default_action" != "local_only" ]] && continue

  repo_path="$zhct_root/$local_path"
  expected_path="$repo_path"
  checked=$((checked + 1))

  if [[ -L "$repo_path" ]]; then
    echo "FAIL $name canonical path is a symlink: $repo_path" >&2
    failures=$((failures + 1))
    continue
  fi
  if [[ ! -d "$repo_path/.git" ]]; then
    echo "FAIL $name is missing or not a standalone Git repository: $repo_path" >&2
    failures=$((failures + 1))
    continue
  fi

  actual_path="$(cd "$repo_path" && pwd -P)"
  if [[ "$actual_path" != "$expected_path" ]]; then
    echo "FAIL $name resolved path mismatch: $actual_path (expected $expected_path)" >&2
    failures=$((failures + 1))
  fi

  branch="$(git -C "$repo_path" branch --show-current)"
  if [[ "$branch" != "master" ]]; then
    echo "FAIL $name branch=$branch (expected master)" >&2
    failures=$((failures + 1))
  fi

  repo_dirty=0
  if [[ -n "$(git -C "$repo_path" status --porcelain)" ]]; then
    echo "FAIL $name worktree is dirty" >&2
    failures=$((failures + 1))
    repo_dirty=1
  fi

  if [[ "$default_action" == "local_only" ]]; then
    if [[ "$branch" == "master" && "$repo_dirty" -eq 0 ]]; then
      echo "OK   $name local_only master clean: head=$(git -C "$repo_path" rev-parse --short=12 HEAD)"
    else
      echo "INFO $name local_only validation failed above: branch=$branch dirty=$repo_dirty"
    fi
    continue
  fi

  actual_origin="$(git -C "$repo_path" remote get-url origin 2>/dev/null || true)"
  if [[ "$actual_origin" != "$remote_url" ]]; then
    echo "FAIL $name origin=$actual_origin (expected $remote_url)" >&2
    failures=$((failures + 1))
  fi

  upstream="$(git -C "$repo_path" rev-parse --abbrev-ref '@{u}' 2>/dev/null || true)"
  if [[ -z "$upstream" || "$upstream" != origin/* ]]; then
    echo "FAIL $name has no origin upstream tracking ref" >&2
    failures=$((failures + 1))
    continue
  fi

  if ! git -C "$repo_path" show-ref --verify --quiet "refs/remotes/$upstream"; then
    echo "FAIL $name upstream ref is missing: $upstream" >&2
    failures=$((failures + 1))
    continue
  fi

  if [[ "$upstream" != "origin/master" ]]; then
    echo "INFO $name local master tracks remote source branch $upstream"
  fi

  read -r ahead behind < <(git -C "$repo_path" rev-list --left-right --count HEAD..."$upstream")
  if [[ "$behind" -gt 0 ]]; then
    echo "FAIL $name is behind/diverged: ahead=$ahead behind=$behind" >&2
    failures=$((failures + 1))
  elif [[ "$ahead" -gt 0 ]]; then
    echo "WARN $name master is locally ahead for human review: ahead=$ahead behind=$behind head=$(git -C "$repo_path" rev-parse --short=12 HEAD)"
    ahead_total=$((ahead_total + ahead))
  else
    echo "OK   $name master clean and aligned: head=$(git -C "$repo_path" rev-parse --short=12 HEAD)"
  fi
done < "$manifest"

for repo in store ai_api ai_store ai_app; do
  for old_path in "$zhct_root/$repo" "$zhct_root/zhct/zhctproject/$repo"; do
    if [[ -e "$old_path" || -L "$old_path" ]]; then
      echo "FAIL duplicate active path still exists: $old_path" >&2
      failures=$((failures + 1))
    else
      echo "OK   duplicate active path absent: $old_path"
    fi
  done
done

android_duplicate_paths=(
  "$zhct_root/CusumptionMachine"
  "$zhct_root/device/CusumptionMachine"
  "$zhct_root/device/ZhctTrayAndWeight"
  "$zhct_root/device/ZhctTrayBindingMachine"
  "$zhct_root/device/ZhctWeightingTable"
  "$zhct_root/device/ZhctWeightingTableDouble"
  "$(dirname "$zhct_root")/AIDishRecognition"
)

for old_path in "${android_duplicate_paths[@]}"; do
  if [[ -e "$old_path" || -L "$old_path" ]]; then
    echo "FAIL duplicate Android active path still exists: $old_path" >&2
    failures=$((failures + 1))
  else
    echo "OK   duplicate Android active path absent: $old_path"
  fi
done

echo "summary checked=$checked local_ahead_commits=$ahead_total failures=$failures"
(( failures == 0 ))
