#!/bin/bash
# fire-research.sh - Fire up Research (Research Agent)
# Usage: ./fire-research.sh "Research competitor pricing models"

set -e

RESEARCH_TOPIC="$1"
if [ -z "$RESEARCH_TOPIC" ]; then
    echo "Usage: ./fire-research.sh \"Research question here\""
    echo "Example: ./fire-research.sh \"Research competitor pricing for construction job platforms\""
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$(dirname "$SCRIPT_DIR")"
RESEARCH_MD="$REPO_DIR/.claude/RESEARCH-MD.md"

echo "=== FIRING UP DAVE (Research Agent) ==="
echo "Topic: $RESEARCH_TOPIC"
echo ""

# Method 1: Add to RESEARCH-MD.md (preferred)
echo "1. Adding research task to RESEARCH-MD.md..."
TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")

# Read current file
if [ -f "$RESEARCH_MD" ]; then
    # Find where to insert (after "Current Research Queue" section)
    awk -v topic="$RESEARCH_TOPIC" -v ts="$TIMESTAMP" '
    /## Current Research Queue/ {print; in_section=1; next}
    in_section && /^[0-9]+\./ {task_count++}
    in_section && /^[^0-9]/ && !added && task_count > 0 {
        print "   " (task_count+1) ". " topic " (added " ts ")"
        added=1
    }
    {print}
    ' "$RESEARCH_MD" > "$RESEARCH_MD.tmp" && mv "$RESEARCH_MD.tmp" "$RESEARCH_MD"
    
    echo "   ✅ Added to research queue"
else
    echo "   ⚠️ RESEARCH-MD.md not found, creating..."
    cat > "$RESEARCH_MD" << EOF
# RESEARCH-MD - For Research (Research Agent)

## Current Research Queue
1. $RESEARCH_TOPIC (added $TIMESTAMP)

## Research Protocol
1. **Scope** - Define clear research question
2. **Sources** - Use web search, existing data, public APIs
3. **Analysis** - Compare options, model outcomes
4. **Recommendation** - Data-driven suggestion with confidence level
5. **Documentation** - Add to relevant .md files

## Output Format
\`\`\`
## Research: [Topic]
**Question:** [What we need to know]
**Sources:** [Where data came from]
**Findings:** [Key data points]
**Analysis:** [What it means]
**Recommendation:** [Suggested action]
**Confidence:** High/Medium/Low
**Next Steps:** [What to do with this]
\`\`\`
EOF
    echo "   ✅ Created RESEARCH-MD.md with task"
fi

echo ""

# Method 2: Spawn research agent directly (if DeepSeek available)
echo "2. Spawning research agent..."
echo "   Prompt: \"Research the following for RateRight: $RESEARCH_TOPIC\""
echo "   Tools: web_search, web_fetch, read, write"
echo "   Output: Update RESEARCH-MD.md with findings"
echo ""

echo "=== DAVE FIRED UP! ==="
echo ""
echo "Next actions:"
echo "1. Research (research agent) will investigate topic"
echo "2. Findings will be added to RESEARCH-MD.md"
echo "3. Rivet will review findings in next brief"
echo "4. CC may implement recommendations"
echo ""
echo "Research in progress:"
grep -A2 "## Current Research Queue" "$RESEARCH_MD" | tail -5