#!/usr/bin/env bash
# ── Gitea Feed Panel ───────────────────────────────────────────────────
# Shows open PRs, recent merges, and issue queue. Called by watch.
# ───────────────────────────────────────────────────────────────────────

B='\033[1m' ; D='\033[2m' ; R='\033[0m'
G='\033[32m' ; Y='\033[33m' ; RD='\033[31m' ; C='\033[36m' ; M='\033[35m'

TOKEN=$(cat ~/.hermes/gitea_token_vps 2>/dev/null)
API="http://143.198.27.163:3000/api/v1/repos/rockachopa/Timmy-time-dashboard"

echo -e "${B}${C} ◈ GITEA${R}  ${D}$(date '+%H:%M:%S')${R}"
echo -e "${D}────────────────────────────────────────${R}"

# Open PRs
echo -e " ${B}Open PRs${R}"
curl -s --max-time 5 -H "Authorization: token $TOKEN" "$API/pulls?state=open&limit=10" 2>/dev/null | python3 -c "
import json,sys
try:
    prs = json.loads(sys.stdin.read())
    if not prs: print('   (none)')
    for p in prs:
        age_h = ''
        print(f'   #{p[\"number\"]:3d} {p[\"user\"][\"login\"]:8s} {p[\"title\"][:45]}')
except: print('   (error)')
" 2>/dev/null

echo -e "${D}────────────────────────────────────────${R}"

# Recent merged (last 5)
echo -e " ${B}Recently Merged${R}"
curl -s --max-time 5 -H "Authorization: token $TOKEN" "$API/pulls?state=closed&sort=updated&limit=5" 2>/dev/null | python3 -c "
import json,sys
try:
    prs = json.loads(sys.stdin.read())
    merged = [p for p in prs if p.get('merged')]
    if not merged: print('   (none)')
    for p in merged[:5]:
        t = p['merged_at'][:16].replace('T',' ')
        print(f'   ${G}✓${R} #{p[\"number\"]:3d} {p[\"title\"][:35]}  ${D}{t}${R}')
except: print('   (error)')
" 2>/dev/null

echo -e "${D}────────────────────────────────────────${R}"

# Issue queue (assigned to kimi)
echo -e " ${B}Kimi Queue${R}"
curl -s --max-time 5 -H "Authorization: token $TOKEN" "$API/issues?state=open&limit=50&type=issues" 2>/dev/null | python3 -c "
import json,sys
try:
    all_issues = json.loads(sys.stdin.read())
    issues = [i for i in all_issues if 'kimi' in [a.get('login','') for a in (i.get('assignees') or [])]]
    if not issues: print('   (empty — assign more!)')
    for i in issues[:8]:
        print(f'   #{i[\"number\"]:3d} {i[\"title\"][:50]}')
    if len(issues) > 8: print(f'   ... +{len(issues)-8} more')
except: print('   (error)')
" 2>/dev/null

echo -e "${D}────────────────────────────────────────${R}"

# Unassigned issues
UNASSIGNED=$(curl -s --max-time 5 -H "Authorization: token $TOKEN" "$API/issues?state=open&limit=50&type=issues" 2>/dev/null | python3 -c "
import json,sys
try:
    issues = json.loads(sys.stdin.read())
    print(len([i for i in issues if not i.get('assignees')]))
except: print('?')
" 2>/dev/null)
echo -e " Unassigned issues: ${Y}$UNASSIGNED${R}"
