# Developer Guide

This guide covers the technical architecture and extension points for developers.

## Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│                    WordPress Plugin                          │
├─────────────────────────────────────────────────────────────┤
│  Sync Queue (Background)                                     │
│  ├── Add to queue on publish/update                         │
│  ├── WP-Cron processes batches of 25                        │
│  └── Retry queue for failures (3 attempts, exp. backoff)    │
├─────────────────────────────────────────────────────────────┤
│  Extractors (Lazy Loaded)                                    │
│  ├── Post (core data)                                        │
│  ├── SEO: Yoast | RankMath | AIOSEO                         │
│  ├── Recipe: WPRM | Tasty | Create                          │
│  └── Links (regex-based, max 200 per post)                  │
├─────────────────────────────────────────────────────────────┤
│  API Client                                                  │
│  ├── 15s timeout with 2 retries                             │
│  ├── Client-side rate limiting (60/min)                     │
│  └── Health check (hourly cron)                             │
└─────────────────────────────────────────────────────────────┘
```

## File Structure

```
phynite-analytics/
├── phynite-analytics.php      # Main plugin file, autoloader
├── uninstall.php              # Cleanup on uninstall
├── readme.txt                 # WordPress.org readme
├── includes/
│   ├── class-phynite-activator.php      # Activation handler
│   ├── class-phynite-deactivator.php    # Deactivation handler
│   ├── class-phynite-admin.php          # Admin settings page
│   ├── class-phynite-api-client.php     # API communication
│   ├── class-phynite-sync.php           # Sync orchestration
│   ├── class-phynite-sync-queue.php     # Background sync queue
│   ├── class-phynite-retry-queue.php    # Failed sync retry
│   ├── class-phynite-rate-limiter.php   # API rate limiting
│   ├── class-phynite-logger.php         # Debug logging
│   └── extractors/
│       ├── class-phynite-post-extractor.php     # Core post data
│       ├── class-phynite-links-extractor.php    # Internal links
│       ├── class-phynite-yoast-extractor.php    # Yoast SEO
│       ├── class-phynite-rankmath-extractor.php # RankMath
│       ├── class-phynite-aioseo-extractor.php   # AIOSEO
│       ├── class-phynite-wprm-extractor.php     # WP Recipe Maker
│       ├── class-phynite-tasty-extractor.php    # Tasty Recipes
│       └── class-phynite-create-extractor.php   # Mediavine Create
├── templates/
│   └── admin-page.php         # Admin settings template
├── assets/
│   ├── css/admin.css          # Admin styles
│   └── js/admin.js            # Admin JavaScript
└── languages/                 # Translation files
```

## Key Classes

### Phynite_Sync

The main orchestrator class that:
- Registers WordPress hooks for publish/update events
- Coordinates data extraction from all extractors
- Handles AJAX requests for manual sync operations

### Phynite_Sync_Queue

Background processing queue that:
- Stores pending syncs in `wp_options`
- Processes batches via WP-Cron
- Implements debouncing (30-second cooldown per post)
- Deduplicates queue entries

### Phynite_Retry_Queue

Handles failed syncs with:
- Exponential backoff (5, 10, 20 minutes)
- Maximum 3 retry attempts
- Queue size limit of 100 items

### Phynite_API_Client

Handles all API communication:
- Timeout: 15s for POST, 10s for GET
- Automatic retry on failure (2 retries, 500ms backoff)
- Integrates with rate limiter

### Extractors

All extractors follow a common pattern:

```php
class Phynite_Example_Extractor {
    public function is_active() {
        // Return true if the related plugin is active
    }

    public function extract( $post_id ) {
        // Return array of extracted data or null
    }
}
```

Extractors are lazy-loaded only when needed to minimize memory usage.

## Constants

```php
PHYNITE_VERSION          // Plugin version (e.g., '1.0.0')
PHYNITE_PLUGIN_FILE      // Main plugin file path
PHYNITE_PLUGIN_DIR       // Plugin directory path
PHYNITE_PLUGIN_URL       // Plugin URL
PHYNITE_PLUGIN_BASENAME  // Plugin basename
PHYNITE_API_URL          // API endpoint URL
```

## Debug Mode

Enable debug logging by adding to `wp-config.php`:

```php
define( 'PHYNITE_DEBUG', true );
```

Logs are stored in the `phynite_debug_log` option (max 100 entries) and also written to `error_log` if `WP_DEBUG` is enabled.

## Database

The plugin uses only WordPress options (no custom tables):

| Option Name | Description |
|-------------|-------------|
| `phynite_api_key` | Encrypted API key |
| `phynite_last_sync` | Timestamp of last sync |
| `phynite_last_sync_count` | Posts synced in last sync |
| `phynite_sync_state` | Current bulk sync state |
| `phynite_sync_queue` | Pending sync queue |
| `phynite_retry_queue` | Failed sync retry queue |
| `phynite_health_status` | Last health check result |
| `phynite_debug_log` | Debug log entries |

Transients used:
- `phynite_rate_limit` - Rate limit tracking
- `phynite_last_sync_{post_id}` - Per-post debouncing

## Cron Jobs

| Hook | Schedule | Description |
|------|----------|-------------|
| `phynite_process_queue` | On-demand | Process sync queue |
| `phynite_process_retry_queue` | Every 5 min | Process retry queue |
| `phynite_health_check` | Hourly | Validate API connection |
| `phynite_process_sync_batch` | On-demand | Bulk sync batches |

## Creating Custom Extractors

To add support for a new plugin, create a new extractor class:

```php
// In your theme or plugin
class Phynite_Custom_Extractor {
    public function is_active() {
        return class_exists( 'Custom_Plugin' );
    }

    public function extract( $post_id ) {
        if ( ! $this->is_active() ) {
            return null;
        }

        return array(
            'custom_field' => get_post_meta( $post_id, 'custom_key', true ),
        );
    }
}

// Register with the sync system
add_filter( 'phynite_extractors', function( $extractors ) {
    $extractors['custom'] = new Phynite_Custom_Extractor();
    return $extractors;
});
```

## Performance Considerations

The plugin is designed for resource-constrained shared hosting:

1. **Memory**: Batch processing limits to 25 posts at a time
2. **CPU**: Regex-based link extraction instead of DOM parsing
3. **Database**: Minimal queries, no custom tables
4. **Network**: Rate limiting prevents API overload
5. **Cron**: Background processing prevents request blocking
