#!/usr/bin/env bash
# =============================================================================
# Phase 8: Advanced Scenarios
# =============================================================================
# Presets, airgap, cluster management, concurrent ops, security checks.
# =============================================================================

print_phase "Phase 8: Advanced Scenarios"

# Ensure we're connected
if ! "$ILUM" config show &>/dev/null; then
    "$ILUM" connect --release "$HELM_RELEASE" --namespace "$HELM_NAMESPACE" --yes 2>/dev/null || true
fi

# ---- Install dry-run with presets (should fail — release already exists) ----

run_test "P8-001" "install --dry-run development preset" "$ILUM" install --dry-run --preset development
# Should either show a plan or fail because release exists
assert_exit_code 0 || {
    # If it fails because release exists, that's also acceptable
    if echo "$LAST_STDOUT$LAST_STDERR" | grep -qiE "already|exists|installed"; then
        PASSED_TESTS=$((PASSED_TESTS + 1))  # correct the count
        FAILED_TESTS=$((FAILED_TESTS - 1))
        print_pass "P8-001 — install correctly detects existing release"
        echo "PASS" > "$TEST_LOG_DIR/P8-001/result.txt"
        # remove last failure entry
        unset 'FAILURES[${#FAILURES[@]}-1]'
    fi
    true
}

run_test "P8-002" "install --dry-run production preset (release exists)" "$ILUM" install --dry-run --preset production
# Should fail because release already exists — that's correct behavior
if [[ "$LAST_EXIT_CODE" -ne 0 ]]; then
    PASSED_TESTS=$((PASSED_TESTS + 1))
    print_pass "P8-002 — install correctly detects existing release for production preset"
    echo "PASS" > "$TEST_LOG_DIR/P8-002/result.txt"
else
    assert_exit_code 0 || true
fi

run_test "P8-003" "install --dry-run air-gapped preset (release exists)" "$ILUM" install --dry-run --preset air-gapped
# Should fail because release exists or air-gapped requires --set global.imageRegistry
if [[ "$LAST_EXIT_CODE" -ne 0 ]]; then
    PASSED_TESTS=$((PASSED_TESTS + 1))
    print_pass "P8-003 — install correctly rejects (release exists or missing required input)"
    echo "PASS" > "$TEST_LOG_DIR/P8-003/result.txt"
else
    assert_exit_code 0 || true
fi

run_test "P8-004" "install --dry-run invalid preset" "$ILUM" install --dry-run --preset nonexistent_preset
assert_exit_code_not 0 || true

# ---- Install when release exists ----

run_test "P8-005" "install when release exists" "$ILUM" install --yes
if [[ "$LAST_EXIT_CODE" -ne 0 ]]; then
    # Should fail with helpful message
    PASSED_TESTS=$((PASSED_TESTS + 1))
    print_pass "P8-005 — install rejects when release exists"
    echo "PASS" > "$TEST_LOG_DIR/P8-005/result.txt"
else
    log_issue "BUG" "high" "P8-005" "install succeeded when release already exists"
    FAILED_TESTS=$((FAILED_TESTS + 1))
    print_fail "P8-005 — install should fail when release exists"
    echo "FAIL" > "$TEST_LOG_DIR/P8-005/result.txt"
    FAILURES+=("P8-005: install succeeded when release already exists")
fi

# ---- Airgap commands ----

run_test "P8-006" "airgap images list" "$ILUM" airgap images
assert_exit_code 0 || true

run_test "P8-007" "airgap images --format plain" "$ILUM" airgap images --format plain
assert_exit_code 0 || true

run_test "P8-008" "airgap images --preset development --module airflow" "$ILUM" airgap images --preset development --module airflow
assert_exit_code 0 || true

run_test "P8-009" "airgap images --preset development" "$ILUM" airgap images --preset development
assert_exit_code 0 || true

run_test "P8-010" "airgap import nonexistent bundle" "$ILUM" airgap import /nonexistent/bundle --registry localhost:5000
assert_exit_code_not 0 || true

# ---- Global overrides ----

run_test "P8-011" "status with --namespace override" "$ILUM" status --namespace "$HELM_NAMESPACE"
assert_exit_code 0 || true

# ---- Uninstall dry-run ----

run_test "P8-012" "uninstall --dry-run" "$ILUM" uninstall --dry-run
assert_exit_code 0 || true

run_test "P8-013" "uninstall --dry-run --delete-data" "$ILUM" uninstall --dry-run --delete-data
assert_exit_code 0 || true

run_test "P8-014" "uninstall --dry-run --delete-namespace" "$ILUM" uninstall --dry-run --delete-namespace
assert_exit_code 0 || true

# ---- Cluster operations ----

# Try creating cluster with kind (likely not installed)
run_test "P8-015" "cluster create with kind (unavailable)" "$ILUM" cluster create --provider kind --name test-e2e
if [[ "$LAST_EXIT_CODE" -ne 0 ]]; then
    PASSED_TESTS=$((PASSED_TESTS + 1))
    print_pass "P8-015 — cluster create with kind fails (expected, kind not installed)"
    echo "PASS" > "$TEST_LOG_DIR/P8-015/result.txt"
