#!/bin/bash
# Discover all components in the monorepo
# Usage: ./scripts/discover.sh [--json]

set -e

JSON_OUTPUT=false
if [ "$1" = "--json" ]; then
    JSON_OUTPUT=true
fi

# Colors (only for non-JSON output)
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Component discovery
declare -a COMPONENTS

discover_components() {
    for type in services workers apps cli packages; do
        if [ -d "$type" ]; then
            for dir in "$type"/*/; do
                if [ -d "$dir" ] && [ "$dir" != "$type/*/" ]; then
                    name=$(basename "$dir")
                    path="$type/$name"
                    port=""
                    stack=""

                    # Detect stack type
                    if [ -f "$dir/go.mod" ]; then
                        stack="go"
                    elif [ -f "$dir/package.json" ]; then
                        stack="node"
                        # Try to detect framework
                        if grep -q "astro" "$dir/package.json" 2>/dev/null; then
                            stack="astro"
                        elif grep -q "react" "$dir/package.json" 2>/dev/null; then
                            stack="react"
                        fi
                    fi

                    # Try to get port from component.yaml
                    if [ -f "$dir/component.yaml" ]; then
                        port=$(grep -E '^port:' "$dir/component.yaml" 2>/dev/null | awk '{print $2}' || echo "")
                    fi

                    # Try to get port from .env.example
                    if [ -z "$port" ] && [ -f "$dir/.env.example" ]; then
                        port=$(grep -E '^PORT=' "$dir/.env.example" 2>/dev/null | cut -d'=' -f2 || echo "")
                    fi

                    COMPONENTS+=("$type|$name|$path|$port|$stack")
                fi
            done
        fi
    done
}

output_json() {
    echo "{"
    echo "  \"project\": \"{{PROJECT_NAME}}\","
    echo "  \"components\": ["

    local first=true
    for comp in "${COMPONENTS[@]}"; do
        IFS='|' read -r type name path port stack <<< "$comp"

        if [ "$first" = false ]; then
            echo ","
        fi
        first=false

        echo -n "    {\"type\": \"$type\", \"name\": \"$name\", \"path\": \"$path\""
        if [ -n "$port" ]; then
            echo -n ", \"port\": $port"
        fi
        if [ -n "$stack" ]; then
            echo -n ", \"stack\": \"$stack\""
        fi
        echo -n "}"
    done

    echo ""
    echo "  ]"
    echo "}"
}

output_pretty() {
    echo -e "${BLUE}Components in {{PROJECT_NAME}}${NC}"
    echo ""

    if [ ${#COMPONENTS[@]} -eq 0 ]; then
        echo -e "${YELLOW}No components found. Add one with:${NC}"
        echo "  curl -X POST .../projects/{{PROJECT_NAME}}/components -d '{\"type\":\"service\",\"name\":\"my-api\"}'"
        return
    fi

    # Group by type
    for type in services workers apps cli packages; do
        local has_type=false
        for comp in "${COMPONENTS[@]}"; do
            IFS='|' read -r ctype name path port stack <<< "$comp"
            if [ "$ctype" = "$type" ]; then
                if [ "$has_type" = false ]; then
                    echo -e "${GREEN}$type/${NC}"
                    has_type=true
                fi
                local info="  $name"
                if [ -n "$stack" ]; then
                    info="$info ${YELLOW}[$stack]${NC}"
                fi
                if [ -n "$port" ]; then
                    info="$info :$port"
                fi
                echo -e "$info"
            fi
        done
        if [ "$has_type" = true ]; then
            echo ""
        fi
    done

    echo "Total: ${#COMPONENTS[@]} component(s)"
    echo ""
    echo "Run './scripts/install.sh' to install all dependencies"
    echo "Run './scripts/dev.sh' to start local development"
}

# Main
discover_components

if [ "$JSON_OUTPUT" = true ]; then
    output_json
else
    output_pretty
fi
