#!/bin/bash

# ====================================================
#      KATA CLI - OPEN THE WIRE ENGINE
# ====================================================

SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
STATE_FILE="$SCRIPT_DIR/.kata_state"

# Load environment securely
if [ -f "$SCRIPT_DIR/.env" ]; then
    export $(grep -v '^#' "$SCRIPT_DIR/.env" | xargs)
fi

API_URL="https://api.groq.com/openai/v1/chat/completions"
MODEL="openai/gpt-oss-20b"

# Ensure API key is configured
if [ -z "$GROQ_API_KEY" ]; then
    echo "Error: GROQ_API_KEY is not defined in $SCRIPT_DIR/.env"
    exit 1
fi

COMMAND=$1

case $COMMAND in
    start)
        echo "Initializing new Kata environment..."
        
        # Scenarios: "Topic | Break Command | Goal | Telemetry Command"
        SCENARIOS=(
            "File Permissions|sudo chmod 000 /sandbox/test.txt|Fix permissions on /sandbox/test.txt to 644|ls -la /sandbox/test.txt"
            "Hidden Files|touch /sandbox/.secret && sudo chmod 000 /sandbox/.secret|Fix permissions on /sandbox/.secret to 644|ls -la /sandbox/.secret"
        )
        
        # Pick random scenario and parse using pipe delimiter
        RANDOM_SCENARIO=${SCENARIOS[$RANDOM % ${#SCENARIOS[@]}]}
        IFS='|' read -r TOPIC BREAK_CMD GOAL TELEMETRY <<< "$RANDOM_SCENARIO"

        # Save active scenario to state file
        echo "GOAL=\"$GOAL\"" > "$STATE_FILE"
        echo "TELEMETRY=\"$TELEMETRY\"" >> "$STATE_FILE"

        PROMPT="Generate a short, realistic sysadmin troubleshooting scenario where a Linux administrator broke '$TOPIC' using the command: '$BREAK_CMD'. Give it a title and a brief problem statement."

        PAYLOAD=$(jq -n --arg model "$MODEL" --arg prompt "$PROMPT" '{model: $model, messages: [{"role": "user", "content": $prompt}], stream: false}')
        
        RESPONSE=$(curl -s -X POST "$API_URL" -H "Content-Type: application/json" -H "Authorization: Bearer $GROQ_API_KEY" -d "$PAYLOAD")

        if echo "$RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
            echo "API request failed:" && echo "$RESPONSE" | jq -r '.error.message // .' && exit 1
        fi

        echo ""
        echo "--- INCOMING TRANSMISSION ---"
        echo "$RESPONSE" | jq -r '.choices[0].message.content // empty'
        echo "-----------------------------"
        echo ""

        echo "[Mutation] Applying chaotic state..."
        sudo mkdir -p /sandbox
        sudo chown zimasu:zimasu /sandbox
        echo "critical config" | sudo tee /sandbox/test.txt > /dev/null
        eval "$BREAK_CMD"
        echo "Environment mutated. Good luck."
        echo "Run 'kata check' when you think you have solved it."
        ;;

    check)
        if [ ! -f "$STATE_FILE" ]; then
            echo "No active kata found. Run 'kata start' first."
            exit 1
        fi

        # Load active scenario goals
        source "$STATE_FILE"

        echo "[Telemetry] Harvesting system state..."
        CURRENT_STATE=$(eval "$TELEMETRY" 2>&1)

        DIAGNOSTIC_PROMPT="You are a strict Linux grading engine. 
The user's goal was: $GOAL
Here is the exact current system telemetry (output of '$TELEMETRY'):
$CURRENT_STATE

Did the user successfully fix the problem? 
Format your response starting with either 'PASS' or 'FAIL', followed by a short explanation."

        PAYLOAD=$(jq -n --arg model "$MODEL" --arg prompt "$DIAGNOSTIC_PROMPT" '{model: $model, messages: [{"role": "user", "content": $prompt}], stream: false}')

        RESPONSE=$(curl -s -X POST "$API_URL" -H "Content-Type: application/json" -H "Authorization: Bearer $GROQ_API_KEY" -d "$PAYLOAD")

        if echo "$RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
            echo "Grading API request failed:" && echo "$RESPONSE" | jq -r '.error.message // .' && exit 1
        fi

        DIAGNOSIS=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // "Error"')

        echo ""
        echo "--- AI AUDIT RESULT ---"
        echo "$DIAGNOSIS"
        echo "-----------------------"

        if [[ "$DIAGNOSIS" == *"PASS"* ]]; then
            echo "Audit passed. Clearing state."
            rm "$STATE_FILE"
	    sudo rm -rf /sandbox
	    echo "Cleanup complete. You are ready for the next kata."
        fi
        ;;
help)
        if [ ! -f "$STATE_FILE" ]; then
            echo "No active kata found. Run 'kata start' first."
            exit 1
        fi

        # Load active scenario goals
        source "$STATE_FILE"

        echo "[Help] Requesting tactical assistance from Groq..."

        HELP_PROMPT="The user is currently stuck on a Linux troubleshooting challenge. 
Their goal is: $GOAL
Provide a brief, conceptual hint or point them to the right Linux tool (e.g., man pages, specific commands) to use. Do not just give them the exact copy-paste solution immediately. Be encouraging."

        PAYLOAD=$(jq -n --arg model "$MODEL" --arg prompt "$HELP_PROMPT" '{model: $model, messages: [{"role": "user", "content": $prompt}], stream: false}')

        RESPONSE=$(curl -s -X POST "$API_URL" -H "Content-Type: application/json" -H "Authorization: Bearer $GROQ_API_KEY" -d "$PAYLOAD")

        if echo "$RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
            echo "API request failed:" && echo "$RESPONSE" | jq -r '.error.message // .' && exit 1
        fi

        HINT=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // "Error generating hint."')

        echo ""
        echo "--- TACTICAL HINT ---"
        echo "$HINT"
        echo "---------------------"
        ;;
*)
        echo "Usage: kata {start|check|help}"
        exit 1
        ;;
esac
