#!/bin/bash

# Wasot Selector Parser Comprehensive Demo
# This script demonstrates all selector features documented in docs/selectors.md

set -e

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Build the selector parser if not already built
echo -e "${BLUE}Building selector parser...${NC}"
cargo build --bin selector_parser --release

SELECTOR_PARSER="./target/release/selector_parser"

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}Wasot Selector Parser Comprehensive Demo${NC}"
echo -e "${GREEN}========================================${NC}"

# Function to test a selector
test_selector() {
    local selector="$1"
    local description="$2"
    
    echo -e "\n${YELLOW}Testing: ${description}${NC}"
    echo -e "Selector: ${BLUE}${selector}${NC}"
    
    if $SELECTOR_PARSER "$selector" 2>/dev/null; then
        echo -e "${GREEN}✓ Successfully parsed${NC}"
    else
        echo -e "${RED}✗ Failed to parse${NC}"
        $SELECTOR_PARSER "$selector" 2>&1 | grep "Error"
    fi
}

# Function to test invalid selectors
test_invalid_selector() {
    local selector="$1"
    local description="$2"
    
    echo -e "\n${YELLOW}Testing (should fail): ${description}${NC}"
    echo -e "Selector: ${BLUE}${selector}${NC}"
    
    if $SELECTOR_PARSER "$selector" 2>/dev/null; then
        echo -e "${RED}✗ Unexpectedly succeeded${NC}"
    else
        echo -e "${GREEN}✓ Correctly rejected${NC}"
        $SELECTOR_PARSER "$selector" 2>&1 | grep "Error" | head -1
    fi
}

echo -e "\n${GREEN}=== Basic Selectors ===${NC}"
echo -e "As defined in docs/selectors.md"

test_selector "*" "Universal selector - selects all elements"
test_selector "paragraph" "Type selector - selects all blocks of type 'paragraph'"
test_selector "section" "Type selector - selects all blocks of type 'section'"
test_selector "#main-content" "ID selector - selects block with id 'main-content'"
test_selector "#id123" "ID selector with numbers"

echo -e "\n${GREEN}=== Argument Selectors ===${NC}"
echo -e "Equivalent to HTML attribute selectors"

test_selector "[author]" "Presence - has 'author' argument (positional or keyword)"
test_selector "[!draft]" "Negated presence - doesn't have 'draft' argument"
test_selector "[lang=\"en\"]" "Exact match - keyword arg with key 'lang' and value 'en'"
test_selector "[title=\"Hello World\"]" "Exact match with spaces in value"
test_selector "[key=value]" "Exact match without quotes (simple identifiers)"
test_selector "[data-id=\"123\"]" "Attribute with dashes"

echo -e "\n${GREEN}=== Child Selectors (Pseudo-classes) ===${NC}"
echo -e "Note: Text elements have no children"

test_selector ":first-child" "First child (text or block)"
test_selector ":first-block" "First block child (not text)"
test_selector ":first-text" "First text child (not block)"
test_selector ":last-child" "Last child (text or block)"
test_selector ":last-block" "Last block child"
test_selector ":last-text" "Last text child"
test_selector ":nth-child(3)" "3rd child element"
test_selector ":nth-block(2)" "2nd block (texts ignored in counting)"
test_selector ":nth-text(1)" "1st text (blocks ignored in counting)"
test_selector ":not(paragraph)" "Negation - not a paragraph"
test_selector ":not(#intro)" "Negation - not id 'intro'"
test_selector ":not([draft])" "Negation - doesn't have draft attribute"

echo -e "\n${GREEN}=== Combinators ===${NC}"
echo -e "Connect simple selectors with relationships"

test_selector "paragraph quote" "Descendant - quote inside paragraph (any depth)"
test_selector "section > paragraph" "Child - paragraph directly inside section"
test_selector "h1 + paragraph" "Adjacent sibling - paragraph immediately after h1"
test_selector "h1 ~ paragraph" "General sibling - any paragraph after h1"

echo -e "\n${GREEN}=== Complex Selectors ===${NC}"
echo -e "Combining multiple features"

test_selector "section#intro" "Type + ID"
test_selector "paragraph[lang=\"en\"]" "Type + attribute"
test_selector "quote:first-child" "Type + pseudo-class"
test_selector "*[author]:last-block" "Universal + attribute + pseudo-class"
test_selector "#main[featured]:not([draft])" "ID + attribute + negation"
test_selector "article > section#intro[lang=\"en\"] paragraph:first-child" "Complex nested selector"
test_selector "div[data-id]:not([hidden]) > span + a" "Complex with multiple combinators"
test_selector "section:not(#intro):first-child" "Multiple pseudo-classes"

echo -e "\n${GREEN}=== OR Selectors (Grouping) ===${NC}"
echo -e "Multiple selectors separated by comma - matches any of the selectors"

