#!/bin/bash
# kimi-loop.sh — Efficient Gitea issue polling for Kimi agent
#
# Fetches only Kimi-assigned issues using proper query parameters,
# avoiding the need to pull all unassigned tickets and filter in Python.
#
# Usage:
#   ./scripts/kimi-loop.sh
#
# Exit codes:
#   0 — Found work for Kimi
#   1 — No work available

set -euo pipefail

# Configuration
GITEA_API="${TIMMY_GITEA_API:-${GITEA_API:-http://143.198.27.163:3000/api/v1}}"
REPO_SLUG="${REPO_SLUG:-rockachopa/Timmy-time-dashboard}"
TOKEN_FILE="${HOME}/.hermes/gitea_token"
WORKTREE_DIR="${HOME}/worktrees"

# Ensure token exists
if [[ ! -f "$TOKEN_FILE" ]]; then
    echo "ERROR: Gitea token not found at $TOKEN_FILE" >&2
    exit 1
fi

TOKEN=$(cat "$TOKEN_FILE")

# Function to make authenticated Gitea API calls
gitea_api() {
    local endpoint="$1"
    local method="${2:-GET}"
    
    curl -s -X "$method" \
        -H "Authorization: token $TOKEN" \
        -H "Content-Type: application/json" \
        "$GITEA_API/repos/$REPO_SLUG/$endpoint"
}

# Efficiently fetch only Kimi-assigned issues (fixes the filter bug)
# Uses assignee parameter to filter server-side instead of pulling all issues
get_kimi_issues() {
    gitea_api "issues?state=open&assignee=kimi&sort=created&order=asc&limit=10"
}

# Main execution
main() {
    echo "🤖 Kimi loop: Checking for assigned work..."
    
    # Fetch Kimi's issues efficiently (server-side filtering)
    issues=$(get_kimi_issues)
    
    # Count issues using jq
    count=$(echo "$issues" | jq '. | length')
    
    if [[ "$count" -eq 0 ]]; then
        echo "📭 No issues assigned to Kimi. Idle."
        exit 1
    fi
    
    echo "📝 Found $count issue(s) assigned to Kimi:"
    echo "$issues" | jq -r '.[] | "  #\(.number): \(.title)"'
    
    # TODO: Process each issue (create worktree, run task, create PR)
    # For now, just report availability
    echo "✅ Kimi has work available."
    exit 0
}

# Handle script being sourced vs executed
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi