#!/usr/bin/env bash
# Goondex status snapshot
# Usage: ./scripts/status.sh

set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

# Check binary
if [[ -x "$repo_root/goondex" ]]; then
  bin="$repo_root/goondex"
elif [[ -x "$repo_root/bin/goondex" ]]; then
  bin="$repo_root/bin/goondex"
else
  bin=""
fi

# DB info (file size)
db_path="$repo_root/goondex.db"
db_size="missing"
if [[ -f "$db_path" ]]; then
  db_size=$(du -h "$db_path" | awk '{print $1}')
fi

# API key presence
keys_file="$repo_root/config/api_keys.json"
tpdb_key="missing"
if [[ -f "$keys_file" ]]; then
  tpdb_key=$(python - <<'PY' "$keys_file"
import json,sys
try:
    with open(sys.argv[1]) as f:
        data=json.load(f)
    key=data.get("tpdb_api_key")
    print("set" if key else "missing")
except Exception:
    print("missing")
PY
)
fi

# Basic counts (if sqlite3 is available)
scene_count="n/a"; performer_count="n/a"; studio_count="n/a"; movie_count="n/a"
if command -v sqlite3 >/dev/null 2>&1 && [[ -f "$db_path" ]]; then
  scene_count=$(sqlite3 "$db_path" 'select count(*) from scenes;') || scene_count="err"
  performer_count=$(sqlite3 "$db_path" 'select count(*) from performers;') || performer_count="err"
  studio_count=$(sqlite3 "$db_path" 'select count(*) from studios;') || studio_count="err"
  movie_count=$(sqlite3 "$db_path" 'select count(*) from movies;') || movie_count="err"
fi

# Status summary
cat <<EOF
Goondex Status
--------------
Repo:        $repo_root
Binary:      ${bin:-"not built"}
DB:          $db_path (${db_size})
Counts:      performers=$performer_count, studios=$studio_count, scenes=$scene_count, movies=$movie_count
Keys:        TPDB=${tpdb_key}
EOF

# Optional: git status (concise)
if command -v git >/dev/null 2>&1; then
  echo "Git:" $(git status --porcelain | wc -l) "dirty file(s)"
fi
