# Bitwise Helper Files - Usage Guide

## 📁 Generated Files

1. **`data/product_bitwise.csv`** - CSV format with bit values for each product
2. **`data/product_bitwise.json`** - JSON format with bit values for each product
3. **`data/bitwise_legend.json`** - Complete bit mapping documentation

## 🔢 Bit System Overview

Each product gets a single integer value that encodes multiple attributes using bitwise flags.

### Bit Positions (0-11): Base Attributes, Materials, Colors

| Bit | Value | Attribute |
|-----|-------|-----------|
| 0 | 1 | Door |
| 1 | 2 | Window |
| 2 | 4 | Is Accessory |
| 3 | 8 | Specific Item Link |
| 4 | 16 | Aluminum Material |
| 5 | 32 | Vinyl Material |
| 6 | 64 | Black Color |
| 7 | 128 | White Color |
| 8 | 256 | Bronze Color |
| 9 | 512 | Tan Color |
| 10 | 1024 | Mill Color |
| 11 | 2048 | Sandstone Color |

### Bit Positions (12+): Sub-types

| Bit | Value | Sub-type |
|-----|-------|----------|
| 12 | 4096 | Patio Door |
| 13 | 8192 | Primary Window |
| 14 | 16384 | Storm Door |
| 15 | 32768 | Storm Window |

## 💡 Usage Examples

### Example 1: Storm Door Insert (BGIST)
```
Product Code: BGIST
Description: INSERTS FOR STORM DOORS
Bit Value: 17553
Binary: 0100010010010001

Decoded:
  ✓ Door (bit 0 = 1)
  ✗ Window (bit 1 = 0)
  ✗ Accessory (bit 2 = 0)
  ✗ Specific Item (bit 3 = 0)
  ✓ Aluminum (bit 4 = 1)
  ✗ Vinyl (bit 5 = 0)
  ✓ Black (bit 6 = 1)
  ✓ White (bit 7 = 1)
  ✓ Bronze (bit 8 = 1)
  ✗ Tan (bit 9 = 0)
  ✓ Mill (bit 10 = 1)
  ✓ Sandstone (bit 11 = 1)
  ✗ Patio Door (bit 12 = 0)
  ✗ Primary Window (bit 13 = 0)
  ✓ Storm Door (bit 14 = 1)
  ✗ Storm Window (bit 15 = 0)
```

### Example 2: Check Attributes in Code

#### Python
```python
import json

# Load helper file
with open('data/product_bitwise.json') as f:
    products = json.load(f)

# Get a product
product = next(p for p in products if p['PROD_CODE'] == 'BGIST')
bit_value = product['BIT_VALUE']

# Check individual flags
is_door = bool(bit_value & 1)
is_aluminum = bool(bit_value & 16)
is_white = bool(bit_value & 128)
is_storm_door = bool(bit_value & 16384)

print(f"BGIST is door: {is_door}")
print(f"BGIST is aluminum: {is_aluminum}")
print(f"BGIST is white: {is_white}")
print(f"BGIST is storm door subtype: {is_storm_door}")

# Filter products by multiple criteria
# Example: Find all aluminum doors with white color
aluminum_white_doors = [
    p for p in products 
    if (p['BIT_VALUE'] & 1) and         # Is a door
       (p['BIT_VALUE'] & 16) and        # Has aluminum
       (p['BIT_VALUE'] & 128) and       # Has white
       not p['DISCONTINUED']             # Not discontinued
]

print(f"Found {len(aluminum_white_doors)} aluminum white doors")
```

#### JavaScript
```javascript
// Load the JSON file
fetch('data/product_bitwise.json')
  .then(response => response.json())
  .then(products => {
    // Check individual flags
    const product = products.find(p => p.PROD_CODE === 'BGIST');
    const bitValue = product.BIT_VALUE;
    
    const isDoor = !!(bitValue & 1);
    const isAluminum = !!(bitValue & 16);
    const isWhite = !!(bitValue & 128);
    const isStormDoor = !!(bitValue & 16384);
    
    console.log(`BGIST is door: ${isDoor}`);
    console.log(`BGIST is aluminum: ${isAluminum}`);
    console.log(`BGIST is white: ${isWhite}`);
    console.log(`BGIST is storm door: ${isStormDoor}`);
    
    // Filter products
    const aluminumWhiteDoors = products.filter(p => 
      (p.BIT_VALUE & 1) &&      // Is a door
      (p.BIT_VALUE & 16) &&     // Has aluminum
      (p.BIT_VALUE & 128) &&    // Has white
      !p.DISCONTINUED            // Not discontinued
    );
    
    console.log(`Found ${aluminumWhiteDoors.length} aluminum white doors`);
  });
```

## 🎯 Benefits of Bitwise Classification

### 1. **Multi-Group Assignment**
Products can belong to multiple categories simultaneously:
- A product can be both Door AND Window (rare but possible)
- A product can have multiple materials (Aluminum AND Vinyl)
- A product can have multiple colors

### 2. **Fast Filtering**
Bitwise operations are extremely fast:
```python
# Instead of:
if product.baseType == 'Door' and 'Aluminum' in product.materials and 'White' in product.colors:
    
# Use:
if (bit_value & 1) and (bit_value & 16) and (bit_value & 128):
```

### 3. **Compact Storage**
One integer stores multiple attributes:
- Single integer vs. multiple boolean fields
- Easy to index and search in databases
- Efficient for large datasets

### 4. **Easy Matching**
Perfect for accessory compatibility:
```python
# Check if accessory matches product materials
accessory_materials = 48  # Aluminum (16) + Vinyl (32)
product_materials = 16    # Aluminum only

# Check if they share any materials
if accessory_materials & product_materials:
    print("Compatible!")  # True because both have Aluminum
```

## 🔄 Integration with Navigation System

Use bitwise values to:
1. Dynamically generate navigation options
2. Filter products in real-time based on user selections
3. Match accessories to products efficiently
4. Handle complex "OR" queries (multiple categories)

### Example: Dynamic Material Question
```python
# Get all products for "Storm Door" subtype
storm_door_products = [p for p in products if p['BIT_VALUE'] & 16384]

# Check materials
has_aluminum = any(p['BIT_VALUE'] & 16 for p in storm_door_products)
has_vinyl = any(p['BIT_VALUE'] & 32 for p in storm_door_products)

# Show material question only if multiple materials exist
if has_aluminum and has_vinyl:
    show_material_question()
else:
    skip_to_next_question()
```

## 📝 Maintenance

### Regenerating Helper Files
When products.csv changes:
```bash
python generate_bitwise_helper.py
```

### Adding New Attributes
To add new bit flags, edit `generate_bitwise_helper.py`:
1. Add to `BIT_DEFINITIONS` dictionary
2. Update `calculate_bit_value()` function
3. Regenerate files

### Adding New Sub-types
Sub-types are automatically detected! Just add them to columns H or I in the CSV, then regenerate.

## 🚀 Performance Notes

- Bitwise AND (`&`) - Check if flag is set: `bit_value & 16`
- Bitwise OR (`|`) - Combine flags: `16 | 128` = Aluminum + White
- Bitwise NOT (`~`) - Invert flags (advanced)
- Bitwise XOR (`^`) - Toggle flags (advanced)

All bitwise operations are O(1) - constant time!
