#!/bin/bash

# Wogi Flow - Load Task Context
# Gather all context needed to implement a task

set -e

WORKFLOW_DIR=".workflow"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
RED='\033[0;31m'
NC='\033[0m'

if [ -z "$1" ]; then
    echo "Usage: flow context <task-id>"
    echo ""
    echo "Loads all context for implementing a task:"
    echo "  - Task story and acceptance criteria"
    echo "  - Related request-log entries"
    echo "  - Referenced component docs"
    echo "  - Relevant decisions"
    exit 1
fi

TASK_ID="$1"

echo -e "${CYAN}═══════════════════════════════════════${NC}"
echo -e "${CYAN}  Context for: $TASK_ID${NC}"
echo -e "${CYAN}═══════════════════════════════════════${NC}"
echo ""

# Find the task story file
STORY_FILE=""
for file in "$WORKFLOW_DIR/changes"/*/"$TASK_ID.md" "$WORKFLOW_DIR/changes"/*/*.md; do
    if [ -f "$file" ] && grep -q "$TASK_ID" "$file" 2>/dev/null; then
        STORY_FILE="$file"
        break
    fi
done

# 1. Task Story
echo -e "${GREEN}📋 STORY${NC}"
echo "─────────────────────────────────────"
if [ -n "$STORY_FILE" ] && [ -f "$STORY_FILE" ]; then
    cat "$STORY_FILE"
else
    # Try to find in tasks.json
    for tasks_file in "$WORKFLOW_DIR/changes"/*/tasks.json; do
        if [ -f "$tasks_file" ]; then
            task_info=$(python3 -c "
import json
with open('$tasks_file') as f:
    data = json.load(f)
for task in data.get('tasks', []):
    if task.get('id') == '$TASK_ID':
        print(f\"Title: {task.get('title', 'N/A')}\")
        print(f\"Status: {task.get('status', 'N/A')}\")
        print(f\"Priority: {task.get('priority', 'N/A')}\")
        us = task.get('userStory', {})
        if us:
            print(f\"\\nUser Story:\")
            print(f\"  As a {us.get('asA', '?')}\")
            print(f\"  I want {us.get('iWant', '?')}\")
            print(f\"  So that {us.get('soThat', '?')}\")
        print(f\"\\nDescription: {task.get('description', 'N/A')}\")
        ac = task.get('acceptanceCriteria', [])
        if ac:
            print(f\"\\nAcceptance Criteria:\")
            for c in ac:
                if isinstance(c, dict):
                    print(f\"  {c.get('scenario', 'Scenario')}:\")
                    print(f\"    Given {c.get('given', '?')}\")
                    print(f\"    When {c.get('when', '?')}\")
                    print(f\"    Then {c.get('then', '?')}\")
                else:
                    print(f\"  - {c}\")
        break
" 2>/dev/null || true)
            if [ -n "$task_info" ]; then
                echo "$task_info"
                break
            fi
        fi
    done
fi
echo ""

# 2. Related Request Log Entries
echo -e "${GREEN}📜 RELATED HISTORY${NC}"
echo "─────────────────────────────────────"
if [ -f "$WORKFLOW_DIR/state/request-log.md" ]; then
    # Search for task ID or related tags
    related=$(grep -B1 -A5 "$TASK_ID" "$WORKFLOW_DIR/state/request-log.md" 2>/dev/null | head -30 || true)
    if [ -n "$related" ]; then
        echo "$related"
    else
        echo "No related entries found in request-log"
    fi
fi
echo ""

# 3. Referenced Components
echo -e "${GREEN}🧩 COMPONENTS${NC}"
echo "─────────────────────────────────────"
if [ -f "$WORKFLOW_DIR/state/app-map.md" ]; then
    echo "Available components:"
    grep "^|" "$WORKFLOW_DIR/state/app-map.md" | grep -v "^| ---" | grep -v "^| Component" | grep -v "^| Screen" | grep -v "^| Modal" | head -15
fi
echo ""

# 4. Relevant Decisions
echo -e "${GREEN}📏 DECISIONS${NC}"
echo "─────────────────────────────────────"
if [ -f "$WORKFLOW_DIR/state/decisions.md" ]; then
    # Show component and coding standards sections
    head -50 "$WORKFLOW_DIR/state/decisions.md" | tail -40
fi
echo ""

# 5. Dependencies
echo -e "${GREEN}🔗 DEPENDENCIES${NC}"
echo "─────────────────────────────────────"
for tasks_file in "$WORKFLOW_DIR/changes"/*/tasks.json; do
    if [ -f "$tasks_file" ]; then
        python3 -c "
import json
with open('$tasks_file') as f:
    data = json.load(f)
for task in data.get('tasks', []):
    if task.get('id') == '$TASK_ID':
        deps = task.get('dependencies', [])
        if deps:
            print('Depends on:')
            for d in deps:
                print(f'  - {d}')
        else:
            print('No dependencies')
        break
" 2>/dev/null || true
    fi
done
echo ""

echo -e "${CYAN}═══════════════════════════════════════${NC}"
echo ""
echo "Ready to implement. Remember to:"
echo "  1. Follow acceptance criteria exactly"
echo "  2. Check app-map before creating components"
echo "  3. Log changes to request-log"
