#!/bin/bash
# Validate and display repository status

REPO_DIR="/root/mihon-repo"
INDEX_FILE="$REPO_DIR/repo/index.json"

echo "=========================================="
echo "  Mihon/Tachiyomi Repository Validator"
echo "=========================================="
echo ""

# Check directory structure
echo "📁 Directory Structure:"
if [ -d "$REPO_DIR/repo" ]; then
    echo "  ✓ repo/ directory exists"
else
    echo "  ✗ repo/ directory missing"
fi

if [ -d "$REPO_DIR/apk" ]; then
    echo "  ✓ apk/ directory exists"
else
    echo "  ✗ apk/ directory missing"
fi

echo ""

# Validate JSON
echo "📄 Index File:"
if [ -f "$INDEX_FILE" ]; then
    echo "  ✓ index.json exists"
    if python3 -c "import json; data = json.load(open('$INDEX_FILE')); print(f'  ✓ Valid JSON')" 2>/dev/null; then
        # Count extensions
        EXT_COUNT=$(python3 -c "import json; data = json.load(open('$INDEX_FILE')); print(len(data.get('extensions', [])))")
        echo "  📦 Extensions listed: $EXT_COUNT"
        
        # Show extension names
        if [ "$EXT_COUNT" -gt 0 ]; then
            echo "  📋 Extension names:"
            python3 -c "import json; data = json.load(open('$INDEX_FILE')); [print(f'     - {e[\"name\"]} ({e[\"pkg\"]})') for e in data.get('extensions', [])]"
        fi
    else
        echo "  ✗ Invalid JSON syntax"
    fi
else
    echo "  ✗ index.json missing"
fi

echo ""

# Check APK files
echo "📦 APK Files:"
APK_COUNT=$(find "$REPO_DIR/apk" -name "*.apk" 2>/dev/null | wc -l)
if [ "$APK_COUNT" -gt 0 ]; then
    echo "  ✓ Found $APK_COUNT APK file(s)"
    find "$REPO_DIR/apk" -name "*.apk" -exec basename {} \; | sed 's/^/     - /'
else
    echo "  ℹ No APK files found (add extensions to apk/ directory)"
fi

echo ""

# Network info
echo "🌐 Network Information:"
IP_ADDR=$(hostname -I | awk '{print $1}')
echo "  Local IP: $IP_ADDR"
echo "  Repository URL: http://$IP_ADDR:8080/repo/"

echo ""

# Check if server is running
echo "🖥️  Server Status:"
if curl -s http://localhost:8080/repo/index.json > /dev/null 2>&1; then
    echo "  ✓ Server is running on port 8080"
else
    echo "  ℹ Server not running (run ./start-server.sh)"
fi

echo ""
echo "=========================================="