test_selector "h1, h2, h3" "Heading selectors - matches any heading level 1, 2, or 3"
test_selector "paragraph, quote" "Text block selectors - matches paragraphs or quotes"
test_selector "section > p, article > div" "Complex OR - child selectors with different parents"
test_selector "#main, header" "Mixed selectors - ID and type"
test_selector ":not(p, div)" "OR inside negation - not paragraph and not div"
test_selector "section:not(#intro), p[lang]" "Complex mixed OR selectors"

echo -e "\n${GREEN}=== Quoted Identifiers ===${NC}"
echo -e "Types, IDs, and attributes with spaces require quotes"

test_selector "\"type with space\"" "Type selector with spaces in quotes"
test_selector "#\"id with space\"" "ID selector with spaces in quotes"
test_selector "[\"key with space\"=\"value with space\"]" "Attribute with spaces in both key and value"
test_selector "\"parent type\" > \"child type\"" "Combinator with quoted types"
test_selector "\"type with space\"#\"id with space\"[\"attr\"=\"val\"]:first-child" "Complex selector with quoted identifiers"
test_selector "\"type one\", \"type two\", \"type three\"" "OR selector with quoted types"
test_selector "[title=\"She said \\\"hello\\\" to me\"]" "Quoted value with escaped quotes (literal backslashes preserved)"
test_selector "\"type \\\"with\\\" quotes\"" "Quoted type with escaped quotes"
test_selector "#\"id \\\"with\\\" quotes\"" "Quoted ID with escaped quotes"
test_selector "\"\"" "Empty quoted identifier"
test_selector "\"   \"" "Quoted identifier with just spaces"
test_selector "\"type@#\$%^&*()+={}[]|\\\\:;'<>,.?/\"" "Quoted identifier with special characters"

echo -e "\n${GREEN}=== Edge Cases ===${NC}"
echo -e "Testing parser robustness"

test_selector "_private-element" "Identifier starting with underscore"
test_selector "data-table-123" "Identifier with numbers and dashes"
test_selector "[title=\"\"]" "Empty attribute value"
test_selector "a>b+c~d" "Combinators without spaces"
test_selector ":not(:not(:not(p)))" "Deeply nested negation"
test_selector "*:not(*:first-child)" "Complex universal selector"
test_selector "#id1#id2" "Multiple IDs (last one wins)"
test_selector "p:not([a]):not([b]):not([c])" "Multiple negations"
test_selector ":nth-child(999999)" "Large nth value"

echo -e "\n${GREEN}=== Invalid Selectors ===${NC}"
echo -e "These should fail to parse"

test_invalid_selector "" "Empty selector"
test_invalid_selector "##double-hash" "Invalid ID syntax"
test_invalid_selector "[" "Unclosed attribute"
test_invalid_selector ":nth-child(abc)" "Invalid nth argument"
test_invalid_selector "div >" "Trailing combinator"
test_invalid_selector "> div" "Leading combinator"
test_invalid_selector "[attr=\"unclosed]" "Unclosed string"
test_invalid_selector ":unknown-pseudo" "Unknown pseudo-class"
test_invalid_selector "p, div," "Trailing comma in OR selector"
test_invalid_selector ",p" "Leading comma in OR selector"
test_invalid_selector "p,," "Double comma in OR selector"

echo -e "\n${GREEN}=== Running Unit Tests ===${NC}"
echo -e "Testing all edge cases..."

if cargo test --bin selector_parser --release --quiet; then
    echo -e "${GREEN}✓ All unit tests passed${NC}"
else
    echo -e "${RED}✗ Some unit tests failed${NC}"
fi

echo -e "\n${GREEN}=== Running Benchmarks ===${NC}"
echo -e "Performance testing..."

$SELECTOR_PARSER --bench

echo -e "\n${GREEN}=== Demo Complete ===${NC}"
echo -e "All selector features from docs/selectors.md have been demonstrated."
echo -e "\n${BLUE}Features Implemented:${NC}"
echo -e "✓ Basic selectors: *, type-name, #id"
echo -e "✓ Argument selectors: [attr], [!attr], [key=\"value\"]"
echo -e "✓ Pseudo-classes: :first-child, :last-child, :nth-child(n), :not()"
echo -e "✓ Combinators: space (descendant), > (child), + (adjacent), ~ (sibling)"
echo -e "✓ OR selectors: comma-separated groups"
echo -e "✓ Quoted identifiers: support for spaces and special characters in types/IDs/attributes (NEW!)"
echo -e "✓ Complex combinations and nesting"
echo -e "\n${BLUE}Notes:${NC}"
echo -e "- Class selectors (.class) are not implemented yet (as noted in docs)"
echo -e "- Advanced attribute selectors (^=, $=, *=) are planned for future"
echo -e "- Advanced nth syntax (2n+1, odd, even) is planned for future"