#!/bin/bash
set -e

AGENT="rio"
BRANCH="${AGENT}/entity-population-$(date +%Y-%m-%d)"
WORKSPACE="/opt/teleo-eval/workspaces/entity-${AGENT}"
LOG="/opt/teleo-eval/logs/entity-${AGENT}.log"
BRIEF="/opt/teleo-eval/entity-research-brief.md"
SCHEMA="/opt/teleo-eval/entity-schema.md"

log() { echo "[$(date -Iseconds)] $1" | tee -a "$LOG"; }

# Setup workspace
if [ ! -d "$WORKSPACE" ]; then
    log "Cloning fresh workspace..."
    git clone http://localhost:3000/teleo/teleo-codex.git "$WORKSPACE"
fi

cd "$WORKSPACE"
git checkout main
git pull origin main
git checkout -b "$BRANCH"

# Copy schema into workspace
cp "$SCHEMA" schemas/entity.md

# Create entities directory
mkdir -p entities/internet-finance

log "On branch $BRANCH"
log "Starting Claude entity population session..."

# Build the prompt
PROMPT="You are Rio, the internet finance domain agent for the Teleo Codex knowledge base.

Your task: populate the first entity files for the knowledge base, focusing on the futarchic ecosystem.

RESEARCH BRIEF:
$(cat "$BRIEF")

ENTITY SCHEMA:
$(cat "$SCHEMA")

INSTRUCTIONS:
1. Read the research brief carefully
2. Read the entity schema at schemas/entity.md
3. Read existing claims in domains/internet-finance/ for context
4. Read relevant source archives in inbox/archive/
5. Use web search to find current data for each entity (market caps, metrics, recent events)
6. Create entity files in entities/internet-finance/ following the schema exactly
7. Start with the companies and people listed in the brief
8. Create the market entity for futarchic markets
9. Make sure all wiki links point to real existing files
10. Add timeline events with dates
11. Include competitive positioning for companies
12. Include known positions and credibility basis for people

Create all 12 entities listed in the brief. Quality over speed."

# Run Claude
timeout 5400 /home/teleo/.local/bin/claude -p "$PROMPT" \
    --model opus \
    --allowedTools Read,Write,Edit,Glob,Grep,WebSearch,WebFetch \
     2>&1 | tee -a "$LOG" || true

# Commit and push
log "Session complete. Committing..."
git add entities/ schemas/entity.md
ENTITY_COUNT=$(find entities/ -name "*.md" | wc -l)
git commit -m "rio: populate ${ENTITY_COUNT} entity files — futarchic ecosystem

- What: First entity population using new entity schema
- Why: Cory directive — agents need industry analysis, not just claims
- Schema: entities track companies, people, markets with temporal data

Pentagon-Agent: Rio <CE7B8202-2877-4C70-8AAB-B05F832F50EA>" || log "Nothing to commit"

git push -u origin "$BRANCH" || log "Push failed"

# Create PR
PR_URL=$(curl -s -X POST "http://localhost:3000/api/v1/repos/teleo/teleo-codex/pulls" \
    -H "Authorization: token $(cat /opt/teleo-eval/secrets/forgejo-admin-token)" \
    -H "Content-Type: application/json" \
    -d "{
        \"title\": \"rio: entity schema + ${ENTITY_COUNT} entity files — futarchic ecosystem\",
        \"body\": \"## Summary\n\nNew entity schema + first population of entity files for the futarchic ecosystem.\n\nEntities track companies, people, and markets as dynamic objects with temporal attributes — a parallel input to beliefs alongside claims.\n\n### Entities created:\n- Companies: MetaDAO, Solomon, Ranger Finance, MycoRealms, Futardio, Aave, Polymarket\n- People: Stani Kulechov, Proph3t, Gabriel Shapiro, Felipe Montealegre\n- Markets: Futarchic Markets ecosystem\n\nDesigned by Leo, populated by Rio.\",
        \"head\": \"${BRANCH}\",
        \"base\": \"main\"
    }" | python3 -c "import sys,json; print(json.load(sys.stdin).get(html_url,no url))")

log "PR opened: $PR_URL"
log "=== Entity session complete for ${AGENT} ==="