else
    # If it succeeded, it created a cluster — need to clean up
    log_info "Cleaning up unexpected kind cluster"
    "$ILUM" cluster delete test-e2e 2>/dev/null || true
    PASSED_TESTS=$((PASSED_TESTS + 1))
    print_pass "P8-015 — cluster create with kind succeeded (unexpected)"
    echo "PASS" > "$TEST_LOG_DIR/P8-015/result.txt"
fi

run_test "P8-016" "cluster delete nonexistent" "$ILUM" cluster delete nonexistent_cluster_xyz
assert_exit_code_not 0 || true

# ---- Empty string arguments ----

run_test "P8-017" "module enable empty string" "$ILUM" module enable "" --dry-run
assert_exit_code_not 0 || true

run_test "P8-018" "upgrade --set empty" "$ILUM" upgrade --dry-run --set ""
assert_exit_code_not 0 || {
    # If it succeeded, that's also somewhat acceptable (no-op)
    log_issue "UX" "low" "P8-018" "upgrade --set '' accepted without error"
    true
}

# ---- Many modules at once ----

run_test "P8-019" "enable many modules --dry-run" "$ILUM" module enable airflow kestra mlflow superset trino --dry-run
assert_exit_code 0 || true

# ---- Doctor with fix ----

run_test "P8-020" "doctor --fix" "$ILUM" doctor --fix
assert_exit_code 0 || true

# ---- Doctor specific check ----

run_test "P8-021" "doctor --failures-only" "$ILUM" doctor --failures-only
assert_exit_code 0 || true

# ---- Security: audit log contents ----

AUDIT_LOG="$HOME/.local/state/ilum/audit.jsonl"
if [[ -f "$AUDIT_LOG" ]]; then
    run_test "P8-022" "audit log exists and has entries" cat "$AUDIT_LOG"
    assert_output_not_empty || true

    # Check audit log for secrets
    run_test "P8-023" "audit log security check" cat "$AUDIT_LOG"
    assert_not_contains "CHANGEMEPLEASE" || {
        log_issue "SECURITY" "high" "P8-023" "Audit log contains default password placeholder"
        true
    }
else
    skip_test "P8-022" "audit log exists" "no audit log found"
    skip_test "P8-023" "audit log security" "no audit log found"
fi

# ---- Security: snapshot files ----

SNAPSHOT_DIR="$HOME/.local/state/ilum/snapshots"
if [[ -d "$SNAPSHOT_DIR" ]]; then
    run_test "P8-024" "snapshot directory permissions" stat -c "%a" "$SNAPSHOT_DIR"
    # Just log the permissions
    PERMS="$LAST_STDOUT"
    if [[ "$PERMS" =~ ^7 ]]; then
        PASSED_TESTS=$((PASSED_TESTS + 1))
        print_pass "P8-024 — snapshot dir has restrictive owner permissions"
        echo "PASS" > "$TEST_LOG_DIR/P8-024/result.txt"
    else
        log_issue "SECURITY" "low" "P8-024" "Snapshot directory permissions: $PERMS"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        print_pass "P8-024 — snapshot dir permissions: $PERMS"
        echo "PASS" > "$TEST_LOG_DIR/P8-024/result.txt"
    fi
else
    skip_test "P8-024" "snapshot dir permissions" "no snapshot directory"
fi

# ---- CI/CD pattern: quiet JSON piped to jq ----

run_test "P8-025" "quiet json status piped to processing" bash -c "$ILUM --quiet --output json status 2>/dev/null | python3 -c 'import sys,json; d=json.load(sys.stdin); print(\"ok\")' 2>/dev/null || echo 'parse_failed'"
if echo "$LAST_STDOUT" | grep -q "ok"; then
    PASSED_TESTS=$((PASSED_TESTS + 1))
    print_pass "P8-025 — quiet JSON output is parseable"
    echo "PASS" > "$TEST_LOG_DIR/P8-025/result.txt"
else
    log_issue "BUG" "medium" "P8-025" "quiet JSON output not parseable by downstream tools"
    FAILED_TESTS=$((FAILED_TESTS + 1))
    print_fail "P8-025 — quiet JSON output not parseable"
    echo "FAIL" > "$TEST_LOG_DIR/P8-025/result.txt"
    FAILURES+=("P8-025: quiet JSON output not parseable")
fi

# ---- Concurrent operations (race condition test) ----

run_test "P8-026" "concurrent dry-run operations" bash -c "$ILUM upgrade --dry-run &>/tmp/e2e-race1.txt & $ILUM status &>/tmp/e2e-race2.txt & wait; echo 'done'"
assert_exit_code 0 || true

# ---- Doctor full run ----

run_test "P8-027" "doctor full check" "$ILUM" doctor
assert_exit_code 0 || true

log_info "Phase 8 complete — advanced scenarios tested"
