#!/bin/bash

# Wogi Flow - Show Task Dependencies

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 deps <task-id>"
    echo ""
    echo "Shows what a task depends on and what depends on it."
    exit 1
fi

TASK_ID="$1"

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

# Search all task files for dependencies
found=false

for tasks_file in "$WORKFLOW_DIR/changes"/*/tasks.json; do
    if [ -f "$tasks_file" ]; then
        python3 << EOF
import json
import sys

task_id = "$TASK_ID"

with open('$tasks_file') as f:
    data = json.load(f)

tasks = data.get('tasks', [])

# Find the task
target = None
for task in tasks:
    if task.get('id') == task_id:
        target = task
        break

if target:
    print(f"Found in: $tasks_file")
    print()
    
    # What it depends on
    deps = target.get('dependencies', [])
    if deps:
        print('\033[1;33m↑ DEPENDS ON:\033[0m')
        for dep in deps:
            # Find dep status
            for t in tasks:
                if t.get('id') == dep:
                    status = t.get('status', 'unknown')
                    print(f"  • {dep} ({status})")
                    break
            else:
                print(f"  • {dep}")
    else:
        print('\033[0;32m↑ No dependencies\033[0m')
    
    print()
    
    # What depends on it
    dependents = []
    for task in tasks:
        if task_id in task.get('dependencies', []):
            dependents.append(task)
    
    if dependents:
        print('\033[1;33m↓ BLOCKS:\033[0m')
        for dep in dependents:
            status = dep.get('status', 'unknown')
            print(f"  • {dep.get('id')} ({status})")
    else:
        print('\033[0;32m↓ Nothing blocked\033[0m')
    
    sys.exit(0)

sys.exit(1)
EOF
        if [ $? -eq 0 ]; then
            found=true
            break
        fi
    fi
done

if [ "$found" = false ]; then
    echo -e "${RED}Task not found: $TASK_ID${NC}"
    exit 1
fi
