#!/bin/bash
# hermes-claim — claim/release/check issues to prevent overlap with the loop
# Usage:
#   hermes-claim take 52       — claim issue #52 for interactive work
#   hermes-claim drop 52       — release claim
#   hermes-claim list           — show all claims
#   hermes-claim check 52      — exit 0 if free, exit 1 if claimed

set -euo pipefail

CLAIMS_FILE="$HOME/Timmy-Time-dashboard/.loop/claims.json"

# Initialize if missing
if [[ ! -f "$CLAIMS_FILE" ]]; then
  echo '{}' > "$CLAIMS_FILE"
fi

ACTION="${1:-list}"
ISSUE="${2:-}"

case "$ACTION" in
  take)
    [[ -z "$ISSUE" ]] && echo "Usage: hermes-claim take <issue#>" && exit 1
    python3 -c "
import json
from datetime import datetime, timezone
with open('$CLAIMS_FILE') as f: c = json.load(f)
c['$ISSUE'] = {'by': '${CLAIMANT:-hermes-interactive}', 'at': datetime.now(timezone.utc).isoformat()}
with open('$CLAIMS_FILE', 'w') as f: json.dump(c, f, indent=2)
print('Claimed issue #$ISSUE')
"
    ;;
  drop)
    [[ -z "$ISSUE" ]] && echo "Usage: hermes-claim drop <issue#>" && exit 1
    python3 -c "
import json
with open('$CLAIMS_FILE') as f: c = json.load(f)
c.pop('$ISSUE', None)
with open('$CLAIMS_FILE', 'w') as f: json.dump(c, f, indent=2)
print('Released issue #$ISSUE')
"
    ;;
  check)
    [[ -z "$ISSUE" ]] && echo "Usage: hermes-claim check <issue#>" && exit 1
    python3 -c "
import json
with open('$CLAIMS_FILE') as f: c = json.load(f)
if '$ISSUE' in c:
    info = c['$ISSUE']
    print(f\"CLAIMED by {info['by']} at {info['at']}\")
    exit(1)
else:
    print('FREE')
" || exit 1
    ;;
  list)
    python3 -c "
import json
with open('$CLAIMS_FILE') as f: c = json.load(f)
if not c:
    print('No active claims.')
else:
    for issue, info in sorted(c.items()):
        print(f\"  #{issue}: {info['by']} (since {info['at']})\")
"
    ;;
  *)
    echo "Usage: hermes-claim [take|drop|check|list] [issue#]"
    exit 1
    ;;
esac
