# AI-Assisted Event Population Implementation Plan

## Overview

This plan implements AI-powered event form population using Anthropic Claude API, integrating seamlessly with the existing HVAC event creation system while maintaining WordPress security standards and TEC compatibility.

## Architecture Strategy

```
INPUT SOURCES          PROCESSING PIPELINE         OUTPUT INTEGRATION
┌─────────────────┐    ┌─────────────────┐        ┌─────────────────┐
│ • URLs          │    │ HVAC_AI_Event   │        │ Form Field      │
│ • Pasted Text   │───>│ _Populator      │──────>│ Population      │
│ • Descriptions  │    │ • Claude API    │        │ • TEC Meta      │
└─────────────────┘    │ • Validation    │        │ • Confidence    │
                       │ • Mapping       │        │ • User Review   │
                       └─────────────────┘        └─────────────────┘
```

## Phase 1: MVP Implementation

### 1.1 Core Infrastructure Setup

**API Configuration**
- Add `define('ANTHROPIC_API_KEY', 'your-key-here');` to wp-config.php
- Create `HVAC_AI_Config` class for secure API settings management
- Implement connectivity validation and error handling

**Core Service Implementation**
```php
// includes/class-hvac-ai-event-populator.php
class HVAC_AI_Event_Populator {
    use HVAC_Singleton_Trait;

    public function populate_from_input($input, $input_type) {
        // Structured Claude API call with web search enabled
        // Return standardized JSON with confidence scores
    }

    private function build_prompt($input, $context) {
        // Dynamic prompt with venue/organizer context
    }

    private function validate_response($response) {
        // Schema validation and sanitization
    }
}
```

**AJAX Endpoint Development**
- Extend existing `HVAC_Ajax_Handlers` class with `hvac_ai_populate_event`
- Integrate with `HVAC_Ajax_Security` framework
- Implement role validation: `hvac_trainer` or `hvac_master_trainer`
- Input validation and sanitization pipeline

### 1.2 Essential Field Mapping

**TEC Integration Points**
```php
private array $field_mapping = [
    'title' => 'event_title',
    'description' => 'event_description',
    'start_date' => 'event_start_datetime',
    'end_date' => 'event_end_datetime',
    'venue' => '_EventVenueID',
    'organizer' => '_EventOrganizerID',
    'cost' => 'event_cost',
    'capacity' => 'event_capacity'
];
```

**Data Processing Pipeline**
- Input sanitization using `sanitize_textarea_field()`
- URL validation for web sources
- Response parsing with JSON schema validation
- Basic venue/organizer duplicate detection

### 1.3 Minimum Viable Frontend

**Modal Interface Integration**
- Enhance existing template system in `templates/page-tec-create-event.php`
- Convert placeholder "AI Assist" button to functional interface
- Single input field supporting both URLs and text
- Basic loading states and error messaging

**JavaScript Integration**
```javascript
// assets/js/hvac-ai-assist.js
jQuery(document).ready(function($) {
    $('#ai-assist-btn').on('click', function() {
        showAIModal();
    });

    function processAIInput(input) {
        // AJAX call to backend endpoint
        // Handle loading states
        // Populate form fields on success
    }
});
```

## Phase 2: Enhanced UX & Validation

### 2.1 Advanced Modal Interface

**Three-Tab Input System**
- **URL Tab**: EventBrite, Facebook Events, custom sites
- **Text Tab**: Email/PDF content, formatted or unformatted
- **Description Tab**: Natural language event details

**Enhanced User Experience**
- Input type auto-detection with visual feedback
- Progressive loading states with detailed status messages
- Enhanced error handling with recovery suggestions

### 2.2 Robust Data Processing

**Venue/Organizer Intelligence**
```php
private function find_matching_venue($extracted_venue) {
    // Fuzzy matching against existing venues
    // Similarity scoring above 80% threshold
    // Return existing ID or create new venue
}

private function detect_duplicates($event_data) {
    // Check date + similar title combinations
    // Return warnings for potential duplicates
}
```

**Confidence Scoring System**
```php
private function calculate_confidence($field_value, $source_context) {
    // Per-field confidence scoring (0.0-1.0)
    // Overall extraction confidence
    // Completeness matrix for missing fields
}
```

### 2.3 Integration Polish

**Form Field Enhancement**
- Field-level confidence indicators (color-coded borders)
- Confidence matrix display modal
- Review and adjust workflow before final submission
- Seamless autosave integration

## Phase 3: Performance & Caching

### 3.1 Caching Implementation

**WordPress Transients Strategy**
```php
private function get_cached_response($input_hash) {
    return get_transient("hvac_ai_cache_{$input_hash}");
}

private function cache_response($input_hash, $response) {
    set_transient("hvac_ai_cache_{$input_hash}", $response, 24 * HOUR_IN_SECONDS);
}
```

**Cache Management**
- Content-based cache key generation
- 24-hour TTL for successful extractions
- Cache invalidation on venue/organizer updates
- Memory-optimized for shared hosting

### 3.2 Performance Optimization

**Request Management**
- Per-user rate limiting (configurable limits)
- Request timeout handling (30-second maximum)
- Error rate monitoring and alerting
- Prompt optimization for accuracy and speed

## Phase 4: Production Readiness

### 4.1 Testing Strategy

**Comprehensive Test Coverage**
- Unit tests for API response parsing
- Integration tests with various input formats
- Security testing for AJAX endpoints
- Performance validation on Cloudways environment

**Test Scenarios**
- EventBrite URLs, Facebook Events, custom sites
- Email formats, PDF content, unstructured text
- Minimal descriptions, detailed specifications
- Non-English content, past events, recurring events

### 4.2 Edge Case Handling

**Robust Error Management**
- Network timeout recovery with retry logic
- Malformed API response handling
- Rate limit exceeded graceful degradation
- Multiple event extraction (first event only)

**Security Hardening**
- Input validation against injection attacks
- API key security audit
- OWASP compliance verification
- WordPress security best practices

## Technical Specifications

### Prompt Engineering Strategy

```
System: You are an HVAC event extraction specialist for professional training calendar.

Context:
- Current date: {current_date}
- Existing venues: {venue_list}
- Existing organizers: {organizer_list}

Input: {user_input}

Extract event information and output ONLY valid JSON:
{
  "title": "string",
  "description": "string",
  "start_date": "YYYY-MM-DD",
  "start_time": "HH:MM",
  "end_date": "YYYY-MM-DD",
  "end_time": "HH:MM",
  "venue": {
    "name": "string",
    "address": "string",
    "confidence": 0.0-1.0
  },
  "organizer": {
    "name": "string",
    "email": "string",
    "confidence": 0.0-1.0
  },
  "cost": number,
  "capacity": number|null,
  "confidence": {
    "overall": 0.0-1.0,
    "per_field": {
      "title": 0.0-1.0,
      "dates": 0.0-1.0,
      "venue": 0.0-1.0
    }
  }
}

Rules:
1. Match venues/organizers to existing when similarity > 80%
2. Convert relative dates to absolute dates
3. Use null for missing fields, not empty strings
4. If multiple events found, extract primary event only
```

### File Structure

```
includes/
├── class-hvac-ai-event-populator.php    # Main AI service
├── class-hvac-ai-modal.php              # Modal interface handler
└── class-hvac-ai-config.php             # API configuration

assets/
├── js/hvac-ai-assist.js                 # Frontend JavaScript
└── css/hvac-ai-assist.css               # Modal styling

templates/
└── page-tec-create-event.php            # Enhanced with AI button
```

### Success Metrics

**Technical Performance**
- API response time < 10 seconds (target: 5 seconds)
- Field population accuracy > 85% against test dataset
- Zero security vulnerabilities in penetration testing
- 99.9% uptime for feature availability

**User Experience**
- 50% reduction in event submission time
- 75% of submissions use AI assistance
- Error rate < 5% requiring manual intervention
- User satisfaction score > 4/5

### Risk Mitigation

**Operational Risks**
- **API Failures**: Graceful degradation with clear error messages
- **Performance Issues**: Request queuing and rate limiting
- **Security Vulnerabilities**: Multi-layer validation and WordPress best practices

**Adoption Risks**
- **User Training**: Comprehensive documentation and tutorials
- **Feature Discovery**: Prominent UI placement and onboarding
- **Trust Building**: Confidence indicators and manual review workflow

## Next Steps

This implementation plan provides a clear roadmap from MVP to production-ready AI-assisted event population. The phased approach allows for early user feedback while maintaining the existing plugin's architecture and security standards.

The plan can be executed incrementally, with each phase building upon the previous foundation while delivering immediate value to HVAC trainers through reduced event submission friction.